├── .gitignore
├── misc
├── screenshot.png
├── intel-power-control.png
├── intel-power-control.sudoers
├── intel-power-control.desktop
└── intel-power-control.svg
├── .pre-commit-config.yaml
├── pyproject.toml
├── .github
└── workflows
│ ├── code-quality.yml
│ └── publish-to-test-pypi.yml
├── Makefile
├── setup.py
├── intel-power-control-setup
├── README.md
├── intel-power-control-helper.c
├── LICENSE
└── intel-power-control
/.gitignore:
--------------------------------------------------------------------------------
1 | *~
2 | /intel-power-control-helper
3 | /.eggs/
4 | /build/
5 | /dist/
6 | /*.egg-info/
7 |
--------------------------------------------------------------------------------
/misc/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jmechnich/intel-power-control/HEAD/misc/screenshot.png
--------------------------------------------------------------------------------
/misc/intel-power-control.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jmechnich/intel-power-control/HEAD/misc/intel-power-control.png
--------------------------------------------------------------------------------
/misc/intel-power-control.sudoers:
--------------------------------------------------------------------------------
1 | # /etc/sudoers.d/intel-power-control
2 | %sudo ALL=(ALL) NOPASSWD: /usr/local/bin/intel-power-control-helper
3 |
--------------------------------------------------------------------------------
/misc/intel-power-control.desktop:
--------------------------------------------------------------------------------
1 | [Desktop Entry]
2 | Name=intel-power-control
3 | Exec=intel-power-control
4 | Terminal=false
5 | Type=Application
6 | Icon=intel-power-control
7 | Comment=GPU power management for Intel hardware on Linux
8 | Categories=HardwareSettings;Qt;System;Utility;
9 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | fail_fast: true
2 |
3 | repos:
4 | - repo: https://github.com/ambv/black
5 | rev: 22.3.0
6 | hooks:
7 | - id: black
8 | args: [--diff, --check]
9 |
10 | - repo: https://github.com/pre-commit/mirrors-pylint
11 | rev: v3.0.0a3
12 | hooks:
13 | - id: pylint
14 | args: [--disable=all, --enable=unused-import]
15 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=42", "wheel", "setuptools_scm[toml]>=3.4"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [tool.setuptools_scm]
6 | local_scheme = "no-local-version"
7 |
8 | [tool.black]
9 | line-length = 80
10 | target-version = ['py38']
11 | include = '''
12 | (
13 | \.pyi?$
14 | | intel-power-control$
15 | | intel-power-control-setup$
16 | )
17 | '''
18 |
--------------------------------------------------------------------------------
/.github/workflows/code-quality.yml:
--------------------------------------------------------------------------------
1 | name: Python linting and formatting checks
2 | on: [pull_request]
3 |
4 | jobs:
5 | build:
6 | runs-on: ubuntu-latest
7 | name: Python linting and formatting checks
8 | steps:
9 | - uses: actions/checkout@v2
10 | - uses: actions/setup-python@v2
11 | with:
12 | python-version: 3.x
13 | - run: pip install --upgrade pip
14 | - run: pip install black==v23.10.1 pylint==v3.0.2 mypy==v1.6.1
15 | - run: black --diff --check .
16 | - run: pylint --disable=all --enable=unused-import setup.py intel-power-control intel-power-control-setup
17 |
--------------------------------------------------------------------------------
/.github/workflows/publish-to-test-pypi.yml:
--------------------------------------------------------------------------------
1 | name: Publish Python 🐍 distributions 📦 to PyPI and TestPyPI
2 |
3 | on: push
4 |
5 | jobs:
6 | build-n-publish:
7 | name: Build and publish Python 🐍 distributions 📦 to PyPI and TestPyPI
8 | runs-on: ubuntu-20.04
9 | steps:
10 | - uses: actions/checkout@master
11 | - name: Set up Python 3.10
12 | uses: actions/setup-python@v3
13 | with:
14 | python-version: "3.10"
15 | - name: Install pypa/build
16 | run: >-
17 | python -m
18 | pip install
19 | build
20 | --user
21 | - name: Build a binary wheel and a source tarball
22 | run: >-
23 | python -m
24 | build
25 | --sdist
26 | --wheel
27 | --outdir dist/
28 | .
29 | - name: Publish distribution 📦 to Test PyPI
30 | uses: pypa/gh-action-pypi-publish@release/v1
31 | with:
32 | password: ${{ secrets.test_pypi_password }}
33 | repository_url: https://test.pypi.org/legacy/
34 | skip_existing: true
35 | - name: Publish distribution 📦 to PyPI
36 | if: startsWith(github.ref, 'refs/tags')
37 | uses: pypa/gh-action-pypi-publish@release/v1
38 | with:
39 | password: ${{ secrets.pypi_password }}
40 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | override CFLAGS += -Wall #-DDEBUG
2 |
3 | TARGET = intel-power-control
4 |
5 | PREFIX ?= /usr/local
6 | BINDIR = $(PREFIX)/bin
7 | DATADIR = $(PREFIX)/share
8 |
9 | all: $(TARGET)-helper
10 |
11 |
12 | install: all
13 | install -d $(BINDIR)
14 | install -m 755 $(TARGET) $(BINDIR)
15 | install -m 755 $(TARGET)-setup $(BINDIR)
16 | ifeq (0, $(shell id -u))
17 | install -m 4755 $(TARGET)-helper $(BINDIR)
18 | else
19 | $(warning Cannot install helper as SUID as we are not root)
20 | install -m 755 $(TARGET)-helper $(BINDIR)
21 | endif
22 | $(install_helper)
23 | install -d $(DATADIR)/$(TARGET)
24 | install -m 644 -t $(DATADIR)/$(TARGET) misc/intel-power-control.png
25 | install -d $(DATADIR)/applications
26 | install -m 644 -t $(DATADIR)/applications \
27 | misc/intel-power-control.desktop
28 | install -d $(DATADIR)/icons/hicolor/32x32
29 | install -m 644 -t $(DATADIR)/icons/hicolor/32x32 \
30 | misc/intel-power-control.png
31 | install -d $(DATADIR)/icons/hicolor/scalable
32 | install -m 644 -t $(DATADIR)/icons/hicolor/scalable \
33 | misc/intel-power-control.svg
34 |
35 | uninstall:
36 | rm -f $(BINDIR)/$(TARGET)
37 | rm -f $(BINDIR)/$(TARGET)-setup
38 | rm -f $(BINDIR)/$(TARGET)-helper
39 | rm -rf $(DATADIR)/$(TARGET)
40 | rm -f $(DATADIR)/applications/intel-power-control.desktop
41 | rm -f $(DATADIR)/icons/hicolor/32x32/intel-power-control.png
42 | rm -f $(DATADIR)/icons/hicolor/scalable/intel-power-control.svg
43 |
44 | clean:
45 | rm -f $(TARGET)-helper *~
46 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import os
4 | import shutil
5 | import subprocess
6 |
7 | from setuptools import setup
8 | from setuptools.command.install import install
9 |
10 |
11 | class CustomInstall(install):
12 | """Custom handler for the 'install' command."""
13 |
14 | def run(self):
15 | target = "intel-power-control-helper"
16 | targetdir = self.install_scripts
17 |
18 | subprocess.check_call(f"cc -Wall {target}.c -o {target}", shell=True)
19 | os.makedirs(targetdir, exist_ok=True)
20 | shutil.copy(target, targetdir)
21 | os.chmod(os.path.join(targetdir, target), 0o755)
22 |
23 | super().run()
24 |
25 |
26 | with open("README.md", "r") as fh:
27 | long_description = fh.read()
28 |
29 | setup(
30 | name="intel-power-control",
31 | author="Joerg Mechnich",
32 | author_email="joerg.mechnich@gmail.com",
33 | license="GNU GPLv3",
34 | description="GPU power management for Intel hardware on Linux",
35 | long_description=long_description,
36 | long_description_content_type="text/markdown",
37 | url="https://github.com/jmechnich/intel-power-control",
38 | use_scm_version={"local_scheme": "no-local-version"},
39 | setup_requires=["setuptools_scm"],
40 | install_requires=["PyQt6"],
41 | scripts=["intel-power-control", "intel-power-control-setup"],
42 | data_files=[
43 | ("share/applications", ["misc/intel-power-control.desktop"]),
44 | ("share/icons/hicolor/32x32/apps", ["misc/intel-power-control.png"]),
45 | ("share/icons/hicolor/scalable/apps", ["misc/intel-power-control.svg"]),
46 | ],
47 | classifiers=[
48 | "Programming Language :: Python :: 3",
49 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
50 | "Operating System :: POSIX :: Linux",
51 | "Environment :: X11 Applications :: Qt",
52 | ],
53 | python_requires=">=3.6",
54 | cmdclass={"install": CustomInstall},
55 | )
56 |
--------------------------------------------------------------------------------
/intel-power-control-setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import os
4 | import stat
5 | import sys
6 |
7 |
8 | def setup_suid(helper, statinfo):
9 | print("Using SUID method")
10 | if statinfo.st_uid != 0:
11 | print("Changing ownership to root:root")
12 | os.chown(helper, 0, 0)
13 | if stat.S_IMODE(statinfo.st_mode) != 0o4755:
14 | print("Setting SUID bit")
15 | os.chmod(helper, 0o4755)
16 |
17 |
18 | def setup_sudo(helper):
19 | print("Using sudo method")
20 | sudodir = "/etc/sudoers.d"
21 | if not os.path.exists(sudodir):
22 | print(f"{sudodir} does not exist, is sudo installed?")
23 | sys.exit(1)
24 | sudofile = os.path.join(sudodir, "intel-power-control")
25 | with open(sudofile, "w") as f:
26 | f.write(f"%sudo ALL=(ALL) NOPASSWD: {helper}")
27 |
28 | print(
29 | f"Successfully installed {sudofile},"
30 | " make sure user is member of group sudo"
31 | )
32 |
33 |
34 | installdir = os.path.dirname(__file__)
35 | helper = os.path.join(installdir, "intel-power-control-helper")
36 |
37 | if not os.path.exists(helper):
38 | print(f"Could not find intel-power-control-helper in {installdir}")
39 | sys.exit(1)
40 |
41 | statinfo = os.stat(helper)
42 | if statinfo.st_uid == 0 and stat.S_IMODE(statinfo.st_mode) == 0o4755:
43 | print("intel-power-control-helper is already set up correctly")
44 | sys.exit(0)
45 |
46 | if os.geteuid() != 0:
47 | print("Please run this script with root privileges")
48 | sys.exit(1)
49 |
50 | dirstat = os.stat(os.path.dirname(helper))
51 | if dirstat.st_uid != 0 or dirstat.st_gid != 0:
52 | print(
53 | "Installation directory does not belong to root,"
54 | " assuming user installation"
55 | )
56 | setup_suid(helper, statinfo)
57 | else:
58 | print("Installation directory belongs to root, choose strategy:")
59 | print("1: suid")
60 | print("2: sudo")
61 | ans = input("Choose 1 or 2, Ctrl-C to abort:").strip()
62 | if ans == "1":
63 | setup_suid(helper, statinfo)
64 | elif ans == "2":
65 | setup_sudo(helper)
66 | else:
67 | print("Aborting")
68 | sys.exit(1)
69 |
70 | sys.exit(0)
71 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://pypi.org/project/intel-power-control/)
2 | [](https://pypi.org/project/intel-power-control/)
3 | [](https://pypi.org/project/intel-power-control/)
4 | [](https://pypi.org/project/intel-power-control/)
5 |
6 | # intel-power-control
7 |
8 | GPU power management for Intel hardware on Linux
9 |
10 | ## Functionality
11 | - Displays cpu online states, temperatures and gpu clock settings.
12 | - Toggle cpu online states
13 | - Throttling of gpu clock (also automatic)
14 | - intel-power-control-helper changes settings as root user
15 |
16 | ## Requirements
17 | - C compiler (i.e. gcc)
18 | - PyQt 6.x
19 |
20 | ## Installation from PyPi (recommended)
21 |
22 | ```
23 | # system-wide
24 | sudo pip install intel-power-control
25 | echo "%sudo ALL=(ALL) NOPASSWD: /usr/local/bin/intel-power-control-helper" | \
26 | sudo tee /etc/sudoers.d/intel-power-control
27 |
28 | # OR as user
29 | pip install intel-power-control --user
30 | sudo chown root:root $HOME/.local/bin/intel-power-control-helper
31 | sudo chmod 4755 $HOME/.local/bin/intel-power-control-helper
32 |
33 | # run program
34 | intel-power-control
35 | ```
36 |
37 | ## Installation from source
38 |
39 | **WARNING**: using this method, you have to take care of installing the
40 | required dependencies yourself (i.e. install PyQt using your distribution's
41 | package manager).
42 |
43 | ```
44 | git clone https://github.com/jmechnich/intel-power-control.git
45 |
46 | # compile
47 | cd intel-power-control
48 | make
49 |
50 | # install to /usr/local
51 | sudo make install
52 |
53 | # OR install to local prefix
54 | make install PREFIX=$HOME/.local
55 | sudo chown root:root $HOME/.local/bin/intel-power-control-helper
56 | sudo chmod 4755 $HOME/.local/bin/intel-power-control-helper
57 |
58 | # run program
59 | intel-power-control
60 | ```
61 |
62 | ## Checking and fixing intel-power-control-helper permissions
63 |
64 | The script `intel-power-control-setup` is supplied to set up the
65 | permissions for `intel-power-control-helper` correctly after
66 | installation.
67 |
68 | ## Changing the look and feel
69 |
70 | Use the `-style` commandline option to select a different
71 | theme. Available themes can be listed by calling the application with
72 | an invalid style argument, e.g. `-style help`.
73 |
74 | ## Screenshots
75 |
76 | 
77 |
--------------------------------------------------------------------------------
/misc/intel-power-control.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | ]>
13 |
47 |
--------------------------------------------------------------------------------
/intel-power-control-helper.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | const char* drmbasepath = "/sys/class/drm";
10 | const char* cpubasepath = "/sys/devices/system/cpu";
11 | const char* backlightpath = "/sys/class/backlight/intel_backlight";
12 | const size_t bufsize = 10;
13 |
14 | int toggleCPU( const char* cpu)
15 | {
16 | #ifdef DEBUG
17 | printf("call toggleCPU(%s)\n", cpu);
18 | #endif
19 | const char* fn = "online";
20 |
21 | size_t buflen = strlen(cpubasepath) + strlen(cpu) + strlen(fn) + 3;
22 | char* buf = calloc( sizeof(char), buflen);
23 | snprintf( buf, buflen, "%s/%s/%s", cpubasepath, cpu, fn);
24 | FILE* f1 = fopen( buf, "r");
25 | if( !f1)
26 | {
27 | printf( "Could not open '%s'\n", buf);
28 | free( buf);
29 | return 1;
30 | }
31 | char state = 0;
32 | size_t read = fread( &state, sizeof(char), 1, f1);
33 | fclose(f1);
34 |
35 | if( read == 0)
36 | {
37 | printf( "Could not read from '%s'\n", buf);
38 | free( buf);
39 | return 1;
40 | }
41 |
42 | char newState = (char)(((int)'0')+(((int)(state-'0')+1)%2));
43 | FILE* f2 = fopen( buf, "w");
44 | if( !f2)
45 | {
46 | printf( "Could not open '%s'\n", buf);
47 | free( buf);
48 | return 1;
49 | }
50 | size_t written = fwrite( &newState, sizeof(char), 1, f2);
51 |
52 | fclose( f2);
53 | free( buf);
54 |
55 | if( written != 1)
56 | {
57 | printf( "Error writing byte to file, got %lu\n", written);
58 | return 1;
59 | }
60 |
61 | return 0;
62 | }
63 |
64 | int setMHz( const char* gpu, const char* fn, const char* val)
65 | {
66 | #ifdef DEBUG
67 | printf("call setMHz(%s,%s,%s)\n", gpu, fn, val);
68 | #endif
69 | size_t buflen = strlen(drmbasepath) + strlen(gpu) + strlen(fn) + 3;
70 | char* buf = calloc( sizeof(char), buflen);
71 | snprintf( buf, buflen, "%s/%s/%s", drmbasepath, gpu, fn);
72 | FILE* f = fopen( buf, "w");
73 | if( !f)
74 | {
75 | printf( "Could not open '%s'\n", buf);
76 | free( buf);
77 | return 1;
78 | }
79 |
80 | size_t written = fwrite( val, sizeof(char), strlen(val), f);
81 |
82 | fclose( f);
83 | free( buf);
84 |
85 | if( written != strlen(val))
86 | {
87 | printf( "Error writing %lu bytes to file, got %lu\n", strlen(val), written);
88 | return 1;
89 | }
90 |
91 | return 0;
92 | }
93 |
94 | int setBrightness( const char* val)
95 | {
96 | const char* fn = "brightness";
97 | size_t buflen = strlen(backlightpath) + strlen(fn) + 2;
98 | char* buf = calloc( sizeof(char), buflen);
99 | snprintf( buf, buflen, "%s/%s", backlightpath, fn);
100 | FILE* f = fopen( buf, "w");
101 | if( !f)
102 | {
103 | printf( "Could not open '%s'\n", buf);
104 | free( buf);
105 | return 1;
106 | }
107 |
108 | size_t written = fwrite( val, sizeof(char), strlen(val), f);
109 |
110 | fclose( f);
111 | free( buf);
112 |
113 | if( written != strlen(val))
114 | {
115 | printf( "Error writing %lu bytes to file, got %lu\n", strlen(val), written);
116 | return 1;
117 | }
118 |
119 | return 0;
120 | }
121 |
122 | void checkPath(const char* arg, const char* val)
123 | {
124 | if(strchr(val,'.')!=0) goto ABORT;
125 | if(strchr(val,'/')!=0) goto ABORT;
126 |
127 | return;
128 |
129 | ABORT:
130 | printf("invalid value for argument '%s': %s\n", arg, val);
131 | abort();
132 | }
133 |
134 | void checkNumber(const char* arg, const char* val)
135 | {
136 | char* endptr = NULL;
137 |
138 | /* check first if value starts with digit */
139 | if(!isdigit(*val)) goto ABORT;
140 |
141 | /* try conversion and check errno */
142 | errno = 0;
143 | strtol(val,&endptr,10);
144 | if(errno != 0) goto ABORT;
145 |
146 | /* check if conversion ended prematurely */
147 | if(strlen(val)!=(endptr-val)) goto ABORT;
148 |
149 | return;
150 |
151 | ABORT:
152 | printf("invalid value for argument '%s': %s\n", arg, val);
153 | abort();
154 | }
155 |
156 | void help()
157 | {
158 | printf("usage: intel-power-manager-helper options\n");
159 | printf(" -h --help print this text and exit\n");
160 | printf(" -c --cpu N toggle CPU state for CPU N\n");
161 | printf(" -g --gpu N select GPU N\n");
162 | printf(" -l --min N set minimum GPU clock to N (requires -g)\n");
163 | printf(" -u --max N set maximum GPU clock to N (requires -g)\n");
164 | printf(" -s --bst N set boost GPU clock to N (requires -g)\n");
165 | printf(" -b --brightness N set brightness to N\n");
166 | }
167 |
168 | int main( int argc, char** argv)
169 | {
170 | uid_t euid = geteuid();
171 | if(euid != 0) {
172 | printf("intel-power-control-helper: insufficient privileges\n");
173 | return 1;
174 | }
175 |
176 | const char* minfn = "gt_min_freq_mhz";
177 | const char* maxfn = "gt_max_freq_mhz";
178 | const char* bstfn = "gt_boost_freq_mhz";
179 |
180 | char cpu[bufsize+1], gpu[bufsize+1], min[bufsize+1], max[bufsize+1],
181 | bst[bufsize+1], bn[bufsize+1];
182 | memset( cpu, 0, bufsize+1);
183 | memset( gpu, 0, bufsize+1);
184 | memset( min, 0, bufsize+1);
185 | memset( max, 0, bufsize+1);
186 | memset( bst, 0, bufsize+1);
187 | memset( bn, 0, bufsize+1);
188 |
189 | int setFreq = 0;
190 |
191 | int c;
192 | while (1)
193 | {
194 |
195 | static struct option long_options[] =
196 | {
197 | /* These options set a flag. */
198 | {"cpu", required_argument, 0, 'c'},
199 | {"gpu", required_argument, 0, 'g'},
200 | {"min", required_argument, 0, 'l'},
201 | {"max", required_argument, 0, 'u'},
202 | {"bst", required_argument, 0, 's'},
203 | {"brightness", required_argument, 0, 'b'},
204 | {"help", no_argument, 0, 'h'},
205 | {0, 0, 0, 0}
206 | };
207 | /* getopt_long stores the option index here. */
208 | int option_index = 0;
209 | c = getopt_long (argc, argv, "c:g:l:u:s:b:h",
210 | long_options, &option_index);
211 |
212 | /* Detect the end of the options. */
213 | if (c == -1)
214 | break;
215 |
216 | switch (c)
217 | {
218 | case 'c':
219 | #ifdef DEBUG
220 | printf("cpu: %s\n", optarg);
221 | #endif
222 | strncpy(cpu, optarg, bufsize);
223 | checkPath("cpu",cpu);
224 | if( toggleCPU( cpu) != 0) abort();
225 | break;
226 | case 'g':
227 | #ifdef DEBUG
228 | printf("gpu: %s\n", optarg);
229 | #endif
230 | strncpy(gpu, optarg, bufsize);
231 | checkPath("gpu",gpu);
232 | break;
233 | case 'l':
234 | #ifdef DEBUG
235 | printf("minimum: %s\n", optarg);
236 | #endif
237 | strncpy(min, optarg, bufsize);
238 | checkNumber("min", min);
239 | setFreq = 1;
240 | break;
241 | case 'u':
242 | #ifdef DEBUG
243 | printf("maximum: %s\n", optarg);
244 | #endif
245 | strncpy(max, optarg, bufsize);
246 | checkNumber("max", max);
247 | setFreq = 1;
248 | break;
249 | case 's':
250 | #ifdef DEBUG
251 | printf("boost: %s\n", optarg);
252 | #endif
253 | strncpy(bst, optarg, bufsize);
254 | checkNumber("bst", bst);
255 | setFreq = 1;
256 | break;
257 | case 'b':
258 | #ifdef DEBUG
259 | printf("set brightness: %s\n", optarg);
260 | #endif
261 | strncpy(bn, optarg, bufsize);
262 | checkNumber("brightness", bn);
263 | if( setBrightness(bn) != 0) abort();
264 | break;
265 | case 'h':
266 | help();
267 | exit(0);
268 | break;
269 | case '?':
270 | abort();
271 | break;
272 | default:
273 | #ifdef DEBUG
274 | printf("Unknown command line flag '%c'\n", c);
275 | #endif
276 | abort();
277 | }
278 | }
279 |
280 | if(setFreq)
281 | {
282 | if( !*gpu )
283 | {
284 | printf( "Required argument missing: -g/--gpu\n");
285 | abort();
286 | }
287 | if( *min && setMHz( gpu, minfn, min) != 0) abort();
288 | if( *max && setMHz( gpu, maxfn, max) != 0) abort();
289 | if( *bst && setMHz( gpu, bstfn, bst) != 0) abort();
290 | exit(0);
291 | }
292 |
293 | return 0;
294 | }
295 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/intel-power-control:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8; mode: python -*-
3 |
4 | import argparse
5 | import os
6 | import re
7 | import subprocess
8 | import sys
9 |
10 | from enum import IntEnum
11 |
12 | from PyQt6.QtCore import (
13 | Qt,
14 | QPoint,
15 | QSettings,
16 | QSignalMapper,
17 | QTimer,
18 | pyqtSlot,
19 | )
20 | from PyQt6.QtGui import (
21 | QColor,
22 | QColorConstants,
23 | QFont,
24 | QGuiApplication,
25 | QIcon,
26 | QPainter,
27 | QPixmap,
28 | )
29 | from PyQt6.QtWidgets import (
30 | QApplication,
31 | QCheckBox,
32 | QComboBox,
33 | QGridLayout,
34 | QGroupBox,
35 | QHBoxLayout,
36 | QLabel,
37 | QMenu,
38 | QPushButton,
39 | QSlider,
40 | QSpinBox,
41 | QStatusBar,
42 | QSystemTrayIcon,
43 | QVBoxLayout,
44 | QWidget,
45 | )
46 |
47 |
48 | def which(program):
49 | def is_exe(fpath):
50 | return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
51 |
52 | fpath, fname = os.path.split(program)
53 | if fpath:
54 | if is_exe(program):
55 | return program
56 | else:
57 | for path in os.environ["PATH"].split(os.pathsep):
58 | path = path.strip('"')
59 | exe_file = os.path.join(path, program)
60 | if is_exe(exe_file):
61 | return exe_file
62 |
63 | return None
64 |
65 | def hexColor(color):
66 | return f"#{hex(color.rgb())[2:]}"
67 |
68 | class Cols(IntEnum):
69 | CUR = 0
70 | MIN = 1
71 | MAX = 2
72 | BST = 3
73 |
74 |
75 | class Vars(IntEnum):
76 | MIN = 0
77 | MAX = 1
78 | BST = 2
79 |
80 |
81 | class IntelPowerControl(QWidget):
82 | update_interval = 2000
83 | cpubasepath = "/sys/devices/system/cpu"
84 | thermalbasepath = "/sys/class/thermal"
85 | gpubasepath = "/sys/class/drm"
86 | backlightpath = "/sys/class/backlight/intel_backlight"
87 | gpuclkdiv = 50
88 | suidhelper = None
89 | msgtimeout = 2000
90 |
91 | def __init__(self, parent=None):
92 | super(IntelPowerControl, self).__init__(parent)
93 | self.textColor = QGuiApplication.palette().text().color()
94 | self.checkHelper()
95 | self.systray = None
96 | self.systrayCycle = 0
97 | self.layout = QVBoxLayout()
98 | self.initCPUs()
99 | self.initThermals()
100 | self.initGPUs()
101 | self.initBrightness()
102 | self.initOptions()
103 | self.layout.addStretch()
104 | self.setLayout(self.layout)
105 | self.updateAll()
106 | self.timer = QTimer()
107 | self.timer.setInterval(self.update_interval)
108 | self.timer.timeout.connect(self.updateAll)
109 | self.timer.start()
110 | if self.showsystray.isChecked():
111 | self.systrayTimer = QTimer()
112 | self.systrayTimer.setInterval(1000)
113 | self.systrayTimer.timeout.connect(self.checkSystray)
114 | self.systrayTimer.start()
115 | self.setFixedSize(self.sizeHint())
116 | sr = QGuiApplication.primaryScreen().geometry()
117 | self.move(
118 | sr.center() - QPoint(int(self.width() / 2), int(self.height() / 2))
119 | )
120 | if not self.suidhelper:
121 | self.status.showMessage(
122 | "Could not find suid helper, disabling sliders"
123 | )
124 | if not (self.starthidden.isEnabled() and self.starthidden.isChecked()):
125 | self.show()
126 |
127 | def checkHelper(self):
128 | suidhelper = which("intel-power-control-helper")
129 | if not suidhelper:
130 | return
131 |
132 | for args in [
133 | [suidhelper],
134 | ["/usr/bin/sudo", "-n", suidhelper],
135 | ]:
136 | ret = subprocess.run(args, capture_output=True)
137 | if ret.returncode == 0:
138 | self.suidhelper = args
139 | return
140 |
141 | print(
142 | f"suidhelper was found at {suidhelper} but cannot be executed"
143 | " with root privileges. Either add a sudo rule or set SUID bit."
144 | )
145 |
146 | def checkSystray(self):
147 | if self.systray:
148 | self.systrayTimer.stop()
149 | self.systrayTimer = None
150 | return
151 | if not QSystemTrayIcon.isSystemTrayAvailable():
152 | return
153 | self.createSystray()
154 |
155 | def closeEvent(self, ev):
156 | if self.systray and self.minimizetray.isChecked():
157 | ev.ignore()
158 | self.hide()
159 | else:
160 | ev.accept()
161 |
162 | def initCPUs(self):
163 | self.cpulabels = {}
164 | box = QGroupBox("CPU State")
165 | layout = QHBoxLayout()
166 | if not os.path.isdir(self.cpubasepath):
167 | l = QLabel(f"No cpu info at '{self.cpubasepath}'")
168 | layout.addWidget(l)
169 | else:
170 | cpus = [
171 | c for c in os.listdir(self.cpubasepath) if re.match(r"^cpu\d+$", c)
172 | ]
173 | self.cpumapper = QSignalMapper()
174 | for i in natural_sort(cpus):
175 | l = QPushButton(i)
176 | if not self.suidhelper:
177 | l.setDisabled(True)
178 | self.cpumapper.setMapping(l, i)
179 | l.clicked.connect(self.cpumapper.map)
180 | layout.addWidget(l)
181 | self.cpulabels[i] = (l, "green")
182 | self.cpumapper.mappedString.connect(self.toggleCPU)
183 | box.setLayout(layout)
184 | self.layout.addWidget(box)
185 |
186 | def initThermals(self):
187 | self.thermals = {}
188 | box = QGroupBox("Thermal Zones")
189 | if not os.path.isdir(self.thermalbasepath):
190 | layout = QHBoxLayout()
191 | l = QLabel(f"No thermal zone info at '{self.thermalbasepath}'")
192 | layout.addWidget(l)
193 | else:
194 | layout = QGridLayout()
195 | thermals = [
196 | t.strip()
197 | for t in os.listdir(self.thermalbasepath)
198 | if t.startswith("thermal_zone")
199 | ]
200 | layout.addWidget(QLabel("Temperature"), 0, 1)
201 | layout.addWidget(QLabel("Type"), 0, 2)
202 | i = 1
203 | for t in sorted(thermals):
204 | layout.addWidget(QLabel(t), i, 0)
205 | tlabel = QLabel("0°C")
206 | layout.addWidget(tlabel, i, 1)
207 | typename = self.readValue(
208 | os.path.join(self.thermalbasepath, t, "type")
209 | )
210 | layout.addWidget(QLabel(typename), i, 2)
211 | self.thermals[t] = (tlabel, 0, typename)
212 | i += 1
213 | layout.setColumnStretch(2, 1)
214 | box.setLayout(layout)
215 | self.layout.addWidget(box)
216 |
217 | def initGPUs(self):
218 | self.gpulabels = {}
219 | self.gpusliders = {}
220 | box = QGroupBox("GPU Clock")
221 | if not os.path.isdir(self.thermalbasepath):
222 | layout = QHBoxLayout()
223 | l = QLabel(f"No gpu info at '{self.gpubasepath}'")
224 | layout.addWidget(l)
225 | else:
226 | layout = QGridLayout()
227 | gpulabels = [
228 | g for g in os.listdir(self.gpubasepath) if re.match(r"^card\d$", g)
229 | ]
230 | self.gpuminmapper = QSignalMapper()
231 | self.gpumaxmapper = QSignalMapper()
232 | self.gpuboostmapper = QSignalMapper()
233 | layout.addWidget(QLabel("Current"), 0, Cols.CUR + 1)
234 | layout.addWidget(QLabel("Minimum"), 0, Cols.MIN + 1)
235 | layout.addWidget(QLabel("Maximum"), 0, Cols.MAX + 1)
236 | layout.addWidget(QLabel("Boost"), 0, Cols.BST + 1)
237 | row = 1
238 | for card in sorted(gpulabels):
239 | dirname = os.path.join(self.gpubasepath, card)
240 | # check if card vendor is Intel
241 | with open(os.path.join(dirname, "device", "vendor")) as f:
242 | vendor = f.readline().strip()
243 | if vendor != "0x8086":
244 | continue
245 | # check for minimal control file availability
246 | if not os.path.exists(os.path.join(dirname, "gt_cur_freq_mhz")):
247 | continue
248 | if not os.path.exists(os.path.join(dirname, "gt_min_freq_mhz")):
249 | continue
250 | if not os.path.exists(os.path.join(dirname, "gt_max_freq_mhz")):
251 | continue
252 | if not os.path.exists(os.path.join(dirname, "gt_boost_freq_mhz")):
253 | continue
254 | layout.addWidget(QLabel(card), row, 0)
255 | l0 = QLabel("0 MHz")
256 | layout.addWidget(l0, row, Cols.CUR + 1)
257 | l1 = QLabel("0 MHz")
258 | layout.addWidget(l1, row, Cols.MIN + 1)
259 | l2 = QLabel("0 MHz")
260 | layout.addWidget(l2, row, Cols.MAX + 1)
261 | l3 = QLabel("0 MHz")
262 | layout.addWidget(l3, row, Cols.BST + 1)
263 | self.gpulabels[card] = ((l0, 0), (l1, 0), (l2, 0), (l3, 0))
264 | gts = [g for g in os.listdir(dirname) if g.startswith("gt_RP")]
265 | if not len(gts):
266 | continue
267 |
268 | states = {}
269 | for g in gts:
270 | state = re.match(r"gt_(RP[n\d])_freq_mhz", g).groups()[0]
271 | states[state] = self.readValue(os.path.join(dirname, g))
272 | rps = sorted(states.keys())
273 | rps_max = int(states[rps[0]])
274 | rps_min = int(states[rps[-1]])
275 | row += 1
276 | minslider = QSlider(Qt.Orientation.Horizontal)
277 | minslider.setRange(
278 | round(rps_min / self.gpuclkdiv), round(rps_max / self.gpuclkdiv)
279 | )
280 | minslider.setTickPosition(QSlider.TickPosition.TicksBelow)
281 | minslider.setTickInterval(1)
282 | minslider.setPageStep(1)
283 | if not self.suidhelper:
284 | minslider.setDisabled(True)
285 | self.gpuminmapper.setMapping(minslider, card)
286 | minslider.valueChanged.connect(self.gpuminmapper.map)
287 | layout.addWidget(minslider, row, 1, 1, len(Cols))
288 | row += 1
289 | maxslider = QSlider(Qt.Orientation.Horizontal)
290 | maxslider.setRange(
291 | round(rps_min / self.gpuclkdiv), round(rps_max / self.gpuclkdiv)
292 | )
293 | maxslider.setTickPosition(QSlider.TickPosition.TicksBelow)
294 | maxslider.setTickInterval(1)
295 | maxslider.setPageStep(1)
296 | if not self.suidhelper:
297 | maxslider.setDisabled(True)
298 | self.gpumaxmapper.setMapping(maxslider, card)
299 | maxslider.valueChanged.connect(self.gpumaxmapper.map)
300 | layout.addWidget(maxslider, row, 1, 1, len(Cols))
301 | row += 1
302 | boostslider = QSlider(Qt.Orientation.Horizontal)
303 | boostslider.setRange(
304 | round(rps_min / self.gpuclkdiv), round(rps_max / self.gpuclkdiv)
305 | )
306 | boostslider.setTickPosition(QSlider.TickPosition.TicksBelow)
307 | boostslider.setTickInterval(1)
308 | boostslider.setPageStep(1)
309 | if not self.suidhelper:
310 | boostslider.setDisabled(True)
311 | self.gpuboostmapper.setMapping(boostslider, card)
312 | boostslider.valueChanged.connect(self.gpuboostmapper.map)
313 | resetBtn = QPushButton("Reset")
314 | resetBtn.clicked.connect(
315 | lambda: (
316 | minslider.setValue(minslider.minimum()),
317 | maxslider.setValue(maxslider.maximum()),
318 | boostslider.setValue(boostslider.maximum()),
319 | )
320 | )
321 | layout.addWidget(resetBtn, row, 0)
322 | layout.addWidget(boostslider, row, 1, 1, len(Cols))
323 | row += 1
324 | self.gpusliders[card] = (minslider, maxslider, boostslider)
325 | self.gpuminmapper.mappedString.connect(self.setMinimumClock)
326 | self.gpumaxmapper.mappedString.connect(self.setMaximumClock)
327 | self.gpuboostmapper.mappedString.connect(self.setBoostClock)
328 | # layout.setColumnStretch(3,1)
329 | layout.setHorizontalSpacing(10)
330 | box.setLayout(layout)
331 | self.layout.addWidget(box)
332 |
333 | def brightnessAvailable(self):
334 | if not os.path.exists(self.backlightpath):
335 | return False
336 | if not os.path.exists(os.path.join(self.backlightpath, "brightness")):
337 | return False
338 | if not os.path.exists(
339 | os.path.join(self.backlightpath, "max_brightness")
340 | ):
341 | return False
342 | return True
343 |
344 | def setBrightness(self):
345 | if not self.brightnessAvailable():
346 | return
347 |
348 | def initBrightness(self):
349 | if not self.brightnessAvailable():
350 | return
351 | brightmax = self.readValue(
352 | os.path.join(self.backlightpath, "max_brightness")
353 | )
354 | box = QGroupBox("Brightness")
355 | layout = QGridLayout()
356 | self.bnslider = QSlider(Qt.Orientation.Horizontal)
357 | if len(brightmax):
358 | self.bnslider.setRange(0, int(int(brightmax) / 100))
359 | else:
360 | self.bnslider.setRange(0, 1)
361 | self.bnslider.setDisabled(True)
362 | self.bnslider.setTickPosition(QSlider.TickPosition.TicksBelow)
363 | self.bnslider.setTickInterval(1)
364 | self.bnslider.setPageStep(1)
365 | self.bnslider.valueChanged.connect(self.setBrightness)
366 | if not self.suidhelper:
367 | self.bnslider.setDisabled(True)
368 | layout.addWidget(self.bnslider, 0, 1, 1, 3)
369 | box.setLayout(layout)
370 | self.layout.addWidget(box)
371 |
372 | def initOptions(self):
373 | self.counter = 0
374 | self.avgtemp = 0.0
375 | self.sumtemp = 0.0
376 | self.max_count = 5
377 | box = QGroupBox("Options")
378 | layout = QGridLayout()
379 | row = 0
380 | layout.addWidget(QLabel("Throttle GPU"), row, 0)
381 | self.throttlegpu = QCheckBox()
382 | if not self.suidhelper:
383 | self.throttlegpu.setDisabled(True)
384 | layout.addWidget(self.throttlegpu, row, 1)
385 | row += 1
386 | layout.addWidget(QLabel("Max. Temperature"), row, 0)
387 | self.maxtemp = QSpinBox()
388 | self.maxtemp.setRange(50, 100)
389 | if not self.suidhelper:
390 | self.maxtemp.setDisabled(True)
391 | layout.addWidget(self.maxtemp, row, 1)
392 | row += 1
393 | layout.addWidget(QLabel("Hysteresis"), row, 0)
394 | self.hyst = QSpinBox()
395 | self.hyst.setRange(-20, 0)
396 | if not self.suidhelper:
397 | self.hyst.setDisabled(True)
398 | layout.addWidget(self.hyst, row, 1)
399 | row += 1
400 | self.tz = QComboBox()
401 | self.tz.addItems(sorted(self.thermals.keys()))
402 | if not self.suidhelper:
403 | self.tz.setDisabled(True)
404 | layout.addWidget(QLabel("Thermal"), row, 0)
405 | layout.addWidget(self.tz, row, 1)
406 | row += 1
407 | layout.addWidget(QLabel("Sync boost to maximum"), row, 0)
408 | self.syncboosttomax = QCheckBox()
409 | layout.addWidget(self.syncboosttomax, row, 1)
410 | row += 1
411 |
412 | layout.addWidget(QLabel("Always On Top"), row, 0)
413 | self.alwaysontop = QCheckBox()
414 | layout.addWidget(self.alwaysontop, row, 1)
415 | row += 1
416 | layout.addWidget(QLabel("Show Systray Icon"), row, 0)
417 | self.showsystray = QCheckBox()
418 | layout.addWidget(self.showsystray, row, 1)
419 | row += 1
420 | layout.addWidget(QLabel("Minimize To Tray"), row, 0)
421 | self.minimizetray = QCheckBox()
422 | self.minimizetray.setEnabled(self.showsystray.isChecked())
423 | layout.addWidget(self.minimizetray, row, 1)
424 | row += 1
425 | layout.addWidget(QLabel("Start Hidden"), row, 0)
426 | self.starthidden = QCheckBox()
427 | self.starthidden.setEnabled(self.showsystray.isChecked())
428 | layout.addWidget(self.starthidden, row, 1)
429 |
430 | layout.setColumnStretch(row, 1)
431 | box.setLayout(layout)
432 | self.layout.addWidget(box)
433 | self.status = QStatusBar(self)
434 | self.layout.addWidget(self.status)
435 | self.loadSettings()
436 |
437 | self.throttlegpu.toggled.connect(self.toggleThrottling)
438 | self.maxtemp.valueChanged.connect(self.setMaxTemp)
439 | self.hyst.valueChanged.connect(self.setHyst)
440 | self.tz.currentIndexChanged.connect(self.setActiveThermal)
441 | self.syncboosttomax.stateChanged.connect(self.toggleSyncBoostToMax)
442 | self.alwaysontop.stateChanged.connect(self.toggleAlwaysOnTop)
443 | self.showsystray.stateChanged.connect(self.toggleSystray)
444 | self.minimizetray.stateChanged.connect(
445 | lambda x: self.updateSettings("minimizetray", int(x))
446 | )
447 | self.starthidden.stateChanged.connect(
448 | lambda x: self.updateSettings("starthidden", int(x))
449 | )
450 |
451 | def updateSettings(self, name, state):
452 | s = QSettings()
453 | s.setValue(name, state)
454 |
455 | def toggleSyncBoostToMax(self, state):
456 | self.syncboosttomax.setChecked(state)
457 | for k, v in self.gpusliders.items():
458 | v[Vars.BST].setEnabled(not state)
459 | self.updateSettings("syncboosttomax", int(state))
460 |
461 | def toggleAlwaysOnTop(self, state):
462 | self.alwaysontop.setChecked(state)
463 | hidden = self.isHidden()
464 | flags = self.windowFlags()
465 | if state:
466 | flags |= Qt.WindowType.WindowStaysOnTopHint
467 | else:
468 | flags &= ~Qt.WindowType.WindowStaysOnTopHint
469 | self.setWindowFlags(flags)
470 | if not hidden:
471 | self.show()
472 | self.updateSettings("alwaysontop", int(state))
473 |
474 | def createSystray(self):
475 | if not QSystemTrayIcon.isSystemTrayAvailable():
476 | return
477 | if self.systray:
478 | self.destroySystray()
479 | self.systray = QSystemTrayIcon()
480 | pix = QPixmap(self.systraySize, self.systraySize)
481 | pix.fill(QColorConstants.Transparent)
482 | self.systray.setIcon(QIcon(pix))
483 | self.systray.activated.connect(self.systrayActivated)
484 | m = QMenu()
485 | m.addAction("Quit", QApplication.quit)
486 | self.systray.setContextMenu(m)
487 | self.systray.show()
488 | self.systrayCycle = 0
489 |
490 | def destroySystray(self):
491 | if not self.systray:
492 | return
493 | self.systray.deleteLater()
494 | self.systray = None
495 |
496 | def toggleSystray(self, state):
497 | self.showsystray.setChecked(state)
498 | self.minimizetray.setEnabled(state)
499 | self.starthidden.setEnabled(state)
500 | if state:
501 | self.createSystray()
502 | else:
503 | self.destroySystray()
504 | self.updateSettings("systray", int(state))
505 |
506 | def systrayActivated(self, reason):
507 | if reason == QSystemTrayIcon.ActivationReason.Trigger:
508 | if self.isHidden():
509 | self.show()
510 | else:
511 | self.hide()
512 |
513 | def loadSettings(self):
514 | self.status.showMessage("Loading settings", self.msgtimeout)
515 | s = QSettings()
516 | self.fgColor = QColor(s.value("fgColor", QColor("#33b0dc")))
517 | self.bgColor = QColor(s.value("bgColor", QColor("#144556")))
518 | self.fontSize = int(s.value("fontsize", 6))
519 | self.systraySize = int(s.value("systraysize", 22))
520 | self.updateSettings("fontsize", self.fontSize)
521 | self.updateSettings("systraysize", self.systraySize)
522 | self.setMaxTemp(int(s.value("maxtemp", 80)))
523 | self.setHyst(int(s.value("hyst", -5)))
524 | self.toggleThrottling(int(s.value("throttlegpu", 1)))
525 | self.setActiveThermal(int(s.value("tzindex", -1)))
526 | self.toggleSyncBoostToMax(int(s.value("syncboosttomax", 0)))
527 | self.toggleAlwaysOnTop(int(s.value("alwaysontop", 0)))
528 | self.toggleSystray(int(s.value("systray", 0)))
529 | self.minimizetray.setChecked(int(s.value("minimizetray", 0)))
530 | self.starthidden.setChecked(int(s.value("starthidden", 0)))
531 |
532 | def setMaxTemp(self, newmax):
533 | self.maxtemp.setValue(newmax)
534 | for k, v in self.thermals.items():
535 | label, val, typename = v
536 | stylesheet = "QLabel { color: %s }" % (
537 | hexColor(self.textColor) if val < newmax else "red"
538 | )
539 | label.setStyleSheet(stylesheet)
540 | self.updateSettings("maxtemp", newmax)
541 |
542 | def setHyst(self, hyst):
543 | self.hyst.setValue(hyst)
544 | self.updateSettings("hyst", hyst)
545 |
546 | def toggleThrottling(self, state):
547 | self.throttlegpu.setChecked(state)
548 | if self.throttlegpu.isEnabled():
549 | self.maxtemp.setEnabled(state)
550 | self.hyst.setEnabled(state)
551 | self.tz.setEnabled(state)
552 | self.updateSettings("throttlegpu", int(state))
553 | if state == False:
554 | for k, v in self.thermals.items():
555 | label, val, typename = v
556 | stylesheet = f"QLabel {{ color: {hexColor(self.textColor)} }}"
557 | label.setStyleSheet(stylesheet)
558 |
559 | def setActiveThermal(self, index):
560 | self.tz.setCurrentIndex(index)
561 | self.updateSettings("tzindex", index)
562 |
563 | def updateAll(self):
564 | self.updateValues()
565 | self.updateGUI()
566 | if self.throttlegpu.isChecked() and self.suidhelper:
567 | self.throttleGPUs()
568 | if self.systray:
569 | self.updateSystray()
570 |
571 | def updateSystray(self):
572 | if not self.systray:
573 | return
574 | self.systray.show()
575 | pix = QPixmap(self.systraySize, self.systraySize)
576 | pix.fill(self.bgColor)
577 | p = QPainter(pix)
578 | f = QFont("Dejavu Sans", self.fontSize)
579 | p.setFont(f)
580 | p.setPen(self.fgColor)
581 | p.drawText(
582 | pix.rect(),
583 | Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter,
584 | "GPU",
585 | )
586 | if self.systrayCycle == 0:
587 | p.drawText(
588 | pix.rect(),
589 | Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignHCenter,
590 | "Temp",
591 | )
592 | elif self.systrayCycle == 1:
593 | p.save()
594 | temp = "..."
595 | if self.avgtemp > 0:
596 | temp = round(self.avgtemp)
597 | if self.maxtemp.isEnabled() and temp >= self.maxtemp.value():
598 | p.setPen(QColorConstants.Red)
599 | p.drawText(
600 | pix.rect(),
601 | Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignHCenter,
602 | "%s\xb0C" % str(temp),
603 | )
604 | p.restore()
605 | elif self.systrayCycle == 2:
606 | p.drawText(
607 | pix.rect(),
608 | Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignHCenter,
609 | "CLK",
610 | )
611 | elif self.systrayCycle == 3:
612 | p.save()
613 | if len(self.gpulabels):
614 | gpu = min(self.gpulabels.values(), key=lambda x: x[0][0].text())
615 | curclock = gpu[Cols.CUR][0].text().split()[0]
616 | maxclock = gpu[Cols.MAX][0].text().split()[0]
617 | if curclock == maxclock:
618 | p.setPen(QColorConstants.Red)
619 | else:
620 | curclock = '-'
621 | p.drawText(
622 | pix.rect(),
623 | Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignHCenter,
624 | "%s" % curclock,
625 | )
626 | p.restore()
627 | self.systrayCycle = (self.systrayCycle + 1) % 4
628 | p.end()
629 | self.systray.setIcon(QIcon(pix))
630 |
631 | def throttleGPUs(self):
632 | if self.counter == 0:
633 | maxtemp = self.maxtemp.value()
634 | hyst = self.hyst.value()
635 | changed = False
636 | if self.avgtemp > maxtemp:
637 | for k, v in self.gpusliders.items():
638 | if (
639 | v[Vars.MAX].isEnabled()
640 | and v[Vars.MAX].value() != v[Vars.MAX].minimum()
641 | ):
642 | v[Vars.MAX].setValue(v[Vars.MAX].value() - 1)
643 | changed = True
644 | if changed:
645 | self.status.showMessage(
646 | "Decreasing GPU clocks: %.1f°C > %d°C"
647 | % (self.avgtemp, maxtemp),
648 | self.msgtimeout,
649 | )
650 | elif self.avgtemp < (maxtemp + hyst):
651 | for k, v in self.gpusliders.items():
652 | if (
653 | v[Vars.MAX].isEnabled()
654 | and v[Vars.MAX].value() != v[Vars.MAX].maximum()
655 | ):
656 | v[Vars.MAX].setValue(v[Vars.MAX].value() + 1)
657 | changed = True
658 | if changed:
659 | self.status.showMessage(
660 | "Increasing GPU clocks: %.1f°C < %d°C"
661 | % (self.avgtemp, maxtemp + hyst),
662 | self.msgtimeout,
663 | )
664 |
665 | def updateValues(self):
666 | # cpus
667 | for k, v in self.cpulabels.items():
668 | online = os.path.join(self.cpubasepath, k, "online")
669 | if os.path.exists(online):
670 | self.cpulabels[k] = (
671 | v[0],
672 | "green" if int(self.readValue(online)) else "red",
673 | )
674 | else:
675 | self.cpulabels[k] = (v[0], "green")
676 |
677 | # thermals
678 | for k, v in self.thermals.items():
679 | path = os.path.join(self.thermalbasepath, k, "temp")
680 | try:
681 | value = int(self.readValue(path)) / 1000
682 | except ValueError:
683 | value = -1
684 |
685 | self.thermals[k] = (
686 | v[0],
687 | value,
688 | v[2],
689 | )
690 |
691 | # gpus
692 | for k, v in self.gpulabels.items():
693 | self.gpulabels[k] = (
694 | (
695 | v[Cols.CUR][0],
696 | int(
697 | self.readValue(
698 | os.path.join(self.gpubasepath, k, "gt_cur_freq_mhz")
699 | )
700 | ),
701 | ),
702 | (
703 | v[Cols.MIN][0],
704 | int(
705 | self.readValue(
706 | os.path.join(self.gpubasepath, k, "gt_min_freq_mhz")
707 | )
708 | ),
709 | ),
710 | (
711 | v[Cols.MAX][0],
712 | int(
713 | self.readValue(
714 | os.path.join(self.gpubasepath, k, "gt_max_freq_mhz")
715 | )
716 | ),
717 | ),
718 | (
719 | v[Cols.BST][0],
720 | int(
721 | self.readValue(
722 | os.path.join(
723 | self.gpubasepath, k, "gt_boost_freq_mhz"
724 | )
725 | )
726 | ),
727 | ),
728 | )
729 | # avg temp
730 | if self.tz.isEnabled() and (self.tz.currentIndex() != -1):
731 | v = self.thermals.get(str(self.tz.currentText()), (0, 0))
732 | self.sumtemp += v[1]
733 | else:
734 | temp = 0
735 | for k, v in self.thermals.items():
736 | temp += v[1]
737 | if len(self.thermals):
738 | temp /= float(len(self.thermals))
739 | self.sumtemp += temp
740 | self.counter = (self.counter + 1) % self.max_count
741 | if self.counter == 0:
742 | self.avgtemp = float(self.sumtemp) / self.max_count
743 | # print ("Average temperature:", self.avgtemp)
744 | self.sumtemp = 0.0
745 | # brightness
746 | bn = self.readValue(os.path.join(self.backlightpath, "brightness"))
747 | if len(bn):
748 | bnint = int(int(bn) / 100)
749 | if self.bnslider.value() != bnint:
750 | tstate = self.bnslider.hasTracking()
751 | self.bnslider.setTracking(False)
752 | self.bnslider.setSliderPosition(bnint)
753 | self.bnslider.setTracking(tstate)
754 |
755 | def updateGUI(self):
756 | # cpus
757 | for k, v in self.cpulabels.items():
758 | v[0].setStyleSheet(
759 | "QPushButton {color: white; background-color: %s}" % v[1]
760 | )
761 |
762 | # thermals
763 | for k, v in self.thermals.items():
764 | label, val, typename = v
765 | label.setText("%d°C" % val)
766 | if self.throttlegpu.isChecked():
767 | if val > self.maxtemp.value():
768 | label.setStyleSheet("QLabel { color: red }")
769 | else:
770 | label.setStyleSheet(f"QLabel {{ color: {hexColor(self.textColor)} }}")
771 |
772 | # gpus
773 | for k, v in self.gpulabels.items():
774 | for i in range(len(Cols)):
775 | v[i][0].setText("%d MHz" % v[i][1])
776 | for k, v in self.gpusliders.items():
777 | v[Vars.MIN].setValue(
778 | int(self.gpulabels[k][Cols.MIN][1] / self.gpuclkdiv)
779 | )
780 | v[Vars.MAX].setValue(
781 | int(self.gpulabels[k][Cols.MAX][1] / self.gpuclkdiv)
782 | )
783 | v[Vars.BST].setValue(
784 | int(self.gpulabels[k][Cols.BST][1] / self.gpuclkdiv)
785 | )
786 |
787 | def callHelper(self, args):
788 | if not self.suidhelper:
789 | return 1
790 | args = self.suidhelper + args
791 | ret = subprocess.run(
792 | args,
793 | stdout=subprocess.PIPE,
794 | stderr=subprocess.STDOUT,
795 | text=True,
796 | )
797 | if ret.returncode != 0:
798 | self.status.showMessage(ret.stdout)
799 | return None
800 | return ret
801 |
802 | @pyqtSlot(str)
803 | def toggleCPU(self, cpu):
804 | if not self.suidhelper:
805 | return
806 | btn, val = self.cpulabels[str(cpu)]
807 | newval = "red" if val == "green" else "green"
808 | self.cpulabels[str(cpu)] = (btn, newval)
809 |
810 | if self.callHelper(["-c", cpu]) is None:
811 | return
812 |
813 | btn.setStyleSheet(
814 | "QPushButton {color: white; background-color: %s}" % newval
815 | )
816 | self.status.showMessage(
817 | "Switching %s to %s" % (cpu, newval), self.msgtimeout
818 | )
819 |
820 | @pyqtSlot(str)
821 | def setMinimumClock(self, gpu):
822 | if not self.suidhelper:
823 | return
824 | val = self.gpusliders[str(gpu)][Vars.MIN].value()
825 | args = ["-g", gpu, "-l", str(val * self.gpuclkdiv)]
826 | if val > self.gpusliders[str(gpu)][Vars.MAX].value():
827 | self.gpusliders[str(gpu)][Vars.MAX].setValue(val)
828 | args += ["-u", str(val * self.gpuclkdiv)]
829 |
830 | if self.callHelper(args) is None:
831 | return
832 |
833 | self.gpulabels[str(gpu)][Cols.MIN][0].setText(
834 | "%d MHz" % (val * self.gpuclkdiv)
835 | )
836 |
837 | @pyqtSlot(str)
838 | def setMaximumClock(self, gpu):
839 | if not self.suidhelper:
840 | return
841 | val = self.gpusliders[str(gpu)][Vars.MAX].value()
842 | args = ["-g", gpu, "-u", str(val * self.gpuclkdiv)]
843 | if val < self.gpusliders[str(gpu)][Vars.MIN].value():
844 | self.gpusliders[str(gpu)][Vars.MIN].setValue(val)
845 | args += ["-l", str(val * self.gpuclkdiv)]
846 |
847 | if self.callHelper(args) is None:
848 | return
849 |
850 | self.gpulabels[str(gpu)][Cols.MAX][0].setText(
851 | "%d MHz" % (val * self.gpuclkdiv)
852 | )
853 | if self.syncboosttomax.isChecked():
854 | self.gpusliders[str(gpu)][Vars.BST].setValue(val)
855 | self.setBoostClock(gpu)
856 |
857 | @pyqtSlot(str)
858 | def setBoostClock(self, gpu):
859 | if not self.suidhelper:
860 | return
861 | val = self.gpusliders[str(gpu)][Vars.BST].value()
862 | args = ["-g", gpu, "-s", str(val * self.gpuclkdiv)]
863 | if val < self.gpusliders[str(gpu)][Vars.MIN].value():
864 | self.gpusliders[str(gpu)][Vars.MIN].setValue(val)
865 | args += ["-l", str(val * self.gpuclkdiv)]
866 |
867 | if self.callHelper(args) is None:
868 | return
869 |
870 | self.gpulabels[str(gpu)][Cols.BST][0].setText(
871 | "%d MHz" % (val * self.gpuclkdiv)
872 | )
873 |
874 | @pyqtSlot()
875 | def setBrightness(self):
876 | if not self.suidhelper:
877 | return
878 | val = self.bnslider.value() * 100
879 | self.callHelper(["-b", str(val)])
880 |
881 | @staticmethod
882 | def readValue(fn):
883 | ret = ""
884 | try:
885 | f = open(fn)
886 | ret = f.readline()
887 | f.close()
888 | except:
889 | pass
890 | return ret.strip()
891 |
892 |
893 | def natural_sort(l):
894 | convert = lambda text: int(text) if text.isdigit() else text.lower()
895 | alphanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)", key)]
896 | return sorted(l, key=alphanum_key)
897 |
898 |
899 | def getDataFile(fn, subdir=""):
900 | datapaths = [
901 | os.path.join(os.environ["HOME"], ".local", "share"),
902 | "/usr/local/share",
903 | "/usr/share",
904 | ]
905 | for p in datapaths:
906 | path = os.path.join(p, subdir, fn)
907 | if os.path.exists(path):
908 | return path
909 | return fn
910 |
911 |
912 | def detach():
913 | stdin = "/dev/null"
914 | stdout = "/dev/null"
915 | stderr = "/dev/null"
916 |
917 | try:
918 | pid = os.fork()
919 | if pid > 0:
920 | # exit first parent
921 | sys.exit(0)
922 | except OSError as e:
923 | sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
924 | sys.exit(1)
925 |
926 | # decouple from parent environment
927 | os.chdir("/")
928 | os.setsid()
929 | os.umask(0)
930 |
931 | # do second fork
932 | try:
933 | pid = os.fork()
934 | if pid > 0:
935 | # exit from second parent
936 | sys.exit(0)
937 | except OSError as e:
938 | sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
939 | sys.exit(1)
940 |
941 | # redirect standard file descriptors
942 | sys.stdout.flush()
943 | sys.stderr.flush()
944 | si = open(stdin, "r")
945 | so = open(stdout, "a+")
946 | se = open(stderr, "a+")
947 | os.dup2(si.fileno(), sys.stdin.fileno())
948 | os.dup2(so.fileno(), sys.stdout.fileno())
949 | os.dup2(se.fileno(), sys.stderr.fileno())
950 |
951 |
952 | def parseCommandLine():
953 | ret = {}
954 | parser = argparse.ArgumentParser(description="intel-power-control")
955 | parser.add_argument(
956 | "-d", "--daemon", help="run as daemon", action="store_true"
957 | )
958 | parser.add_argument("-style", help="set Qt style")
959 | args = parser.parse_args()
960 |
961 | # detach immediately if run as daemon
962 | if args.daemon:
963 | detach()
964 |
965 | ret["daemon"] = args.daemon
966 |
967 | return ret
968 |
969 |
970 | def main():
971 | import signal
972 |
973 | signal.signal(signal.SIGINT, signal.SIG_DFL)
974 |
975 | argdict = parseCommandLine()
976 | a = QApplication(sys.argv)
977 | a.setOrganizationName("mechnich")
978 | a.setApplicationName("intel-power-control")
979 | a.setWindowIcon(
980 | QIcon(getDataFile("intel-power-control.png", subdir="icons"))
981 | )
982 | i = IntelPowerControl()
983 | return a.exec()
984 |
985 |
986 | if __name__ == "__main__":
987 | main()
988 |
--------------------------------------------------------------------------------