thermald-1.5/0000775000175000017500000000000012661205435011627 5ustar kingkingthermald-1.5/autogen.sh0000775000175000017500000000005212661205366013630 0ustar kingking#!/bin/sh autoreconf --install --verbose thermald-1.5/thermal_daemon_usage.txt0000664000175000017500000000005512661205366016536 0ustar kingkingThermal Daemon Usage: Use: man thermald thermald-1.5/test/0000775000175000017500000000000012661205366012611 5ustar kingkingthermald-1.5/test/test3.xml0000664000175000017500000000213312661205366014374 0ustar kingking THD_TEST_0 * QUIET thd_test_0 thd_test_0 * passive thd_cdev_0 10 thermald-1.5/test/test7.xml0000664000175000017500000000566212661205366014412 0ustar kingking THD_TEST_0 * QUIET thd_test_ex_0 thd_test_0 40000 passive thd_cdev_0_cap_3 thd_test_0 50000 passive thd_cdev_0_cap_6 thd_test_0 60000 passive thd_cdev_0_cap_9 /sys/class/thermal/cooling_device7/cur_state thd_cdev_0_cap_3 0 1 3 /sys/class/thermal/cooling_device7/cur_state thd_cdev_0_cap_6 4 1 6 /sys/class/thermal/cooling_device7/cur_state thd_cdev_0_cap_9 9 1 10 thermald-1.5/test/thermald_test_kern_module.c0000664000175000017500000001223112661205366020177 0ustar kingking/* * Test module to test thermald * * Copyright (C) 2015, Intel Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ /* * To build add * obj-m += thermald_test_kern_module.o in drivers/thermal/Makefile */ #include #include #include #include #include #include #define SENSOR_COUNT 10 #define CDEV_COUNT 10 struct thermald_sensor { struct thermal_zone_device *tzone; }; struct thermald_cdev { struct thermal_cooling_device *cdev; unsigned long max_state; unsigned long curr_state; }; static struct thermald_sensor *sensors[SENSOR_COUNT]; static struct thermald_cdev *cdevs[CDEV_COUNT]; static int sys_get_curr_temp(struct thermal_zone_device *tzd, int *temp) { *temp = 10000; return 0; } static int sys_get_trip_temp(struct thermal_zone_device *tzd, int trip, int *temp) { *temp = 40000; return 0; } static int sys_get_trip_type(struct thermal_zone_device *thermal, int trip, enum thermal_trip_type *type) { *type = THERMAL_TRIP_PASSIVE; return 0; } static struct thermal_zone_device_ops tzone_ops = { .get_temp = sys_get_curr_temp, .get_trip_temp = sys_get_trip_temp, .get_trip_type = sys_get_trip_type, }; static struct thermald_sensor *create_test_tzone(int id) { struct thermald_sensor *sensor; char name[20]; sensor = kzalloc(sizeof(*sensor), GFP_KERNEL); if (!sensor) return NULL; snprintf(name, sizeof(name), "thd_test_%d", id); sensor->tzone = thermal_zone_device_register(name, 1, 0, sensor, &tzone_ops, NULL, 0, 0); if (IS_ERR(sensor->tzone)) { kfree(sensor); return NULL; } return sensor; } static void destroy_test_tzone(struct thermald_sensor *sensor) { if (!sensor) return; thermal_zone_device_unregister(sensor->tzone); kfree(sensor); } static int get_max_state(struct thermal_cooling_device *cdev, unsigned long *state) { struct thermald_cdev *pcdev = cdev->devdata; *state = pcdev->max_state; return 0; } static int get_cur_state(struct thermal_cooling_device *cdev, unsigned long *state) { struct thermald_cdev *pcdev = cdev->devdata; *state = pcdev->curr_state; return 0; } static int set_cur_state(struct thermal_cooling_device *cdev, unsigned long state) { struct thermald_cdev *pcdev = cdev->devdata; pcdev->curr_state = state; return 0; } static const struct thermal_cooling_device_ops cdev_ops = { .get_max_state = get_max_state, .get_cur_state = get_cur_state, .set_cur_state = set_cur_state, }; static struct thermald_cdev *create_test_cdev(int id) { struct thermald_cdev *cdev; char name[20]; cdev = kzalloc(sizeof(*cdev), GFP_KERNEL); if (!cdev) return NULL; snprintf(name, sizeof(name), "thd_cdev_%d", id); cdev->cdev = thermal_cooling_device_register(name, cdev, &cdev_ops); if (IS_ERR(cdev->cdev)) { kfree(cdev); return NULL; } cdev->max_state = 10; return cdev; } static void destroy_test_cdev(struct thermald_cdev *cdev) { if (!cdev) return; thermal_cooling_device_unregister(cdev->cdev); kfree(cdev); } static int sensor_temp; static ssize_t sensor_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%d\n", sensor_temp); } static ssize_t sensor_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { sscanf(buf, "%d", &sensor_temp); return count; } static int control_state; static ssize_t control_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%d\n", control_state); } static ssize_t control_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { sscanf(buf, "%d", &control_state); return count; } static struct kobj_attribute sensor_attribute = __ATTR(sensor_temp, 0644, sensor_show, sensor_store); static struct kobj_attribute control_attribute = __ATTR(control_state, 0644, control_show, control_store); static struct attribute *thermald_attrs[] = { &sensor_attribute.attr, &control_attribute.attr, NULL, }; static struct attribute_group attr_group = { .attrs = thermald_attrs, }; static struct kobject *thermal_control_kobj; static int __init thermald_init(void) { int i; int ret; thermal_control_kobj = kobject_create_and_add("thermald_test", kernel_kobj); if (!thermal_control_kobj) return -ENOMEM; ret = sysfs_create_group(thermal_control_kobj, &attr_group); if (ret) { kobject_put(thermal_control_kobj); return ret; } for (i = 0; i < SENSOR_COUNT; ++i) { sensors[i] = create_test_tzone(i); } for (i = 0; i < CDEV_COUNT; ++i) { cdevs[i] = create_test_cdev(i); } return 0; } static void __exit thermald_exit(void) { int i; for (i = 0; i < SENSOR_COUNT; ++i) { destroy_test_tzone(sensors[i]); } for (i = 0; i < CDEV_COUNT; ++i) { destroy_test_cdev(cdevs[i]); } kobject_put(thermal_control_kobj); } module_init(thermald_init) module_exit(thermald_exit) MODULE_LICENSE("GPL v2"); thermald-1.5/test/test6.xml0000664000175000017500000000462312661205366014405 0ustar kingking THD_TEST_0 * QUIET thd_test_ex_0 thd_test_0 40000 passive thd_cdev_0 3 thd_test_0 50000 passive thd_cdev_0 6 thd_test_0 60000 passive thd_cdev_0 thermald-1.5/test/readme_test.txt0000664000175000017500000000057112661205366015651 0ustar kingkingTests are executed using a loopback Linux driver. Build this as a kernel module by copying thermald_test_kern_module.c to drivers/thermal in Linux kernel source. Add obj-m += thermald_test_kern_module.o in drivers/thermal/Makefile In addition enable in kernel .config CONFIG_THERMAL_EMULATION=y Once kernel driver is loaded using insmod/modprobe execute exec_config_tests.sh thermald-1.5/test/exec_config_tests.sh0000775000175000017500000001700012661205366016641 0ustar kingking#!/bin/bash CONF_FILE="/usr/local/var/run/thermald/thermal-conf.xml.auto" #Test 1: Simple association: one zone to one cooling device # check if cdev state reach max when temp >= 40C and when # temp < 40C state reach to 0. echo "Executing test 1: Simple zone to cdev association" cp test1.xml $CONF_FILE dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.Reinit sleep 5 THD0_ZONE=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_test_0 | sed 's/\/type.*//') THD0_CDEV=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_cdev_0 | sed 's/\/type.*//') echo "Current temperature for thd_test_0 temp to" cat ${THD0_ZONE}/temp sleep 2 echo 50000 > ${THD0_ZONE}/emul_temp echo "Emulate temp to" cat ${THD0_ZONE}/temp COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD0_CDEV}/cur_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 10 ]; then echo "Reached Max State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 10 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi cat ${THD0_CDEV}/cur_state echo 10000 > ${THD0_ZONE}/emul_temp COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD0_CDEV}/cur_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 0 ]; then echo "Reached Min State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 0 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi # TEST 2 echo "Executing test 2: Check if influence field is respected, in picking up cdev" cp test2.xml $CONF_FILE dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.Reinit sleep 5 THD0_ZONE=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_test_0 | sed 's/\/type.*//') THD0_CDEV0=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_cdev_0 | sed 's/\/type.*//') THD0_CDEV1=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_cdev_1 | sed 's/\/type.*//') echo "Current temperature for thd_test_0 temp to" cat ${THD0_ZONE}/temp sleep 2 echo 50000 > ${THD0_ZONE}/emul_temp echo "Emulate temp to" cat ${THD0_ZONE}/temp # check the highest priority cdev picked up first COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD0_CDEV1}/cur_state) echo "current state for thd_cdev_1" ${curr_state} if [ $curr_state -eq 10 ]; then echo "Reached Max State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 10 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi # pick up the next COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD0_CDEV0}/cur_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 10 ]; then echo "Reached Max State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 10 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi echo 10000 > ${THD0_ZONE}/emul_temp COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD0_CDEV0}/cur_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 0 ]; then echo "Reached Min State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 0 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD0_CDEV1}/cur_state) echo "current state for thd_cdev_1" ${curr_state} if [ $curr_state -eq 0 ]; then echo "Reached Min State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 0 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi # Test 3 echo "Executing test 3: Check if sample field is respected" echo "currently it is a visual test only" echo "It will show Too early to act messages, gap between two ops is 15+ sec as per connfig here " cp test3.xml $CONF_FILE dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.Reinit sleep 5 THD0_ZONE=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_test_0 | sed 's/\/type.*//') THD0_CDEV=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_cdev_0 | sed 's/\/type.*//') echo "Current temperature for thd_test_0 temp to" cat ${THD0_ZONE}/temp sleep 2 echo 50000 > ${THD0_ZONE}/emul_temp echo "Emulate temp to" cat ${THD0_ZONE}/temp COUNTER=0 while [ $COUNTER -lt 20 ]; do curr_state=$(cat ${THD0_CDEV}/cur_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 10 ]; then echo "Reached Max State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 10 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi cat ${THD0_CDEV}/cur_state echo 10000 > ${THD0_ZONE}/emul_temp COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD0_CDEV}/cur_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 0 ]; then echo "Reached Min State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 0 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi # Test 4 echo "Executing test 4: one cdev in multiple zones, one zone crossed passive, make sure that the other zone doesn't deactivate an activated cdev " cp test4.xml $CONF_FILE dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.Reinit sleep 5 THD0_ZONE=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_test_0 | sed 's/\/type.*//') THD0_CDEV=$(grep -r . /sys/class/thermal/* 2>/tmp/err.txt | grep thd_cdev_0 | sed 's/\/type.*//') echo "Current temperature for thd_test_0 temp to" cat ${THD0_ZONE}/temp sleep 2 echo 50000 > ${THD0_ZONE}/emul_temp echo "Emulate temp to" cat ${THD0_ZONE}/temp COUNTER=0 while [ $COUNTER -lt 20 ]; do curr_state=$(cat ${THD0_CDEV}/cur_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 10 ]; then echo "Reached Max State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 10 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi cat ${THD0_CDEV}/cur_state echo 10000 > ${THD0_ZONE}/emul_temp COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD0_CDEV}/cur_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 0 ]; then echo "Reached Min State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 0 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi # Test 5 echo "Executing test 5: Test case where sensor/zone/cdev are not" echo " in thermal sysfs and still able to control" cp test5.xml $CONF_FILE dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.Reinit sleep 5 THD5_ZONE=/sys/kernel/thermald_test THD5_CDEV=/sys/kernel/thermald_test echo "Current temperature" cat ${THD5_ZONE}/sensor_temp sleep 2 echo 50000 > ${THD5_ZONE}/sensor_temp echo "Emulate temp to" cat ${THD5_ZONE} COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD5_CDEV}/control_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 10 ]; then echo "Reached Max State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 10 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi cat ${THD5_CDEV} echo 10000 > ${THD5_ZONE}/sensor_temp COUNTER=0 while [ $COUNTER -lt 10 ]; do curr_state=$(cat ${THD5_CDEV}/control_state) echo "current state for thd_cdev_0" ${curr_state} if [ $curr_state -eq 0 ]; then echo "Reached Min State" break fi sleep 5 let COUNTER=COUNTER+1 done if [ $curr_state -ne 0 ]; then echo "Test Failed" exit 1 else echo "Test passed" fi thermald-1.5/test/test5.xml0000664000175000017500000000324312661205366014401 0ustar kingking sysfs_zone_test * QUIET sysfs_sensor_0 /sys/kernel/thermald_test/sensor_temp 0 sysfs_thermal_zone_0 sysfs_sensor_0 40000 passive sysfs_cdev_0 sysfs_cdev_0 /sys/kernel/thermald_test/control_state 0 1 10 thermald-1.5/test/test4.xml0000664000175000017500000000346312661205366014404 0ustar kingking THD_TEST_0 * QUIET thd_test_0 thd_test_0 * passive thd_cdev_0 thd_test_1 thd_test_1 * passive thd_cdev_0 thermald-1.5/test/test1.xml0000664000175000017500000000203312661205366014371 0ustar kingking THD_TEST_0 * QUIET thd_test_0 thd_test_0 * passive thd_cdev_0 thermald-1.5/test/test2.xml0000664000175000017500000000252312661205366014376 0ustar kingking THD_TEST_0 * QUIET thd_test_0 thd_test_0 * passive thd_cdev_0 80 thd_cdev_1 100 thermald-1.5/README.txt0000664000175000017500000001533012661205366013332 0ustar kingkingUse man pages to check command line arguments in configuration: man thermald man thermal-conf.xml Prerequisites: Kernel Prefers kernel with Intel RAPL power capping driver : Available from Linux kernel 3.13.rc1 Intel P State driver (Available in Linux kernel stable release) Intel Power clamp driver (Available in Linux kernel stable release) CONFIG_X86_MSR, so that x86 MSR can be read/write from user space to control RAPL if no RAPL powecap class driver is not present. Default If none of the above available cpufreq to control P states. Building and executing on Fedora 1. Install yum install automake yum install gcc yum install gcc-c++ yum install glib-devel yum install dbus-glib-devel yum install libxml2-devel 2 Build ./autogen.sh ./configure prefix=/usr make sudo make install 3 - start service sudo systemctl start thermald.service - Get status sudo systemctl status thermald.service - Stop service sudo systemctl stop thermald.service 4. Terminate using DBUS I/F sudo test/test_pref.sh and select "TERMINATE" choice. Building on Ubuntu 1. Install sudo apt-get install autoconf sudo apt-get install g++ sudo apt-get install libglib2.0-dev sudo apt-get install libdbus-1-dev sudo apt-get install libdbus-glib-1-dev sudo apt-get install libxml2-dev 2 Build ./autogen.sh ./configure prefix=/usr make sudo make install (It will give error for systemd configuration, but ignore) cp data/thermald.conf /etc/init/ 3. Use "sudo start thermald" to start Use "sudo stop thermald" to stop ------------------------------------------- Releases Release 1.5 - Default warning level increase so that doesn't print much in logs - Add new feature to set specific target state on reaching a threshold, this allows multiple thresholds (trips) - Android update for build - Additional backlight devices - New option to specify config file via command line - Prevent adding cooling device in /etc via dbus - Whitelist of processor models, to avoid startup on server platforms Release 1.4.3 - One new dbus message to get temp - Fixes to prevent warnings Release 1.4 - Extension of DBUS I/F for developing Monitoring and Control GUI - Added exampled to thermal-conf man page - Support INT340X class of thermal control introduced in kernel 4.0 - Reinit without restart thermald to load new parameters like new control temperature - Fix indexes when Linux thermal sysfs doesn't have contiguous zone numbering - Support for new Intel SoC platforms - Introduce back-light control as the Linux back light cooling device is removed - Restore modified passive trip points in thermal zones on exit - Virtual Sensor definition - Fix loop when uevents floods the system - Error message removal for rapl sysfs traversal - Coverity error Release 1.3 - Auto creation of configuration based on ACPI thermal relationship table - Default CPU bound load check for unbinded thermal sensors Release 1.2 - Several fixes for Klocworks and Coverity scans (0 issues remaining) - Baytrail RAPL support as this doesn't have max power limit value Release 1.1 - Use powercap Intel RAPL driver - Use skin temperature sensor by default if available - Specify thermal relationship - Clean up for MSR related controls as up stream kernel driver are capable now - Override capability of thermal sysfs for a specific sensor or zone - Friendly to new thermal sysfs Release 1.04 - Android and chrome os integration - Minor fixes for buggy max temp Release 1.03 - Allow negative step increments while configuring via XML - Use powercap RAPL driver I/F - Additional cpuids in the list - Add man page with details of usage - Added P state turbo on/off Release 1.02 - Allow user to change the max temperarure via dbus message - Allow user to change the cooling method order via an XML configuration - Upstart fixes - Valgrind and zero warnings on build Release 1.01 - Implement RAPL using MSRs. - User can configure cooling device order via XML config file - Fix sensor path configuration for thermal-conf.xml, so that user cn specify custom sensor paths - Use CPU max scaling frequency to control CPU Frequencies - RPM generation scripts - Build and formatting fixes from Alexander Bersenev Release 1.0 - Tested on multiple platforms - Using PID version 0.9 - Replaced netlink with uevents - Fix issue with pre-configured thermal data to control daemon - Use pthreads version 0.8 - Fix RAPL PATH, which is submitted upstream - Handle case when there is no MSR access from user mode - Allow non Intel CPUs version 0.7 - Conditional per cpu control - Family id check - If no max use offset from critical temperature - Switch to hwmon if there is no coretemp - Error handling if MSR support is not enabled in kernel - Code clean up and comments Version 0.6 - Use Intel P state driver to control P states - Use RAPL cooling device - Fix valgrind reported errors and cleanup - Add document Version 0.5 - License update to GPL v2 or later - Change dbus session bus to system - Load thermal-conf.xml data if exact UUID match Version 0.4 - Added power clamp driver interface - Added per cpu controls by trying to calibrate in the background to learn sensor cpu relationship - Optimized p states and turbo states and cleaned up - systemd and service start stop interface Version 0.3 - Added P states t states turbo states as the cooling methods - No longer depend on any thermal sysfs, zone cooling device by default - Uses DTS core temperature and p/turbo/t states to cool system - By default only will use DTS core temperature and p/turbo/t states only - All the previous controls based on the zones/cdevs and XML configuration is only done, when activated via command line - The set points are calculated and stored in a config file when it hits thermal threshold and adjusted based on slope and angular increments to dynamically adjust set point Version 0.2 - Define XML interface to set configuration data. Refere to thermal-conf.xml. This allows to overide buggy Bios thermal comfiguration and also allows to extend the capability. - Use platform DMI UUID to index into configuration data. If there is no UUID match, falls back to thermal sysfs - Terminate interface - Takes over control from kernel thermal processing - Clean up of classes. Version 0.1 - Dbus interface to set preferred policy: "performance", "quiet/power", "disabled" - Defines a C++ classes for zones, cooling devices, trip points, thermal engine - Methods can be overridden in a custom class to modify default behaviour - Read thermal zone and cooling devices, trip points etc, - Read temprature via netlink notification or via polling configurable via command line - Once a trip point is crossed, activate the associate cooling devices. Start with min tstate to max tstate for each cooling device. - Based on active or passive settings it decides the cooling devices thermald-1.5/distribution_integration/0000775000175000017500000000000012661205366016754 5ustar kingkingthermald-1.5/distribution_integration/thermal-daemon.spec0000664000175000017500000000475312661205366022536 0ustar kingkingName: thermal-daemon Version: v1.3 Release: 3%{?dist} Summary: The "Linux Thermal Daemon" program from 01.org License: GPLv2+ URL: https://github.com/01org/thermal_daemon %global pkgname thermal_daemon %global commit 0225c182da262492fb99055975b7d462e68d7490 %global shortcommit %(c=%{commit}; echo ${c:0:7}) Source0: https://github.com/01org/thermal_daemon/archive/%{commit}/%{pkgname}-%{version}-%{shortcommit}.tar.gz BuildRequires: automake BuildRequires: autoconf BuildRequires: glib-devel BuildRequires: dbus-glib-devel BuildRequires: libxml2-devel BuildRequires: systemd Requires(post): systemd-units Requires(preun): systemd-units Requires(postun): systemd-units %description Thermal Daemon monitors and controls platform temperature. %prep %setup -qn %{pkgname}-%{shortcommit} %build autoreconf -f -i %configure prefix=%{_prefix} make %{?_smp_mflags} # Although there is a folder test in the upstream repo, this is not for self tests. # Hence check section is not present. %install %make_install DESTDIR=%{buildroot} %post %systemd_post thermald.service %preun %systemd_preun thermald.service %postun %systemd_postun_with_restart thermald.service %files %{_sbindir}/thermald %config(noreplace) %{_sysconfdir}/dbus-1/system.d/org.freedesktop.thermald.conf %{_datadir}/dbus-1/system-services/org.freedesktop.thermald.service %config(noreplace) %{_sysconfdir}/thermald/thermal-conf.xml %config(noreplace) %{_sysconfdir}/thermald/thermal-cpu-cdev-order.xml %doc COPYING README.txt %{_mandir}/man8/thermald.8.gz %{_mandir}/man5/thermal-conf.xml.5.gz %{_unitdir}/thermald.service %exclude %{_sysconfdir}/init %changelog * Fri Oct 17 2014 António Meireles 1.3-3 - update spec file * Tue Oct 01 2013 Srinivas Pandruvada 1.03-1 - Upgraded to thermal daemon 1.03 * Mon Jun 24 2013 Srinivas Pandruvada 1.02-5 - Replaced underscore with dash in the package name * Thu Jun 20 2013 Srinivas Pandruvada 1.02-4 - Resolved prefix and RPM_BUILD_ROOT as per review comments * Wed Jun 19 2013 Srinivas Pandruvada 1.02-3 - Removed libxml2 requirement and uses shortcommit in the Source0 * Tue Jun 18 2013 Srinivas Pandruvada 1.02-2 - Update spec file after first review * Fri Jun 14 2013 Srinivas Pandruvada 1.02-1 - Initial package thermald-1.5/distribution_integration/make_rpm.sh0000775000175000017500000000157512661205366021116 0ustar kingking#!/bin/bash BRANCH=$(git branch | grep '^*' | sed 's/^..\(.*\)/\1/') HASH=$(git rev-parse ${BRANCH}) TAG=$(git describe --tags --abbrev=0) RELEASE=$(git describe --tags | cut -d- -f2 | tr - _) SHORT_COMMIT=$(git rev-parse HEAD | cut -c 1-7) sed -i "s,^%global commit.*,%global commit ${HASH}," thermal-daemon.spec sed -i "s,^Version:.*,Version: ${TAG}," thermal-daemon.spec sed -i "s,^Release.*,Release: ${RELEASE}%{?dist}," thermal-daemon.spec rsync -a --exclude='rpms' --exclude='.git' ../../thermal_daemon . mv thermal_daemon thermal_daemon-${SHORT_COMMIT} tar czf ~/rpmbuild/SOURCES/thermal_daemon-${TAG}-${SHORT_COMMIT}.tar.gz thermal_daemon-${SHORT_COMMIT} rpmbuild -bs thermal-daemon.spec # /usr/bin/mock -r fedora-21-x86_64 ~/SRPMS/thermal-daemon-*.src.rpm rpmbuild -ba thermal-daemon.spec rpmlint thermal-daemon.spec ~/rpmbuild/SRPMS/thermal* rm -rf thermal_daemon-${SHORT_COMMIT} thermald-1.5/distribution_integration/chromeos_gentoo_ebuild_spec0000664000175000017500000000123512661205366024430 0ustar kingking# Copyright 1999-2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Header: $ EAPI=4 inherit autotools systemd DESCRIPTION="Thermal daemon for Intel architectures" HOMEPAGE="https://01.org/linux-thermal-daemon" SRC_URI="https://github.com/01org/thermal_daemon/archive/v${PV}.tar.gz -> ${P}.tar.gz" LICENSE="GPL-2+" SLOT="0" KEYWORDS="amd64 ia64 x86" IUSE="" S=${WORKDIR}/thermal_daemon-${PV} DEPEND="dev-libs/dbus-glib dev-libs/libxml2" RDEPEND="${DEPEND}" DOCS=( ThermalDaemon_Introduction.pdf README.txt ) src_prepare() { eautoreconf } src_configure() { econf --with-systemdsystemunitdir=$(systemd_get_unitdir) } thermald-1.5/distribution_integration/android_dbus_service_information0000664000175000017500000000075312661205366025466 0ustar kingkingAndroid Integration Thermald required dbus daemon. To start dbus daemon add the following to your init.rc. service dbus /system/bin/dbus-daemon --system --nofork class main socket dbus stream 660 root root user root group system inet To start thermald as a service service thermald /system/bin/thermald --dbus-enable user root group system class main disabled oneshot By default it is disabled. So need explicit command somewhere: "start thermald" thermald-1.5/src/0000775000175000017500000000000012661205366012421 5ustar kingkingthermald-1.5/src/thd_cdev_intel_pstate_driver.cpp0000664000175000017500000000643512661205366021043 0ustar kingking/* * thd_sysfs_intel_pstate_driver.cpp: thermal cooling class implementation * using Intel p state driver * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_cdev_intel_pstate_driver.h" /* * This implementation allows to control get max state and * set current state of using Intel P state driver * P state drives uses a percent count. 100% means full * performance, setting anything lower limits performance. * Each lower state reduces performance by unit value. * unit value is calculated using number of possible p states * . Each step reduces bye one p state. * Contents of "/sys/devices/system/cpu/intel_pstate/" max_perf_pct, min_perf_pct, no_turbo */ void cthd_intel_p_state_cdev::set_curr_state(int state, int arg) { std::stringstream tc_state_dev; int new_state; tc_state_dev << "/max_perf_pct"; if (cdev_sysfs.exists(tc_state_dev.str())) { std::stringstream state_str; if (state == 0) new_state = 100; else { new_state = 100 - (state + min_compensation) * unit_value; } state_str << new_state; thd_log_debug("set cdev state index %d state %d percent %d\n", index, state, new_state); if (new_state <= turbo_disable_percent) set_turbo_disable_status(true); else set_turbo_disable_status(false); if (cdev_sysfs.write(tc_state_dev.str(), state_str.str()) < 0) curr_state = (state == 0) ? 0 : max_state; else curr_state = state; } else curr_state = (state == 0) ? 0 : max_state; } void cthd_intel_p_state_cdev::set_turbo_disable_status(bool enable) { std::stringstream tc_state_dev; if (enable == turbo_status) { return; } tc_state_dev << "/no_turbo"; if (enable) { cdev_sysfs.write(tc_state_dev.str(), "1"); thd_log_info("turbo disabled \n"); } else { cdev_sysfs.write(tc_state_dev.str(), "0"); thd_log_info("turbo enabled \n"); } turbo_status = enable; } int cthd_intel_p_state_cdev::get_max_state() { return max_state; } int cthd_intel_p_state_cdev::update() { std::stringstream tc_state_dev; tc_state_dev << "/max_perf_pct"; if (cdev_sysfs.exists(tc_state_dev.str())) { std::string state_str; cdev_sysfs.read(tc_state_dev.str(), state_str); std::istringstream(state_str) >> curr_state; } else { return THD_ERROR; } thd_log_info("Use Default pstate drv settings\n"); max_state = default_max_state; min_compensation = 0; unit_value = 100.0 / max_state; curr_state = 0; thd_log_debug( "cooling dev index:%d, curr_state:%d, max_state:%d, unit:%f, min_com:%d, type:%s\n", index, curr_state, max_state, unit_value, min_compensation, type_str.c_str()); return THD_SUCCESS; } thermald-1.5/src/thd_cdev_cpufreq.cpp0000664000175000017500000001257312661205366016442 0ustar kingking/* * thd_cdev_pstates.cpp: thermal cooling class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ /* Control P states using cpufreq. Each step reduces to next lower frequency * */ #include "thd_cdev_cpufreq.h" #include "thd_engine.h" int cthd_cdev_cpufreq::init() { // Get number of CPUs if (cdev_sysfs.exists("present")) { std::string count_str; size_t p0 = 0, p1; cdev_sysfs.read("present", count_str); p1 = count_str.find_first_of("-", p0); if (p1 == std::string::npos) return THD_ERROR; std::string token1 = count_str.substr(p0, p1 - p0); if (token1.empty()) return THD_ERROR; std::istringstream(token1) >> cpu_start_index; if ((p1 + 1) >= count_str.size()) return THD_ERROR; std::string token2 = count_str.substr(p1 + 1); if (token2.empty()) return THD_ERROR; std::istringstream(token2) >> cpu_end_index; if ((cpu_end_index <= 0) || (cpu_end_index < cpu_start_index) || cpu_end_index > 63) return THD_ERROR; } else { return THD_ERROR; } thd_log_debug("pstate CPU present %d-%d\n", cpu_start_index, cpu_end_index); // Get list of available frequencies for each CPU // Assuming every core supports same sets of frequencies, so // just reading for cpu0 std::vector _cpufreqs; if (cdev_sysfs.exists("cpu0/cpufreq/scaling_available_frequencies")) { std::string p = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies"; std::ifstream f(p.c_str(), std::fstream::in); if (f.fail()) return -EINVAL; while (!f.eof()) { std::string token; f >> token; if (!f.bad()) { if (!token.empty()) _cpufreqs.push_back(token); } } f.close(); } else return THD_ERROR; // Check scaling max frequency and min frequency // Remove frequencies above and below this in the freq list // The available list contains these frequencies even if they are not allowed unsigned int scaling_min_frequency = 0; unsigned int scaling_max_frequency = 0; for (int i = cpu_start_index; i <= cpu_end_index; ++i) { std::stringstream str; std::string freq_str; str << "cpu" << i << "/cpufreq/scaling_min_freq"; if (cdev_sysfs.exists(str.str())) { cdev_sysfs.read(str.str(), freq_str); unsigned int freq_int; std::istringstream(freq_str) >> freq_int; if (scaling_min_frequency == 0 || freq_int < scaling_min_frequency) scaling_min_frequency = freq_int; } } for (int i = cpu_start_index; i <= cpu_end_index; ++i) { std::stringstream str; std::string freq_str; str << "cpu" << i << "/cpufreq/scaling_max_freq"; if (cdev_sysfs.exists(str.str())) { cdev_sysfs.read(str.str(), freq_str); unsigned int freq_int; std::istringstream(freq_str) >> freq_int; if (scaling_max_frequency == 0 || freq_int > scaling_max_frequency) scaling_max_frequency = freq_int; } } thd_log_debug("cpu freq max %u min %u\n", scaling_max_frequency, scaling_min_frequency); for (unsigned int i = 0; i < _cpufreqs.size(); ++i) { thd_log_debug("cpu freq Add %d: %s\n", i, _cpufreqs[i].c_str()); unsigned int freq_int; std::istringstream(_cpufreqs[i]) >> freq_int; if (freq_int >= scaling_min_frequency && freq_int <= scaling_max_frequency) { add_frequency(freq_int); } } for (unsigned int i = 0; i < cpufreqs.size(); ++i) { thd_log_debug("cpu freq %d: %d\n", i, cpufreqs[i]); } pstate_active_freq_index = 0; return THD_SUCCESS; } void cthd_cdev_cpufreq::add_frequency(unsigned int freq_int) { if (cpufreqs.empty() || cpufreqs.at(0) > (int) freq_int) cpufreqs.push_back(freq_int); else { std::vector::iterator it; it = cpufreqs.begin(); cpufreqs.insert(it, freq_int); } } void cthd_cdev_cpufreq::set_curr_state(int state, int arg) { if (state < (int) cpufreqs.size()) { thd_log_debug("cpu freq set_curr_stat %d: %d\n", state, cpufreqs[state]); if (cpu_index == -1) { for (int i = cpu_start_index; i <= cpu_end_index; ++i) { std::stringstream str; str << "cpu" << i << "/cpufreq/scaling_max_freq"; if (cdev_sysfs.exists(str.str())) { std::stringstream speed; speed << cpufreqs[state]; cdev_sysfs.write(str.str(), speed.str()); } pstate_active_freq_index = state; curr_state = state; } } else { if (thd_engine->apply_cpu_operation(cpu_index)) { std::stringstream str; str << "cpu" << cpu_index << "/cpufreq/scaling_max_freq"; if (cdev_sysfs.exists(str.str())) { std::stringstream speed; speed << cpufreqs[state]; cdev_sysfs.write(str.str(), speed.str()); } pstate_active_freq_index = state; curr_state = state; } } } } int cthd_cdev_cpufreq::get_max_state() { return cpufreqs.size() - 1; } int cthd_cdev_cpufreq::update() { return init(); } thermald-1.5/src/thd_cdev_therm_sys_fs.cpp0000664000175000017500000000656712661205366017510 0ustar kingking/* * cthd_sysfs_cdev.cpp: thermal cooling class implementation * for thermal sysfs * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_cdev_therm_sys_fs.h" #include "thd_engine.h" /* This uses ACPI style thermal sysfs interface to set states. * It expects, max_state. curr_state in thermal sysfs and uses * these sysfs-files to control. * */ int cthd_sysfs_cdev::update() { std::stringstream tc_state_dev; tc_state_dev << "cooling_device" << index << "/cur_state"; if (cdev_sysfs.exists(tc_state_dev.str())) { std::string state_str; cdev_sysfs.read(tc_state_dev.str(), state_str); std::istringstream(state_str) >> curr_state; } else curr_state = 0; std::stringstream tc_max_state_dev; tc_max_state_dev << "cooling_device" << index << "/max_state"; if (cdev_sysfs.exists(tc_max_state_dev.str())) { std::string state_str; cdev_sysfs.read(tc_max_state_dev.str(), state_str); std::istringstream(state_str) >> max_state; } else max_state = 0; std::stringstream tc_type_dev; tc_type_dev << "cooling_device" << index << "/type"; if (cdev_sysfs.exists(tc_type_dev.str())) { cdev_sysfs.read(tc_type_dev.str(), type_str); if (type_str.size()) { // They essentially change same ACPI object, so reading their // state from sysfs after a change to any processor will cause // double compensation if (type_str == "Processor") read_back = false; } } thd_log_debug("cooling dev %d:%d:%d:%s\n", index, curr_state, max_state, type_str.c_str()); return THD_SUCCESS; } int cthd_sysfs_cdev::get_max_state() { std::stringstream tc_state_dev; tc_state_dev << "cooling_device" << index << "/max_state"; if (cdev_sysfs.exists(tc_state_dev.str())) { std::string state_str; cdev_sysfs.read(tc_state_dev.str(), state_str); std::istringstream(state_str) >> max_state; } else max_state = 0; return max_state; } void cthd_sysfs_cdev::set_curr_state(int state, int arg) { std::stringstream tc_state_dev; tc_state_dev << "cooling_device" << index << "/cur_state"; if (cdev_sysfs.exists(tc_state_dev.str())) { std::stringstream state_str; state_str << state; thd_log_debug("set cdev state index %d state %d\n", index, state); cdev_sysfs.write(tc_state_dev.str(), state_str.str()); curr_state = state; } else curr_state = 0; } int cthd_sysfs_cdev::get_curr_state() { if (!read_back) { return curr_state; } std::stringstream tc_state_dev; tc_state_dev << "cooling_device" << index << "/cur_state"; if (cdev_sysfs.exists(tc_state_dev.str())) { std::string state_str; cdev_sysfs.read(tc_state_dev.str(), state_str); std::istringstream(state_str) >> curr_state; } else curr_state = 0; return curr_state; } thermald-1.5/src/thd_cdev_order_parser.h0000664000175000017500000000262212661205366017123 0ustar kingking/* * thd_cdev_order_parser.h: Specify cdev order * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_ORDER_PARSE_H #define THD_CDEV_ORDER_PARSE_H #include #include #include #include #include "thermald.h" class cthd_cdev_order_parse { private: xmlDoc *doc; xmlNode *root_element; std::string filename; std::vector cdev_order_list; int parse(xmlNode * a_node, xmlDoc *doc); int parse_new_cdev(xmlNode * a_node, xmlDoc *doc); public: cthd_cdev_order_parse(); int parser_init(); void parser_deinit(); int start_parse(); int get_order_list(std::vector &list); }; #endif thermald-1.5/src/thd_sensor.cpp0000664000175000017500000000632112661205366015277 0ustar kingking/* * thd_sensor.h: thermal sensor class implementation * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_sensor.h" #include "thd_engine.h" cthd_sensor::cthd_sensor(int _index, std::string control_path, std::string _type_str, int _type) : index(_index), type(_type), sensor_sysfs(control_path.c_str()), sensor_active( false), type_str(_type_str), async_capable(false), virtual_sensor(false), thresholds(0) { } int cthd_sensor::sensor_update() { if (type == SENSOR_TYPE_THERMAL_SYSFS) { if (sensor_sysfs.exists("type")) { sensor_sysfs.read("type", type_str); thd_log_info("sensor_update: type %s\n", type_str.c_str()); } else return THD_ERROR; if (sensor_sysfs.exists("temp")) { return THD_SUCCESS; } else { thd_log_warn("sensor id %d: No temp sysfs for reading temp\n", index); return THD_ERROR; } } if (type == SENSOR_TYPE_RAW) { if (sensor_sysfs.exists("")) { return THD_SUCCESS; } else { thd_log_warn("sensor id %d: No temp sysfs for reading raw temp\n", index); return THD_ERROR; } } return THD_SUCCESS; } unsigned int cthd_sensor::read_temperature() { csys_fs sysfs; std::string buffer; int temp; thd_log_debug("read_temperature sensor ID %d\n", index); if (type == SENSOR_TYPE_THERMAL_SYSFS) sensor_sysfs.read("temp", buffer); else sensor_sysfs.read("", buffer); std::istringstream(buffer) >> temp; if (temp < 0) temp = 0; thd_log_debug("Sensor %s :temp %u \n", type_str.c_str(), temp); return (unsigned int)temp; } void cthd_sensor::enable_uevent() { csys_fs cdev_sysfs("/sys/class/thermal/"); std::stringstream policy_sysfs; policy_sysfs << "thermal_zone" << index << "/policy"; if (cdev_sysfs.exists(policy_sysfs.str().c_str())) { cdev_sysfs.write(policy_sysfs.str(), "user_space"); } } int cthd_sensor::set_threshold(int index, int temp) { if (type != SENSOR_TYPE_THERMAL_SYSFS) return THD_ERROR; std::stringstream tcdev; std::stringstream thres; int status = 0; if (!async_capable) { return THD_ERROR; } tcdev << "trip_point_" << index << "_temp"; thres << temp; if (sensor_sysfs.exists(tcdev.str().c_str())) { status = sensor_sysfs.write(tcdev.str(), thres.str()); } thd_log_debug("cthd_sensor::set_threshold: status %d\n", status); if (status > 0) { enable_uevent(); return THD_SUCCESS; } else return THD_ERROR; } void cthd_sensor::sensor_poll_trip(bool status) { if (status) thd_engine->thd_engine_poll_enable(index); else thd_engine->thd_engine_poll_disable(index); } thermald-1.5/src/thd_zone_therm_sys_fs.cpp0000664000175000017500000001341412661205366017527 0ustar kingking/* * thd_zone_therm_sys_fs.cpp: thermal zone class implementation * for thermal sysfs * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_zone_therm_sys_fs.h" #include "thd_engine.h" #include cthd_sysfs_zone::cthd_sysfs_zone(int count, std::string path) : cthd_zone(count, path), trip_point_cnt(0), zone(NULL) { std::stringstream tc_type_dev; tc_type_dev << index << "/type"; thd_log_debug("Thermal Zone look for %s\n", tc_type_dev.str().c_str()); if (zone_sysfs.exists(tc_type_dev.str())) { zone_sysfs.read(tc_type_dev.str(), type_str); } thd_log_debug("Thermal Zone %d:%s\n", index, type_str.c_str()); } cthd_sysfs_zone::~cthd_sysfs_zone() { std::stringstream trip_sysfs; trip_sysfs << index << "/" << "trip_point_"; for (unsigned int i = 0; i < initial_trip_values.size(); ++i) { std::stringstream temp_stream; temp_stream << trip_sysfs.str() << i << "_temp"; if (initial_trip_values[i] >= 0 && zone_sysfs.exists(temp_stream.str())) { zone_sysfs.write(temp_stream.str(), initial_trip_values[i]); } } } int cthd_sysfs_zone::zone_bind_sensors() { cthd_sensor *sensor; sensor = thd_engine->search_sensor(type_str); if (sensor) { bind_sensor(sensor); } else return THD_ERROR; return THD_SUCCESS; } int cthd_sysfs_zone::read_trip_points() { // Gather all trip points std::stringstream trip_sysfs; trip_sysfs << index << "/" << "trip_point_"; for (int i = 0; i < max_trip_points; ++i) { std::stringstream type_stream; std::stringstream temp_stream; std::stringstream hist_stream; std::string _type_str; std::string _temp_str; std::string _hist_str; trip_point_type_t trip_type; int temp = 0, hyst = 1; mode_t mode = 0; cthd_sensor *sensor; bool wr_mode = false; type_stream << trip_sysfs.str() << i << "_type"; if (zone_sysfs.exists(type_stream.str())) { zone_sysfs.read(type_stream.str(), _type_str); thd_log_debug("read_trip_points %s:%s \n", type_stream.str().c_str(), _type_str.c_str()); } temp_stream << trip_sysfs.str() << i << "_temp"; if (zone_sysfs.exists(temp_stream.str())) { mode = zone_sysfs.get_mode(temp_stream.str()); zone_sysfs.read(temp_stream.str(), _temp_str); std::istringstream(_temp_str) >> temp; thd_log_debug("read_trip_points %s:%s \n", temp_stream.str().c_str(), _temp_str.c_str()); } hist_stream << trip_sysfs.str() << i << "_hyst"; if (zone_sysfs.exists(hist_stream.str())) { zone_sysfs.read(hist_stream.str(), _hist_str); std::istringstream(_hist_str) >> hyst; if (hyst < 1000 || hyst > 5000) hyst = 1000; thd_log_debug("read_trip_points %s:%s \n", hist_stream.str().c_str(), _hist_str.c_str()); } if (_type_str == "critical") trip_type = CRITICAL; else if (_type_str == "hot") trip_type = MAX; else if (_type_str == "active") trip_type = ACTIVE; else if (_type_str == "passive") trip_type = PASSIVE; else trip_type = INVALID_TRIP_TYPE; sensor = thd_engine->search_sensor(type_str); if (sensor && (mode & S_IWUSR)) { sensor->set_async_capable(true); wr_mode = true; initial_trip_values.push_back(temp); } else initial_trip_values.push_back(-1); if (sensor && temp > 0 && trip_type != INVALID_TRIP_TYPE && !wr_mode) { cthd_trip_point trip_pt(trip_point_cnt, trip_type, temp, hyst, index, sensor->get_index()); trip_pt.thd_trip_point_set_control_type(SEQUENTIAL); trip_points.push_back(trip_pt); ++trip_point_cnt; } } thd_log_debug("read_trip_points Added %d trips \n", trip_point_cnt); if (trip_point_cnt == 0) return THD_ERROR; else return THD_SUCCESS; } int cthd_sysfs_zone::read_cdev_trip_points() { thd_log_debug(" >> read_cdev_trip_points for \n"); // Gather all Cdevs // Gather all trip points std::stringstream cdev_sysfs; cdev_sysfs << index << "/" << "cdev"; for (int i = 0; i < max_cool_devs; ++i) { std::stringstream trip_pt_stream, cdev_stream; std::string trip_pt_str; int trip_cnt = -1; char buf[51], *ptr; trip_pt_stream << cdev_sysfs.str() << i << "_trip_point"; if (zone_sysfs.exists(trip_pt_stream.str())) { zone_sysfs.read(trip_pt_stream.str(), trip_pt_str); std::istringstream(trip_pt_str) >> trip_cnt; } else continue; thd_log_debug("cdev trip point: %s contains %d\n", trip_pt_str.c_str(), trip_cnt); cdev_stream << cdev_sysfs.str() << i; if (zone_sysfs.exists(cdev_stream.str())) { thd_log_debug("cdev%d present\n", i); int ret = zone_sysfs.read_symbolic_link_value(cdev_stream.str(), buf, sizeof(buf) - 1); if (ret == 0) { ptr = strstr(buf, "cooling_device"); if (ptr) { ptr += strlen("cooling_device"); thd_log_debug("symbolic name %s:%s\n", buf, ptr); if (trip_cnt >= 0 && trip_cnt < trip_point_cnt) { trip_points[trip_cnt].thd_trip_point_add_cdev_index( atoi(ptr), cthd_trip_point::default_influence); zone_cdev_set_binded(); } else { thd_log_debug("Invalid trip_cnt\n"); } } } } } thd_log_debug( "cthd_sysfs_zone::read_cdev_trip_points: ZONE bound to CDEV status %d \n", zone_cdev_binded_status); return THD_SUCCESS; } thermald-1.5/src/thd_kobj_uevent.h0000664000175000017500000000272112661205366015746 0ustar kingking/* * thd_kobj_uevent.h: Get notification from kobj uevent * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_KOBJ_UEVENT_H_ #define THD_KOBJ_UEVENT_H_ #include #include #include #include #include #include #include #include #include class cthd_kobj_uevent { private: static const int max_buffer_size = 512; struct sockaddr_nl nls; int fd; char device_path[max_buffer_size]; public: cthd_kobj_uevent() { fd = 0; memset(&nls, 0, sizeof(nls)); device_path[0] = '\0'; } int kobj_uevent_open(); void kobj_uevent_close(); void register_dev_path(char *path); bool check_for_event(); } ; #endif thermald-1.5/src/thd_msr.h0000664000175000017500000000366312661205366014242 0ustar kingking/* thd_msr.h: thermal engine msr class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_MSR_H #define THD_MSR_H #include "thd_common.h" #include "thd_sys_fs.h" class cthd_msr { private: csys_fs msr_sysfs; int no_of_cpus; public: cthd_msr(); int read_msr(int cpu, unsigned int idx, unsigned long long *val); int write_msr(int cpu, unsigned int idx, unsigned long long val); int get_no_cpus(); bool check_turbo_status(); int enable_turbo(); int disable_turbo(); int get_clock_mod_duty_cycle(); int set_clock_mod_duty_cycle(int state); int get_min_freq(); int get_max_freq(); int get_min_turbo_freq(); int get_max_turbo_freq(); int inc_freq_state(); int dec_freq_state(); int set_freq_state(int state); int set_perf_bias_performace(); int set_perf_bias_balaced(); int set_perf_bias_energy(); int get_mperf_value(int cpu, unsigned long long *value); int get_aperf_value(int cpu, unsigned long long *value); int set_freq_state_per_cpu(int cpu, int state); int inc_freq_state_per_cpu(int cpu); int dec_freq_state_per_cpu(int cpu); int set_clock_mod_duty_cycle_per_cpu(int cpu, int state); int disable_turbo_per_cpu(int cpu); int enable_turbo_per_cpu(int cpu); }; #endif thermald-1.5/src/thd_trt_art_reader.cpp0000664000175000017500000003304512661205366016772 0ustar kingking/* * thd_trt_art_reader.cpp: Create configuration using ACPI * _ART and _TRT tables * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include #include "thd_common.h" #include "thd_sys_fs.h" #include "thd_trt_art_reader.h" #include "acpi_thermal_rel_ioct.h" using namespace std; #define PRINT_ERROR(...) thd_log_error(__VA_ARGS__) #define PRINT_DEBUG(...) thd_log_debug(__VA_ARGS__) typedef struct { const char *source; const char *sub_string; } sub_string_t; sub_string_t source_substitue_strings[] = { { "B0D4", "cpu" }, { "TCPU", "cpu" }, { "B0DB", "cpu" }, { NULL, NULL } }; sub_string_t target_substitue_strings[] = { { "B0D4", "rapl_controller" }, { "DPLY", "LCD" }, { "DISP", "LCD" }, { "TMEM", "rapl_controller_dram" }, { "TCPU", "rapl_controller" }, { "B0DB", "rapl_controller" }, { NULL, NULL } }; sub_string_t sensor_substitue_strings[] = { { "B0D4", "hwmon" }, { "TCPU", "hwmon" }, { "B0DB", "hwmon" }, { NULL, NULL } }; typedef enum { TARGET_DEV, SOURCE_DEV, SENSOR_DEV } sub_type_t; /* * The _TRT and _ART table may refer to entry, for which we have * we need to tie to some control device, which is not enumerated * as a thermal cooling device. In this case, we substitute them * to a inbuilt standard name. */ static void associate_device(sub_type_t type, string &name) { DIR *dir; struct dirent *entry; std::string base_path = "/sys/bus/platform/devices/"; if ((dir = opendir(base_path.c_str())) != NULL) { while ((entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "INT340", strlen("INT340"))) { char buf[256]; int ret; std::string name_path = base_path + entry->d_name + "/firmware_node"; ret = readlink(name_path.c_str(), buf, sizeof(buf) - 1); if (ret > 0) { buf[ret] = '\0'; name_path.clear(); name_path = base_path + entry->d_name + "/" + std::string(buf) + "/"; csys_fs acpi_sysfs(name_path.c_str()); std::string uid; if (acpi_sysfs.exists("uid")) { ret = acpi_sysfs.read("uid", uid); if (ret < 0) continue; } else if (acpi_sysfs.exists("path")) { ret = acpi_sysfs.read("path", uid); if (ret < 0) continue; size_t pos = uid.find_last_of("."); if (pos != std::string::npos) { uid = uid.substr(pos + 1); } } else continue; if (name == uid) { if (name_path.find("INT3406") != std::string::npos) { name = "DISP"; } else if (name_path.find("INT3402") != std::string::npos) { name = "TMEM"; } else if (name_path.find("INT3401") != std::string::npos) { name = "TCPU"; } closedir(dir); return; } } } } closedir(dir); } } static void subtitute_string(sub_type_t type, string &name) { int i = 0; sub_string_t *list; if (type == TARGET_DEV) { associate_device(type, name); list = target_substitue_strings; } else if (type == SOURCE_DEV) list = source_substitue_strings; else list = sensor_substitue_strings; while (list[i].source) { if (name == list[i].source) { name = list[i].sub_string; break; } i++; } } cthd_acpi_rel::cthd_acpi_rel() : rel_cdev("/dev/acpi_thermal_rel"), xml_hdr("\n"), conf_begin( "\n"), conf_end( "\n"), conf_file(), trt_data(NULL), trt_count( 0), art_data(NULL), art_count(0) { } int cthd_acpi_rel::generate_conf(std::string file_name) { int trt_status; string prefix; int art_status; int ret = 0; std::ifstream conf_file_check(file_name.c_str()); if (conf_file_check.is_open()) { PRINT_ERROR(" File Exists: file_name %s, so no regenerate\n", file_name.c_str()); conf_file_check.close(); return 0; } conf_file_check.close(); art_status = read_art(); trt_status = read_trt(); if (trt_status < 0 && art_status < 0) { PRINT_ERROR("TRT/ART read failed\n"); return -1; } conf_file.open(file_name.c_str()); if (!conf_file.is_open()) { PRINT_ERROR("failed to open output file [%s]\n", file_name.c_str()); ret = -1; goto cleanup; } conf_file << xml_hdr.c_str(); conf_file << conf_begin.c_str(); prefix = indentation = "\t"; conf_file << indentation.c_str() << "" << "\n"; create_platform_conf(); create_platform_pref(0); create_thermal_zones(); conf_file << prefix.c_str() << "" << "\n"; conf_file << conf_end.c_str(); conf_file.close(); cleanup: if (trt_status > 0) delete[] trt_data; if (art_status > 0) delete[] art_data; return ret; } int cthd_acpi_rel::read_art() { int fd; int ret; unsigned long count, length; fd = open(rel_cdev.c_str(), O_RDWR); if (fd < 0) { PRINT_ERROR("failed to open %s \n", rel_cdev.c_str()); return -1; } ret = ioctl(fd, ACPI_THERMAL_GET_ART_COUNT, &count); if (ret < 0) { PRINT_ERROR(" failed to GET COUNT on %s\n", rel_cdev.c_str()); close(fd); return -1; } PRINT_DEBUG("ART count %lu ...\n", count); ret = ioctl(fd, ACPI_THERMAL_GET_ART_LEN, &length); if (ret < 0 || !length) { PRINT_ERROR(" failed to GET LEN on %s\n", rel_cdev.c_str()); close(fd); return -1; } PRINT_DEBUG("ART length %lu ...\n", length); art_data = (unsigned char*) new char[length]; if (!art_data) { PRINT_ERROR("cannot allocate buffer %lu to read ART\n", length); close(fd); return -1; } ret = ioctl(fd, ACPI_THERMAL_GET_ART, art_data); if (ret < 0) { PRINT_ERROR(" failed to GET ART on %s\n", rel_cdev.c_str()); close(fd); return -1; } art_count = count; dump_art(); close(fd); return 0; } int cthd_acpi_rel::read_trt() { int fd; int ret; unsigned long count, length; fd = open(rel_cdev.c_str(), O_RDWR); if (fd < 0) { PRINT_ERROR("failed to open %s \n", rel_cdev.c_str()); return -1; } ret = ioctl(fd, ACPI_THERMAL_GET_TRT_COUNT, &count); if (ret < 0) { PRINT_ERROR(" failed to GET COUNT on %s\n", rel_cdev.c_str()); close(fd); return -1; } PRINT_DEBUG("TRT count %lu ...\n", count); ret = ioctl(fd, ACPI_THERMAL_GET_TRT_LEN, &length); if (ret < 0 || !length) { PRINT_ERROR(" failed to GET LEN on %s\n", rel_cdev.c_str()); close(fd); return -1; } trt_data = (unsigned char*) new char[length]; if (!trt_data) { PRINT_ERROR("cannot allocate buffer %lu to read TRT\n", length); close(fd); return -1; } ret = ioctl(fd, ACPI_THERMAL_GET_TRT, trt_data); if (ret < 0) { PRINT_ERROR(" failed to GET TRT on %s\n", rel_cdev.c_str()); close(fd); return -1; } trt_count = count; dump_trt(); close(fd); return 0; } void cthd_acpi_rel::add_passive_trip_point(rel_object_t &rel_obj) { if (!rel_obj.trt_objects.size()) return; string prefix = indentation + "\t"; conf_file << prefix.c_str() << "\n"; subtitute_string(SENSOR_DEV, rel_obj.target_sensor); conf_file << prefix.c_str() << "\t" << "" << rel_obj.target_sensor.c_str() << "\n"; conf_file << prefix.c_str() << "\t" << "" << "*" << "\n"; conf_file << prefix.c_str() << "\t" << "" << "passive" "\n"; conf_file << prefix.c_str() << "\t" << "" << "SEQUENTIAL" << "\n"; for (unsigned int j = 0; j < rel_obj.trt_objects.size(); ++j) { union trt_object *object = (union trt_object *) rel_obj.trt_objects[j]; string device_name = object->acpi_trt_entry.source_device; conf_file << prefix.c_str() << "\t" << "\n"; subtitute_string(TARGET_DEV, device_name); conf_file << prefix.c_str() << "\t\t" << "" << device_name.c_str() << "\n"; conf_file << prefix.c_str() << "\t\t" << "" << object->acpi_trt_entry.influence << "\n"; conf_file << prefix.c_str() << "\t\t" << "" << object->acpi_trt_entry.sample_period * 100 / 1000 << "\n"; conf_file << prefix.c_str() << "\t" << "\n"; } conf_file << prefix.c_str() << "\n"; } void cthd_acpi_rel::add_active_trip_point(rel_object_t &rel_obj) { if (!rel_obj.art_objects.size()) return; string prefix = indentation + "\t"; conf_file << prefix.c_str() << "\n"; subtitute_string(SENSOR_DEV, rel_obj.target_sensor); conf_file << prefix.c_str() << "\t" << "" << rel_obj.target_sensor.c_str() << "\n"; conf_file << prefix.c_str() << "\t" << "" << "*" << "\n"; conf_file << prefix.c_str() << "\t" << "" << "active" "\n"; conf_file << prefix.c_str() << "\t" << "" << "SEQUENTIAL" << "\n"; for (unsigned int j = 0; j < rel_obj.art_objects.size(); ++j) { union art_object *object = (union art_object *) rel_obj.art_objects[j]; string device_name = object->acpi_art_entry.source_device; conf_file << prefix.c_str() << "\t" << "\n"; subtitute_string(TARGET_DEV, device_name); conf_file << prefix.c_str() << "\t\t" << "" << device_name.c_str() << "\n"; conf_file << prefix.c_str() << "\t\t" << "" << object->acpi_art_entry.weight << "\n"; conf_file << prefix.c_str() << "\t" << "\n"; } conf_file << prefix.c_str() << "\n"; } void cthd_acpi_rel::create_thermal_zone(string type) { unsigned int i; indentation += "\t"; string prefix = indentation; indentation += '\t'; parse_target_devices(); for (i = 0; i < rel_list.size(); ++i) { if (rel_list[i].target_device == "") { PRINT_ERROR("Empty target, skipping ..\n"); continue; } conf_file << prefix.c_str() << "" << "\n"; subtitute_string(SOURCE_DEV, rel_list[i].target_device); conf_file << prefix.c_str() << "\t" << "" << rel_list[i].target_device.c_str() << "" << "\n"; conf_file << prefix.c_str() << "\t" << "" << "\n"; indentation += "\t"; add_passive_trip_point(rel_list[i]); add_active_trip_point(rel_list[i]); conf_file << prefix.c_str() << "\t" << "" << "\n"; conf_file << prefix.c_str() << "" << "\n"; } } void cthd_acpi_rel::parse_target_devices() { union trt_object *trt = (union trt_object *) trt_data; union art_object *art = (union art_object *) art_data; unsigned int i; for (i = 0; i < trt_count; i++) { rel_object_t rel_obj(trt[i].acpi_trt_entry.target_device); vector::iterator find_iter; find_iter = find_if(rel_list.begin(), rel_list.end(), object_finder(trt[i].acpi_trt_entry.target_device)); if (find_iter == rel_list.end()) { rel_obj.trt_objects.push_back(&trt[i]); rel_list.push_back(rel_obj); } else find_iter->trt_objects.push_back(&trt[i]); } for (i = 0; i < art_count; i++) { rel_object_t rel_obj(art[i].acpi_art_entry.target_device); vector::iterator find_iter; find_iter = find_if(rel_list.begin(), rel_list.end(), object_finder(art[i].acpi_art_entry.target_device)); if (find_iter == rel_list.end()) { rel_obj.art_objects.push_back(&art[i]); rel_list.push_back(rel_obj); } else find_iter->art_objects.push_back(&art[i]); } } void cthd_acpi_rel::create_thermal_zones() { string prefix = indentation; conf_file << prefix.c_str() << "" << "\n"; // Read ... create_thermal_zone("test"); // conf_file << prefix.c_str() << "" << "\n"; } void cthd_acpi_rel::create_platform_conf() { // string line; string prefix; indentation += "\t"; prefix = indentation; conf_file << prefix.c_str() << "" << "_TRT export" << "" << "\n"; ifstream product_name("/sys/class/dmi/id/product_name"); conf_file << indentation.c_str() << ""; #if 0 if (product_name.is_open() && getline(product_name, line)) { #else char buffer[256]; if (product_name.is_open() && product_name.getline(buffer, sizeof(buffer))) { string line(buffer); #endif conf_file << line.c_str(); } else conf_file << "*" << "\n"; conf_file << prefix.c_str() << "" << "\n"; } void cthd_acpi_rel::dump_trt() { union trt_object *trt = (union trt_object *) trt_data; unsigned int i; for (i = 0; i < trt_count; i++) { PRINT_DEBUG("TRT %d: SRC %s:\t", i, trt[i].acpi_trt_entry.source_device); PRINT_DEBUG("TRT %d: TGT %s:\t", i, trt[i].acpi_trt_entry.target_device); PRINT_DEBUG("TRT %d: INF %llu:\t", i, trt[i].acpi_trt_entry.influence); PRINT_DEBUG("TRT %d: SMPL %llu:\n", i, trt[i].acpi_trt_entry.sample_period); } } void cthd_acpi_rel::dump_art() { union art_object *art = (union art_object *) art_data; unsigned int i; for (i = 0; i < art_count; i++) { PRINT_DEBUG("ART %d: SRC %s:\t", i, art[i].acpi_art_entry.source_device); PRINT_DEBUG("ART %d: TGT %s:\t", i, art[i].acpi_art_entry.target_device); PRINT_DEBUG("ART %d: WT %llu:\n", i, art[i].acpi_art_entry.weight); } } void cthd_acpi_rel::create_platform_pref(int perf) { if (perf) conf_file << indentation.c_str() << "PERFORMANCE" << "\n"; else conf_file << indentation.c_str() << "QUIET" << "\n"; } thermald-1.5/src/thd_zone.cpp0000664000175000017500000002510012661205366014735 0ustar kingking/* * thd_zone.cpp: thermal zone class implentation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ /* This class implements parent thermal zone/sensor. It is included * in a thermal engine. During initialization, it establishes a * relationship between cooling devices and trip points (where * some action needs to be taken). * When it gets a notification for a change, it reads the temperature * from sensors and uses cthd_trip point to schedule action on the event * if required. */ #include "thd_zone.h" #include "thd_engine.h" cthd_zone::cthd_zone(int _index, std::string control_path, sensor_relate_t rel) : index(_index), zone_sysfs(control_path.c_str()), zone_temp(0), zone_active( false), zone_cdev_binded_status(false), type_str(), sensor_rel( rel), thd_model("") { thd_log_debug("Added zone index:%d \n", index); } cthd_zone::~cthd_zone() { trip_points.clear(); sensors.clear(); } void cthd_zone::thermal_zone_temp_change(int id, unsigned int temp, int pref) { int i, count; bool updated_max = false; bool reset = false; count = trip_points.size(); for (i = 0; i < count; ++i) { cthd_trip_point &trip_point = trip_points[i]; if (trip_point.get_trip_type() == MAX) { thd_model.add_sample(zone_temp); if (thd_model.is_set_point_reached()) { int set_point; set_point = thd_model.get_set_point(); thd_log_debug("new set point %d \n", set_point); trip_point.thd_trip_update_set_point(set_point); updated_max = true; } } trip_point.thd_trip_point_check(id, temp, pref, &reset); // Force all cooling devices to min state if (reset) { zone_reset(); break; } } // Re-adjust polling thresholds if (updated_max) { for (i = count - 1; i >= 0; --i) { cthd_trip_point &trip_point = trip_points[i]; if (trip_point.get_trip_type() == POLLING) { thd_log_debug("new poll point %d \n", thd_model.get_hot_zone_trigger_point()); trip_point.thd_trip_update_set_point( thd_model.get_hot_zone_trigger_point()); trip_point.thd_trip_point_check(id, temp, pref, &reset); } } } } void cthd_zone::update_zone_preference() { if (!zone_active) return; thd_log_debug("update_zone_preference\n"); thd_model.update_user_set_max_temp(); for (unsigned int i = 0; i < sensors.size(); ++i) { cthd_sensor *sensor; sensor = sensors[i]; zone_temp = sensor->read_temperature(); thermal_zone_temp_change(sensor->get_index(), 0, thd_engine->get_preference()); } for (unsigned int i = 0; i < sensors.size(); ++i) { cthd_sensor *sensor; sensor = sensors[i]; zone_temp = sensor->read_temperature(); thermal_zone_temp_change(sensor->get_index(), zone_temp, thd_engine->get_preference()); } } int cthd_zone::read_user_set_psv_temp() { std::stringstream filename; int temp = -1; filename << TDRUNDIR << "/" << "thd_user_psv_temp." << type_str << "." << "conf"; std::ifstream ifs(filename.str().c_str(), std::ifstream::in); if (ifs.good()) { ifs >> temp; thd_log_info("read_user_set_psv_temp %d\n", temp); if (temp < 1000) temp = -1; } ifs.close(); return temp; } int cthd_zone::zone_update() { int ret; thd_model.set_zone_type(type_str); thd_model.use_pid(); if (zone_bind_sensors() != THD_SUCCESS) { thd_log_warn("Zone update failed: unable to bind \n"); return THD_ERROR; } ret = read_trip_points(); if (ret != THD_SUCCESS) return THD_ERROR; int usr_psv_temp = read_user_set_psv_temp(); if (usr_psv_temp > 0) { cthd_trip_point trip_pt_passive(0, PASSIVE, usr_psv_temp, 0, index, DEFAULT_SENSOR_ID); update_trip_temp(trip_pt_passive); } ret = read_cdev_trip_points(); if (ret != THD_SUCCESS) { thd_log_info("No cdev trip points loaded for zone index %d\n", index); // Don't bail out as they may be attached by thermal relation tables } if (trip_points.size()) { unsigned int polling_trip = 0; unsigned int max_trip_temp = 0; std::sort(trip_points.begin(), trip_points.end(), trip_sort); thd_log_info("Sorted trip dump zone index:%d type:%s:\n", index, type_str.c_str()); for (unsigned int i = 0; i < trip_points.size(); ++i) { trip_points[i].trip_dump(); } // Set the lowest trip point as the threshold for sensor async mode // Use that the lowest point, after that we poll if (trip_points.size()) polling_trip = trip_points[0].get_trip_temp(); for (unsigned int i = 0; i < trip_points.size(); ++i) { if (polling_trip > trip_points[i].get_trip_temp()) polling_trip = trip_points[i].get_trip_temp(); if (trip_points[i].get_trip_type() == MAX) max_trip_temp = trip_points[i].get_trip_temp(); thd_log_info("trip type: %d temp: %d \n", trip_points[i].get_trip_type(), trip_points[i].get_trip_temp()); } if (polling_trip > def_async_trip_offset) polling_trip -= def_async_trip_offset; for (unsigned int i = 0; i < sensors.size(); ++i) { cthd_sensor *sensor; sensor = sensors[i]; if (sensor->check_async_capable()) { if (max_trip_temp) { unsigned int _polling_trip; // We have to guarantee MAX, so we better // wake up before, so that by the time // we are notified, temp > max temp thd_model.set_max_temperature(max_trip_temp); _polling_trip = thd_model.get_hot_zone_trigger_point(); if (polling_trip) { if (_polling_trip < polling_trip) { if ((polling_trip - _polling_trip) < def_async_trip_offset) polling_trip = _polling_trip - def_async_trip_offset; else polling_trip = _polling_trip; } } else polling_trip = _polling_trip; } sensor->set_threshold(0, polling_trip); cthd_trip_point trip_pt_polling(trip_points.size(), POLLING, polling_trip, 0, index, sensor->get_index()); trip_pt_polling.thd_trip_point_set_control_type(PARALLEL); trip_points.push_back(trip_pt_polling); } } } for (unsigned int i = 0; i < trip_points.size(); ++i) { cthd_trip_point &trip_point = trip_points[i]; unsigned int set_point; if (trip_point.get_trip_type() == MAX) { thd_model.set_max_temperature(trip_point.get_trip_temp()); set_point = thd_model.get_set_point(); if (set_point != thd_model.get_set_point()) { trip_point.thd_trip_update_set_point(set_point); } } } return THD_SUCCESS; } void cthd_zone::read_zone_temp() { if (zone_active) { unsigned int temp; zone_temp = 0; for (unsigned int i = 0; i < sensors.size(); ++i) { cthd_sensor *sensor; sensor = sensors[i]; temp = sensor->read_temperature(); if (zone_temp < temp) zone_temp = temp; if (sensor_rel == SENSOR_INDEPENDENT) thermal_zone_temp_change(sensor->get_index(), temp, thd_engine->get_preference()); } if (sensor_rel == SENSORS_CORELATED && zone_temp) thermal_zone_temp_change(sensors[0]->get_index(), zone_temp, thd_engine->get_preference()); } } void cthd_zone::zone_temperature_notification(int type, int data) { read_zone_temp(); } void cthd_zone::zone_reset() { int i, count; if (zone_active) { count = trip_points.size(); for (i = count - 1; i >= 0; --i) { cthd_trip_point &trip_point = trip_points[i]; trip_point.thd_trip_cdev_state_reset(); } } } int cthd_zone::bind_cooling_device(trip_point_type_t type, unsigned int trip_temp, cthd_cdev *cdev, int influence, int sampling_period, int target_state) { int i, count; bool added = false; // trip_temp = 0 is a special case, where it will add to first matched type count = trip_points.size(); for (i = 0; i < count; ++i) { cthd_trip_point &trip_point = trip_points[i]; if ((trip_point.get_trip_type() == type) && (trip_point.get_trip_temp() > 0) && (trip_temp == 0 || trip_point.get_trip_temp() == trip_temp)) { trip_point.thd_trip_point_add_cdev(*cdev, influence, sampling_period, target_state); added = true; zone_cdev_set_binded(); break; } } #if 0 // Check again, if we really need this logic if (!added && trip_temp) { // Create a new trip point and add only if trip_temp is valid cthd_trip_point trip_pt(count, type, trip_temp, 0, index, DEFAULT_SENSOR_ID); trip_points.push_back(trip_pt); added = true; } #endif if (added) return THD_SUCCESS; else return THD_ERROR; } int cthd_zone::update_max_temperature(int max_temp) { std::stringstream filename; std::stringstream temp_str; filename << TDRUNDIR << "/" << "thd_user_set_max." << type_str << "." << "conf"; std::ofstream fout(filename.str().c_str()); if (!fout.good()) { return THD_ERROR; } temp_str << max_temp; fout << temp_str.str(); fout.close(); return THD_SUCCESS; } int cthd_zone::update_psv_temperature(int psv_temp) { std::stringstream filename; std::stringstream temp_str; filename << TDRUNDIR << "/" << "thd_user_psv_temp." << type_str << "." << "conf"; std::ofstream fout(filename.str().c_str()); if (!fout.good()) { return THD_ERROR; } temp_str << psv_temp; fout << temp_str.str(); fout.close(); return THD_SUCCESS; } void cthd_zone::add_trip(cthd_trip_point &trip) { bool add = true; for (unsigned int j = 0; j < trip_points.size(); ++j) { if (trip_points[j].get_trip_type() == trip.get_trip_type()) { thd_log_debug("updating existing trip temp \n"); trip_points[j] = trip; if (trip.get_trip_type() == MAX) { thd_model.set_max_temperature(trip.get_trip_temp()); // TODO: If sensor supports polling // update the polling threshold also. } add = false; break; } } if (add) trip_points.push_back(trip); } void cthd_zone::update_trip_temp(cthd_trip_point &trip) { for (unsigned int j = 0; j < trip_points.size(); ++j) { if (trip_points[j].get_trip_type() == trip.get_trip_type()) { thd_log_debug("updating existing trip temp \n"); trip_points[j].update_trip_temp(trip.get_trip_temp()); trip_points[j].update_trip_hyst(trip.get_trip_hyst()); if (trip.get_trip_type() == MAX) { thd_model.set_max_temperature(trip.get_trip_temp()); // TODO: If sensor supports polling // update the polling threshold also. } break; } } } thermald-1.5/src/thd_trip_point.h0000664000175000017500000001111012661205366015612 0ustar kingking/* * thd_trip_point.h: thermal zone trip points class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_TRIP_POINT_H #define THD_TRIP_POINT_H #include "thd_common.h" #include "thd_sys_fs.h" #include "thd_preference.h" #include "thd_cdev.h" #include #include #include // std::sort #include typedef enum { CRITICAL, MAX, PASSIVE, ACTIVE, POLLING, INVALID_TRIP_TYPE } trip_point_type_t; typedef enum { PARALLEL, // All associated cdevs are activated together SEQUENTIAL // one after other once the previous cdev reaches its max state } trip_control_type_t; #define TRIP_PT_INVALID_TARGET_STATE 0xffffff typedef struct { cthd_cdev *cdev; int influence; int sampling_priod; time_t last_op_time; int target_state; } trip_pt_cdev_t; #define DEFAULT_SENSOR_ID 0xFFFF static bool trip_cdev_sort(trip_pt_cdev_t cdev1, trip_pt_cdev_t cdev2) { return (cdev1.influence > cdev2.influence); } class cthd_trip_point { private: int index; trip_point_type_t type; unsigned int temp; unsigned int hyst; std::vector cdevs; trip_control_type_t control_type; int zone_id; int sensor_id; bool trip_on; bool poll_on; bool check_duplicate(cthd_cdev *cdev, int *index) { for (unsigned int i = 0; i < cdevs.size(); ++i) { if (cdevs[i].cdev->get_cdev_type() == cdev->get_cdev_type()) { *index = i; return true; } } return false; } public: static const int default_influence = 0; cthd_trip_point(int _index, trip_point_type_t _type, unsigned int _temp, unsigned int _hyst, int _zone_id, int _sensor_id, trip_control_type_t _control_type = PARALLEL); bool thd_trip_point_check(int id, unsigned int read_temp, int pref, bool *reset); void thd_trip_point_add_cdev(cthd_cdev &cdev, int influence, int sampling_period = 0, int target_state = TRIP_PT_INVALID_TARGET_STATE); void thd_trip_cdev_state_reset(); int thd_trip_point_value() { return temp; } void thd_trip_update_set_point(unsigned int new_value) { temp = new_value; } int thd_trip_point_add_cdev_index(int _index, int influence); void thd_trip_point_set_control_type(trip_control_type_t type) { control_type = type; } trip_point_type_t get_trip_type() { return type; } unsigned int get_trip_temp() { return temp; } unsigned int get_trip_hyst() { return hyst; } void update_trip_temp(unsigned int _temp) { temp = _temp; } void update_trip_type(trip_point_type_t _type) { type = _type; } void update_trip_hyst(unsigned int _temp) { hyst = _temp; } int get_sensor_id() { return sensor_id; } unsigned int get_cdev_count() { return cdevs.size(); } trip_pt_cdev_t &get_cdev_at_index(unsigned int index) { if (index < cdevs.size()) return cdevs[index]; #ifndef ANDROID else throw std::invalid_argument("index"); #endif } void trip_cdev_add(trip_pt_cdev_t trip_cdev) { int index; if (check_duplicate(trip_cdev.cdev, &index)) { cdevs[index].influence = trip_cdev.influence; } else cdevs.push_back(trip_cdev); std::sort(cdevs.begin(), cdevs.end(), trip_cdev_sort); } void trip_dump() { std::string _type_str; if (type == CRITICAL) _type_str = "critical"; else if (type == MAX) _type_str = "max"; else if (type == PASSIVE) _type_str = "passive"; else if (type == ACTIVE) _type_str = "active"; else if (type == POLLING) _type_str = "polling"; else _type_str = "invalid"; thd_log_info( "index %d: type:%s temp:%u hyst:%u zone id:%d sensor id:%d cdev size:%lu\n", index, _type_str.c_str(), temp, hyst, zone_id, sensor_id, (unsigned long) cdevs.size()); for (unsigned int i = 0; i < cdevs.size(); ++i) { thd_log_info("cdev[%u] %s\n", i, cdevs[i].cdev->get_cdev_type().c_str()); } } }; static bool trip_sort(cthd_trip_point trip1, cthd_trip_point trip2) { return (trip1.get_trip_temp() < trip2.get_trip_temp()); } #endif thermald-1.5/src/thd_engine.cpp0000664000175000017500000006663612661205366015252 0ustar kingking/* * thd_engine.cpp: thermal engine class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ /* This class acts as the parent class of all thermal engines. Main functions are: * - Initialization * - Read cooling devices and thermal zones(sensors), which can be overridden in child * - Starts a poll loop, All the thermal processing happens in this thread's context * - Message processing loop * - If either a poll interval is expired or notified via netlink, it schedules a * a change notification on the associated cthd_zone to read and process. */ #include #include #include #include #include #include #include "thd_engine.h" #include "thd_cdev_therm_sys_fs.h" #include "thd_zone_therm_sys_fs.h" #include "thd_zone_dynamic.h" #include "thd_cdev_gen_sysfs.h" static void *cthd_engine_thread(void *arg); cthd_engine::cthd_engine() : current_cdev_index(0), current_zone_index(0), current_sensor_index(0), parse_thermal_zone_success( false), parse_thermal_cdev_success(false), poll_timeout_msec( -1), wakeup_fd(-1), uevent_fd(-1), control_mode(COMPLEMENTRY), write_pipe_fd( 0), preference(0), status(true), thz_last_uevent_time(0), thz_last_temp_ind_time( 0), terminate(false), genuine_intel(0), has_invariant_tsc(0), has_aperf( 0), proc_list_matched(false), poll_interval_sec(0), poll_sensor_mask( 0), poll_fd_cnt(0), rt_kernel(false), parser_init_done(false) { thd_engine = pthread_t(); thd_attr = pthread_attr_t(); pthread_mutex_init(&thd_engine_mutex, NULL); memset(poll_fds, 0, sizeof(poll_fds)); memset(last_cpu_update, 0, sizeof(last_cpu_update)); } cthd_engine::~cthd_engine() { unsigned int i; if (parser_init_done) parser.parser_deinit(); for (i = 0; i < sensors.size(); ++i) { delete sensors[i]; } sensors.clear(); for (i = 0; i < zones.size(); ++i) { delete zones[i]; } zones.clear(); for (i = 0; i < cdevs.size(); ++i) { delete cdevs[i]; } cdevs.clear(); } void cthd_engine::thd_engine_thread() { unsigned int i; int n; time_t tm; int poll_timeout_sec = poll_timeout_msec / 1000; thd_log_info("thd_engine_thread begin\n"); for (;;) { if (terminate) break; rapl_power_meter.rapl_measure_power(); n = poll(poll_fds, poll_fd_cnt, poll_timeout_msec); thd_log_debug("poll exit %d polls_fd event %d %d\n", n, poll_fds[0].revents, poll_fds[1].revents); if (n < 0) { thd_log_warn("Write to pipe failed \n"); continue; } time(&tm); if (n == 0 || (tm - thz_last_temp_ind_time) >= poll_timeout_sec) { if (!status) { thd_log_warn("Thermal Daemon is disabled \n"); continue; } pthread_mutex_lock(&thd_engine_mutex); // Polling mode enabled. Trigger a temp change message for (i = 0; i < zones.size(); ++i) { cthd_zone *zone = zones[i]; zone->zone_temperature_notification(0, 0); } pthread_mutex_unlock(&thd_engine_mutex); thz_last_temp_ind_time = tm; } if (uevent_fd >= 0 && poll_fds[uevent_fd].revents & POLLIN) { // Kobj uevent if (kobj_uevent.check_for_event()) { time_t tm; time(&tm); thd_log_debug("kobj uevent for thermal\n"); if ((tm - thz_last_uevent_time) >= thz_notify_debounce_interval) { pthread_mutex_lock(&thd_engine_mutex); for (i = 0; i < zones.size(); ++i) { cthd_zone *zone = zones[i]; zone->zone_temperature_notification(0, 0); } pthread_mutex_unlock(&thd_engine_mutex); } else { thd_log_debug("IGNORE THZ kevent\n"); } thz_last_uevent_time = tm; } } if (wakeup_fd >= 0 && poll_fds[wakeup_fd].revents & POLLIN) { message_capsul_t msg; thd_log_debug("wakeup fd event\n"); int result = read(poll_fds[wakeup_fd].fd, &msg, sizeof(message_capsul_t)); if (result < 0) { thd_log_warn("read on wakeup fd failed\n"); poll_fds[wakeup_fd].revents = 0; continue; } if (proc_message(&msg) < 0) { thd_log_debug("Terminating thread..\n"); } } } thd_log_debug("thd_engine_thread_end\n"); } bool cthd_engine::set_preference(const int pref) { return true; } int cthd_engine::thd_engine_start(bool ignore_cpuid_check) { int ret; int wake_fds[2]; if (ignore_cpuid_check) { thd_log_debug("Ignore CPU ID check for MSRs \n"); proc_list_matched = true; } else { check_cpu_id(); if (!proc_list_matched) { if ((parser_init() == THD_SUCCESS) && parser.platform_matched()) { thd_log_warn("Unsupported cpu model, using thermal-conf.xml only \n"); } else { thd_log_warn("Unsupported cpu model, use thermal-conf.xml file or run with --ignore-cpuid-check \n"); return THD_FATAL_ERROR; } } } check_for_rt_kernel(); // Pipe is used for communication between two processes ret = pipe(wake_fds); if (ret) { thd_log_error("Thermal sysfs: pipe creation failed %d:\n", ret); return THD_FATAL_ERROR; } if (fcntl(wake_fds[0], F_SETFL, O_NONBLOCK) < 0) { thd_log_error("Cannot set non-blocking on pipe: %s\n", strerror(errno)); return THD_FATAL_ERROR; } if (fcntl(wake_fds[1], F_SETFL, O_NONBLOCK) < 0) { thd_log_error("Cannot set non-blocking on pipe: %s\n", strerror(errno)); return THD_FATAL_ERROR; } write_pipe_fd = wake_fds[1]; memset(poll_fds, 0, sizeof(poll_fds)); wakeup_fd = poll_fd_cnt; poll_fds[wakeup_fd].fd = wake_fds[0]; poll_fds[wakeup_fd].events = POLLIN; poll_fds[wakeup_fd].revents = 0; poll_fd_cnt++; poll_timeout_msec = -1; if (poll_interval_sec) { thd_log_warn("Polling mode is enabled: %d\n", poll_interval_sec); poll_timeout_msec = poll_interval_sec * 1000; } ret = read_thermal_sensors(); if (ret != THD_SUCCESS) { thd_log_error("Thermal sysfs Error in reading sensors\n"); // This is a fatal error and daemon will exit return THD_FATAL_ERROR; } ret = read_cooling_devices(); if (ret != THD_SUCCESS) { thd_log_error("Thermal sysfs Error in reading cooling devs\n"); // This is a fatal error and daemon will exit return THD_FATAL_ERROR; } ret = read_thermal_zones(); if (ret != THD_SUCCESS) { thd_log_error("No thermal sensors found\n"); // This is a fatal error and daemon will exit return THD_FATAL_ERROR; } // Check if polling is disabled and sensors don't support // async mode, in that enable force polling if (!poll_interval_sec) { unsigned int i; for (i = 0; i < zones.size(); ++i) { cthd_zone *zone = zones[i]; if (!zone->zone_active_status()) continue; if (!zone->check_sensor_async_status()) { thd_log_warn( "Polling will be enabled as some sensors are not capable to notify asynchnously \n"); poll_timeout_msec = def_poll_interval; break; } } if (i == zones.size()) { thd_log_info("Proceed without polling mode! \n"); } } uevent_fd = poll_fd_cnt; poll_fds[uevent_fd].fd = kobj_uevent.kobj_uevent_open(); if (poll_fds[uevent_fd].fd < 0) { thd_log_warn("Invalid kobj_uevent handle\n"); uevent_fd = -1; goto skip_kobj; } thd_log_info("FD = %d\n", poll_fds[uevent_fd].fd); kobj_uevent.register_dev_path( (char *) "/devices/virtual/thermal/thermal_zone"); poll_fds[uevent_fd].events = POLLIN; poll_fds[uevent_fd].revents = 0; poll_fd_cnt++; skip_kobj: #ifndef DISABLE_PTHREAD // Create thread pthread_attr_init(&thd_attr); pthread_attr_setdetachstate(&thd_attr, PTHREAD_CREATE_DETACHED); ret = pthread_create(&thd_engine, &thd_attr, cthd_engine_thread, (void*) this); #else { pid_t childpid; if((childpid = fork()) == - 1) { perror("fork"); exit(EXIT_FAILURE); } if(childpid == 0) { /* Child process closes up input side of pipe */ close(wake_fds[1]); cthd_engine_thread((void*)this); } else { /* Parent process closes up output side of pipe */ close(wake_fds[0]); } } #endif preference = thd_pref.get_preference(); thd_log_info("Current user preference is %d\n", preference); if (control_mode == EXCLUSIVE) { thd_log_info("Control is taken over from kernel\n"); takeover_thermal_control(); } return ret; } int cthd_engine::thd_engine_stop() { return THD_SUCCESS; } static void *cthd_engine_thread(void *arg) { cthd_engine *obj = (cthd_engine*) arg; obj->thd_engine_thread(); return NULL; } void cthd_engine::send_message(message_name_t msg_id, int size, unsigned char *msg) { message_capsul_t msg_cap; memset(&msg_cap, 0, sizeof(message_capsul_t)); msg_cap.msg_id = msg_id; msg_cap.msg_size = (size > MAX_MSG_SIZE) ? MAX_MSG_SIZE : size; if (msg) memcpy(msg_cap.msg, msg, msg_cap.msg_size); int result = write(write_pipe_fd, &msg_cap, sizeof(message_capsul_t)); if (result < 0) thd_log_warn("Write to pipe failed \n"); } void cthd_engine::process_pref_change() { int new_pref; thd_pref.refresh(); new_pref = thd_pref.get_preference(); if (new_pref == PREF_DISABLED) { status = false; return; } status = true; if (preference != new_pref) { thd_log_warn("Preference changed \n"); } preference = new_pref; for (unsigned int i = 0; i < zones.size(); ++i) { cthd_zone *zone = zones[i]; zone->update_zone_preference(); } if (control_mode == EXCLUSIVE) { thd_log_info("Control is taken over from kernel\n"); takeover_thermal_control(); } } void cthd_engine::thd_engine_terminate() { send_message(TERMINATE, 0, NULL); sleep(1); process_terminate(); } int cthd_engine::thd_engine_set_user_max_temp(const char *zone_type, const char *user_set_point) { std::string str(user_set_point); cthd_zone *zone; thd_log_debug("thd_engine_set_user_set_point %s\n", user_set_point); std::locale loc; if (std::isdigit(str[0], loc) == 0) { thd_log_warn("thd_engine_set_user_set_point Invalid set point\n"); return THD_ERROR; } zone = get_zone(zone_type); if (!zone) { thd_log_warn("thd_engine_set_user_set_point Invalid zone\n"); return THD_ERROR; } return zone->update_max_temperature(atoi(user_set_point)); } int cthd_engine::thd_engine_set_user_psv_temp(const char *zone_type, const char *user_set_point) { std::string str(user_set_point); cthd_zone *zone; thd_log_debug("thd_engine_set_user_psv_temp %s\n", user_set_point); std::locale loc; if (std::isdigit(str[0], loc) == 0) { thd_log_warn("thd_engine_set_user_psv_temp Invalid set point\n"); return THD_ERROR; } zone = get_zone(zone_type); if (!zone) { thd_log_warn("thd_engine_set_user_psv_temp Invalid zone\n"); return THD_ERROR; } return zone->update_psv_temperature(atoi(user_set_point)); } void cthd_engine::thermal_zone_change(message_capsul_t *msg) { thermal_zone_notify_t *pmsg = (thermal_zone_notify_t*) msg->msg; for (unsigned i = 0; i < zones.size(); ++i) { cthd_zone *zone = zones[i]; if (zone->zone_active_status()) zone->zone_temperature_notification(pmsg->type, pmsg->data); else { thd_log_debug("zone is not active\n"); } } } void cthd_engine::poll_enable_disable(bool status, message_capsul_t *msg) { unsigned int *sensor_id = (unsigned int*) msg->msg; if (status) { poll_sensor_mask |= (1 << (*sensor_id)); poll_timeout_msec = def_poll_interval; thd_log_debug("thd_engine polling enabled via %u \n", *sensor_id); } else { poll_sensor_mask &= ~(1 << (*sensor_id)); if (!poll_sensor_mask) { poll_timeout_msec = -1; thd_log_debug("thd_engine polling last disabled via %u \n", *sensor_id); } } } int cthd_engine::proc_message(message_capsul_t *msg) { int ret = 0; thd_log_debug("Receieved message %d\n", msg->msg_id); switch (msg->msg_id) { case WAKEUP: break; case TERMINATE: thd_log_warn("Terminating ...\n"); ret = -1; terminate = true; break; case PREF_CHANGED: process_pref_change(); break; case THERMAL_ZONE_NOTIFY: if (!status) { thd_log_warn("Thermal Daemon is disabled \n"); break; } thermal_zone_change(msg); break; case RELOAD_ZONES: thd_engine_reload_zones(); break; case POLL_ENABLE: if (!poll_interval_sec) { poll_enable_disable(true, msg); } break; case POLL_DISABLE: if (!poll_interval_sec) { poll_enable_disable(false, msg); } break; default: break; } return ret; } cthd_cdev *cthd_engine::thd_get_cdev_at_index(int index) { for (int i = 0; i < (int) cdevs.size(); ++i) { if (cdevs[i]->thd_cdev_get_index() == index) return cdevs[i]; } return NULL; } void cthd_engine::takeover_thermal_control() { csys_fs sysfs("/sys/class/thermal/"); DIR *dir; struct dirent *entry; const std::string base_path = "/sys/class/thermal/"; thd_log_info("Taking over thermal control \n"); if ((dir = opendir(base_path.c_str())) != NULL) { while ((entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "thermal_zone", strlen("thermal_zone"))) { int i; i = atoi(entry->d_name + strlen("thermal_zone")); std::stringstream policy; std::string curr_policy; policy << "thermal_zone" << i << "/policy"; if (sysfs.exists(policy.str().c_str())) { sysfs.read(policy.str(), curr_policy); zone_preferences.push_back(curr_policy); sysfs.write(policy.str(), "user_space"); } } } closedir(dir); } } void cthd_engine::giveup_thermal_control() { if (control_mode != EXCLUSIVE) return; if (zone_preferences.size() == 0) return; thd_log_info("Giving up thermal control \n"); csys_fs sysfs("/sys/class/thermal/"); DIR *dir; struct dirent *entry; const std::string base_path = "/sys/class/thermal/"; int cnt = 0; if ((dir = opendir(base_path.c_str())) != NULL) { while ((entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "thermal_zone", strlen("thermal_zone"))) { int i; i = atoi(entry->d_name + strlen("thermal_zone")); std::stringstream policy; policy << "thermal_zone" << i << "/policy"; if (sysfs.exists(policy.str().c_str())) { sysfs.write(policy.str(), zone_preferences[cnt++]); } } } closedir(dir); } } void cthd_engine::process_terminate() { thd_log_warn("terminating on user request ..\n"); giveup_thermal_control(); } void cthd_engine::thd_engine_poll_enable(int sensor_id) { send_message(POLL_ENABLE, (int) sizeof(sensor_id), (unsigned char*) &sensor_id); } void cthd_engine::thd_engine_poll_disable(int sensor_id) { send_message(POLL_DISABLE, (int) sizeof(sensor_id), (unsigned char*) &sensor_id); } void cthd_engine::thd_engine_reload_zones() { thd_log_warn(" Reloading zones\n"); for (unsigned int i = 0; i < zones.size(); ++i) { cthd_zone *zone = zones[i]; delete zone; } zones.clear(); int ret = read_thermal_zones(); if (ret != THD_SUCCESS) { thd_log_error("No thermal sensors found\n"); // This is a fatal error and daemon will exit return; } } // Add any tested platform ids in this table static supported_ids_t id_table[] = { { 6, 0x2a }, // Sandybridge { 6, 0x3a }, // IvyBridge { 6, 0x3c }, // Haswell { 6, 0x45 }, // Haswell ULT { 6, 0x46 }, // Haswell ULT { 6, 0x3d }, // Broadwell { 6, 0x37 }, // Valleyview BYT { 6, 0x4c }, // Brasewell { 6, 0x4e }, // skylake { 6, 0x5e }, // skylake { 6, 0x5c }, // Broxton { 0, 0 } // Last Invalid entry }; int cthd_engine::check_cpu_id() { #ifndef ANDROID // Copied from turbostat program unsigned int ebx, ecx, edx, max_level; unsigned int fms, family, model, stepping; genuine_intel = 0; int i = 0; bool valid = false; proc_list_matched = false; ebx = ecx = edx = 0; __cpuid(0, max_level, ebx, ecx, edx); if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e) genuine_intel = 1; if (genuine_intel == 0) { // Simply return without further capability check return THD_SUCCESS; } __cpuid(1, fms, ebx, ecx, edx); family = (fms >> 8) & 0xf; model = (fms >> 4) & 0xf; stepping = fms & 0xf; if (family == 6 || family == 0xf) model += ((fms >> 16) & 0xf) << 4; thd_log_warn( "%u CPUID levels; family:model:stepping 0x%x:%x:%x (%u:%u:%u)\n", max_level, family, model, stepping, family, model, stepping); while (id_table[i].family) { if (id_table[i].family == family && id_table[i].model == model) { proc_list_matched = true; valid = true; break; } i++; } if (!valid) { thd_log_warn(" Need Linux PowerCap sysfs \n"); } #endif return THD_SUCCESS; } void cthd_engine::thd_read_default_thermal_sensors() { DIR *dir; struct dirent *entry; const std::string base_path = "/sys/class/thermal/"; int max_index = 0; thd_log_debug("thd_read_default_thermal_sensors \n"); if ((dir = opendir(base_path.c_str())) != NULL) { while ((entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "thermal_zone", strlen("thermal_zone"))) { int i; i = atoi(entry->d_name + strlen("thermal_zone")); if (i > max_index) max_index = i; cthd_sensor *sensor = new cthd_sensor(i, base_path + entry->d_name + "/", ""); if (sensor->sensor_update() != THD_SUCCESS) { delete sensor; continue; } sensors.push_back(sensor); } } closedir(dir); } if (sensors.size()) current_sensor_index = max_index + 1; thd_log_info("thd_read_default_thermal_sensors loaded %zu sensors \n", sensors.size()); } void cthd_engine::thd_read_default_thermal_zones() { DIR *dir; struct dirent *entry; const std::string base_path = "/sys/class/thermal/"; int max_index = 0; thd_log_debug("thd_read_default_thermal_zones \n"); if ((dir = opendir(base_path.c_str())) != NULL) { while ((entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "thermal_zone", strlen("thermal_zone"))) { int i; i = atoi(entry->d_name + strlen("thermal_zone")); if (i > max_index) max_index = i; cthd_sysfs_zone *zone = new cthd_sysfs_zone(i, "/sys/class/thermal/thermal_zone"); if (zone->zone_update() != THD_SUCCESS) { delete zone; continue; } if (control_mode == EXCLUSIVE) zone->set_zone_active(); zones.push_back(zone); } } closedir(dir); } if (zones.size()) current_zone_index = max_index + 1; thd_log_info("thd_read_default_thermal_zones loaded %zu zones \n", zones.size()); } void cthd_engine::thd_read_default_cooling_devices() { DIR *dir; struct dirent *entry; const std::string base_path = "/sys/class/thermal/"; int max_index = 0; thd_log_debug("thd_read_default_cooling devices \n"); if ((dir = opendir(base_path.c_str())) != NULL) { while ((entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "cooling_device", strlen("cooling_device"))) { int i; i = atoi(entry->d_name + strlen("cooling_device")); if (i > max_index) max_index = i; cthd_sysfs_cdev *cdev = new cthd_sysfs_cdev(i, "/sys/class/thermal/"); if (cdev->update() != THD_SUCCESS) { delete cdev; continue; } cdevs.push_back(cdev); } } closedir(dir); } if (cdevs.size()) current_cdev_index = max_index + 1; thd_log_info("thd_read_default_cooling devices loaded %zu cdevs \n", cdevs.size()); } cthd_zone* cthd_engine::search_zone(std::string name) { cthd_zone *zone; for (unsigned int i = 0; i < zones.size(); ++i) { zone = zones[i]; if (!zone) continue; if (zone->get_zone_type() == name) return zone; } return NULL; } cthd_cdev* cthd_engine::search_cdev(std::string name) { cthd_cdev *cdev; for (unsigned int i = 0; i < cdevs.size(); ++i) { cdev = cdevs[i]; if (!cdev) continue; if (cdev->get_cdev_type() == name) return cdev; } return NULL; } cthd_sensor* cthd_engine::search_sensor(std::string name) { cthd_sensor *sensor; for (unsigned int i = 0; i < sensors.size(); ++i) { sensor = sensors[i]; if (!sensor) continue; if (sensor->get_sensor_type() == name) return sensor; } return NULL; } cthd_sensor* cthd_engine::get_sensor(int index) { if (index >= 0 && index < (int) sensors.size()) return sensors[index]; else return NULL; } int cthd_engine::get_sensor_temperature(int index, unsigned int *temperature) { if (index >= 0 && index < (int) sensors.size()) { *temperature = sensors[index]->read_temperature(); return THD_SUCCESS; } else return THD_ERROR; } cthd_zone* cthd_engine::get_zone(int index) { if (index == -1) return NULL; if (index >= 0 && index < (int) zones.size()) return zones[index]; else return NULL; } cthd_zone* cthd_engine::get_zone(std::string type) { cthd_zone *zone; for (unsigned int i = 0; i < zones.size(); ++i) { zone = zones[i]; if (zone->get_zone_type() == type) return zone; } return NULL; } // Code copied from // https://rt.wiki.kernel.org/index.php/RT_PREEMPT_HOWTO#Runtime_detection_of_an_RT-PREEMPT_Kernel void cthd_engine::check_for_rt_kernel() { struct utsname _uname; char *crit1 = NULL; int crit2 = 0; FILE *fd; uname(&_uname); crit1 = strcasestr(_uname.version, "PREEMPT RT"); if ((fd = fopen("/sys/kernel/realtime", "r")) != NULL) { int flag; crit2 = ((fscanf(fd, "%d", &flag) == 1) && (flag == 1)); fclose(fd); } if (crit1 && crit2) rt_kernel = true; else rt_kernel = false; thd_log_info("Running on a %s kernel\n", rt_kernel ? "PREEMPT RT" : "vanilla"); } int cthd_engine::user_add_sensor(std::string name, std::string path) { cthd_sensor *sensor; pthread_mutex_lock(&thd_engine_mutex); for (unsigned int i = 0; i < sensors.size(); ++i) { if (sensors[i]->get_sensor_type() == name) { sensor = sensors[i]; sensor->update_path(path); pthread_mutex_unlock(&thd_engine_mutex); return THD_SUCCESS; } } sensor = new cthd_sensor(current_sensor_index, path, name, SENSOR_TYPE_RAW); if (sensor->sensor_update() != THD_SUCCESS) { delete sensor; pthread_mutex_unlock(&thd_engine_mutex); return THD_ERROR; } sensors.push_back(sensor); ++current_sensor_index; pthread_mutex_unlock(&thd_engine_mutex); send_message(WAKEUP, 0, 0); return THD_SUCCESS; } int cthd_engine::user_add_virtual_sensor(std::string name, std::string dep_sensor, double slope, double intercept) { cthd_sensor *sensor; int ret; pthread_mutex_lock(&thd_engine_mutex); for (unsigned int i = 0; i < sensors.size(); ++i) { if (sensors[i]->get_sensor_type() == name) { sensor = sensors[i]; if (sensor->is_virtual()) { cthd_sensor_virtual *virt_sensor = (cthd_sensor_virtual *) sensor; ret = virt_sensor->sensor_update_param(dep_sensor, slope, intercept); } else { pthread_mutex_unlock(&thd_engine_mutex); return THD_ERROR; } pthread_mutex_unlock(&thd_engine_mutex); return ret; } } cthd_sensor_virtual *virt_sensor; virt_sensor = new cthd_sensor_virtual(current_sensor_index, name, dep_sensor, slope, intercept); if (virt_sensor->sensor_update() != THD_SUCCESS) { delete virt_sensor; pthread_mutex_unlock(&thd_engine_mutex); return THD_ERROR; } sensors.push_back(virt_sensor); ++current_sensor_index; pthread_mutex_unlock(&thd_engine_mutex); send_message(WAKEUP, 0, 0); return THD_SUCCESS; } cthd_sensor *cthd_engine::user_get_sensor(unsigned int index) { if (index < sensors.size()) return sensors[index]; else return NULL; } cthd_zone *cthd_engine::user_get_zone(unsigned int index) { if (index < zones.size()) return zones[index]; else return NULL; } cthd_cdev *cthd_engine::user_get_cdev(unsigned int index) { if (index < cdevs.size()) return cdevs[index]; else return NULL; } int cthd_engine::user_set_psv_temp(std::string name, unsigned int temp) { cthd_zone *zone; int ret; pthread_mutex_lock(&thd_engine_mutex); zone = get_zone(name); if (!zone) { pthread_mutex_unlock(&thd_engine_mutex); thd_log_warn("user_set_psv_temp\n"); return THD_ERROR; } thd_log_info("Setting psv %u\n", temp); ret = zone->update_psv_temperature(temp); pthread_mutex_unlock(&thd_engine_mutex); return ret; } int cthd_engine::user_set_max_temp(std::string name, unsigned int temp) { cthd_zone *zone; int ret; pthread_mutex_lock(&thd_engine_mutex); zone = get_zone(name); if (!zone) { pthread_mutex_unlock(&thd_engine_mutex); thd_log_warn("user_set_max_temp\n"); return THD_ERROR; } thd_log_info("Setting max %u\n", temp); ret = zone->update_max_temperature(temp); pthread_mutex_unlock(&thd_engine_mutex); return ret; } int cthd_engine::user_add_zone(std::string zone_name, unsigned int trip_temp, std::string sensor_name, std::string cdev_name) { int ret = THD_SUCCESS; cthd_zone_dynamic *zone = new cthd_zone_dynamic(current_zone_index, zone_name, trip_temp, PASSIVE, sensor_name, cdev_name); if (!zone) { return THD_ERROR; } if (zone->zone_update() == THD_SUCCESS) { pthread_mutex_lock(&thd_engine_mutex); zones.push_back(zone); pthread_mutex_unlock(&thd_engine_mutex); zone->set_zone_active(); ++current_zone_index; } for (unsigned int i = 0; i < zones.size(); ++i) { zones[i]->zone_dump(); } return ret; } int cthd_engine::user_set_zone_status(std::string name, int status) { cthd_zone *zone; pthread_mutex_lock(&thd_engine_mutex); zone = get_zone(name); if (!zone) { pthread_mutex_unlock(&thd_engine_mutex); return THD_ERROR; } thd_log_info("Zone Set status %d\n", status); if (status) zone->set_zone_active(); else zone->set_zone_inactive(); pthread_mutex_unlock(&thd_engine_mutex); return THD_SUCCESS; } int cthd_engine::user_get_zone_status(std::string name, int *status) { cthd_zone *zone; pthread_mutex_lock(&thd_engine_mutex); zone = get_zone(name); if (!zone) { pthread_mutex_unlock(&thd_engine_mutex); return THD_ERROR; } if (zone->zone_active_status()) *status = 1; else *status = 0; pthread_mutex_unlock(&thd_engine_mutex); return THD_SUCCESS; } int cthd_engine::user_delete_zone(std::string name) { pthread_mutex_lock(&thd_engine_mutex); for (unsigned int i = 0; i < zones.size(); ++i) { if (zones[i]->get_zone_type() == name) { delete zones[i]; zones.erase(zones.begin() + i); break; } } pthread_mutex_unlock(&thd_engine_mutex); for (unsigned int i = 0; i < zones.size(); ++i) { zones[i]->zone_dump(); } return THD_SUCCESS; } int cthd_engine::user_add_cdev(std::string cdev_name, std::string cdev_path, int min_state, int max_state, int step) { cthd_cdev *cdev; pthread_mutex_lock(&thd_engine_mutex); // Check if there is existing cdev with this name and path cdev = search_cdev(cdev_name); if (!cdev) { cthd_gen_sysfs_cdev *cdev_sysfs; cdev_sysfs = new cthd_gen_sysfs_cdev(current_cdev_index, cdev_path); if (!cdev_sysfs) { pthread_mutex_unlock(&thd_engine_mutex); return THD_ERROR; } cdev_sysfs->set_cdev_type(cdev_name); if (cdev_sysfs->update() != THD_SUCCESS) { delete cdev_sysfs; pthread_mutex_unlock(&thd_engine_mutex); return THD_ERROR; } cdevs.push_back(cdev_sysfs); ++current_cdev_index; cdev = cdev_sysfs; } cdev->set_min_state(min_state); cdev->set_max_state(max_state); cdev->set_inc_dec_value(step); pthread_mutex_unlock(&thd_engine_mutex); for (unsigned int i = 0; i < cdevs.size(); ++i) { cdevs[i]->cdev_dump(); } return THD_SUCCESS; } int cthd_engine::parser_init() { if (parser_init_done) return THD_SUCCESS; if (parser.parser_init(get_config_file()) == THD_SUCCESS) { if (parser.start_parse() == THD_SUCCESS) { parser.dump_thermal_conf(); parser_init_done = true; return THD_SUCCESS; } } return THD_ERROR; } void cthd_engine::parser_deinit() { if (parser_init_done) { parser.parser_deinit(); parser_init_done = false; } } thermald-1.5/src/thd_cdev_gen_sysfs.cpp0000664000175000017500000000262712661205366016774 0ustar kingking/* * cthd_sysfs_gen_sysfs.cpp: thermal cooling class interface * for non thermal cdev sysfs * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_cdev_gen_sysfs.h" int cthd_gen_sysfs_cdev::update() { if (cdev_sysfs.exists()) { std::string state_str; cdev_sysfs.read("", state_str); std::istringstream(state_str) >> curr_state; min_state = max_state = curr_state; } else return THD_ERROR; return THD_SUCCESS; } void cthd_gen_sysfs_cdev::set_curr_state(int state, int arg) { std::stringstream state_str; state_str << state; thd_log_debug("set cdev state index %d state %d\n", index, state); cdev_sysfs.write("", state_str.str()); curr_state = state; } thermald-1.5/src/thd_rapl_interface.h0000664000175000017500000000552712661205366016420 0ustar kingking/* rapl_interface.h: rapl interface for power top * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef RAPL_INTERFACE_H #define RAPL_INTERFACE_H #include "thd_msr.h" class c_rapl_interface { private: static const int def_sampling_interval = 1; //In seconds unsigned char rapl_domains; int measurment_interval; int first_cpu; cthd_msr msr; double power_units; double energy_status_units; double time_units; double last_pkg_energy_status; double last_dram_energy_status; double last_pp0_energy_status; double last_pp1_energy_status; int read_msr(int cpu, unsigned int idx, unsigned long long *val); int write_msr(int cpu, unsigned int idx, unsigned long long val); public: c_rapl_interface(int cpu = 0); int get_rapl_power_unit(unsigned long long *value); double get_power_unit(); double get_energy_status_unit(); double get_time_unit(); int get_pkg_energy_status(double *status); int get_pkg_power_info(double *thermal_spec_power, double *max_power, double *min_power, double *max_time_window); int get_pkg_power_limit_msr(unsigned long long *value); int set_pkg_power_limit_msr(unsigned long long value); unsigned long long default_pkg_power_limit_msr_value; int set_pkg_power_limit(int time_window, int power); int store_pkg_power_limit(); int restore_pkg_power_limit(); int get_dram_energy_status(double *status); int get_dram_power_info(double *thermal_spec_power, double *max_power, double *min_power, double *max_time_window); int get_dram_power_limit(unsigned long long *value); int set_dram_power_limit(unsigned long long value); int get_pp0_energy_status(double *status); int get_pp0_power_limit(unsigned long long *value); int set_pp0_power_limit(unsigned long long value); int get_pp0_power_policy(unsigned int *pp0_power_policy); int get_pp1_energy_status(double *status); int get_pp1_power_limit(unsigned long long *value); int set_pp1_power_limit(unsigned long long value); int get_pp1_power_policy(unsigned int *pp1_power_policy); bool pkg_domain_present(); bool dram_domain_present(); bool pp0_domain_present(); bool pp1_domain_present(); void rapl_measure_energy(); }; #endif thermald-1.5/src/thd_sys_fs.h0000664000175000017500000000417412661205366014745 0ustar kingking/* * thd_sys_fs.h: sysfs class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_SYS_FS_H_ #define THD_SYS_FS_H_ #include #include #include #include #include #include #include #include #include class csys_fs { private: std::string base_path; public: csys_fs() : base_path("") { } ; csys_fs(const char *path) : base_path(path) { } /* write data to base path (dir) + provided path */ int write(const std::string &path, const std::string &buf); int write(const std::string &path, unsigned int data); int write(const std::string &path, unsigned int position, unsigned long long data); /* read data from base path (dir) + provided path */ int read(const std::string &path, char *buf, int len); int read(const std::string &path, std::string &buf); int read(const std::string &path, unsigned int *ptr_val); int read(const std::string &path, unsigned long *ptr_val); int read(const std::string &path, unsigned int position, char *buf, int len); const char *get_base_path() { return base_path.c_str(); } int read_symbolic_link_value(const std::string &path, char *buf, int len); bool exists(const std::string &path); bool exists(); mode_t get_mode(const std::string &path); void update_path(std::string path) { base_path = path; } }; #endif /* THD_SYS_FS_H_ */ thermald-1.5/src/thd_engine_default.h0000664000175000017500000000272512661205366016410 0ustar kingking/* * cthd_engine_defualt.cpp: Default thermal engine * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_ENGINE_DEFAULT_H_ #define THD_ENGINE_DEFAULT_H_ #include "thd_engine.h" #include "thd_cpu_default_binding.h" class cthd_engine_default: public cthd_engine { private: int add_replace_cdev(cooling_dev_t *config); cthd_cpu_default_binding def_binding; public: static const int power_clamp_reduction_percent = 5; cthd_engine_default() : cthd_engine() { } ~cthd_engine_default(); int read_thermal_zones(); int read_cooling_devices(); int read_thermal_sensors(); }; int thd_engine_create_default_engine(bool ignore_cpuid_check, bool exclusive_control, const char *config_file); #endif /* THD_ENGINE_DEFAULT_H_ */ thermald-1.5/src/thd_dbus_interface.xml0000664000175000017500000001275112661205366016765 0ustar kingking thermald-1.5/src/thermald.h0000664000175000017500000000511512661205366014374 0ustar kingking/* * thermald.h: Thermal Daemon common header file * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_THERMALD_H #define THD_THERMALD_H #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef ANDROID #define LOG_NDEBUG 1 #undef LOG_TAG #define LOG_TAG "THERMALD" #include #include #include #define thd_log_fatal ALOGE #define thd_log_error ALOGE #define thd_log_warn ALOGW #define thd_log_info ALOGD #define thd_log_debug ALOGV #else #include "config.h" #define LOCKF_SUPPORT #ifdef GLIB_SUPPORT #include #include #include #include #include #include // Log macros #define thd_log_fatal g_error // Print error and terminate #define thd_log_error g_critical #define thd_log_warn g_warning #define thd_log_debug g_debug #define thd_log_info(...) g_log(NULL, G_LOG_LEVEL_INFO, __VA_ARGS__) #else static int dummy_printf(const char *__restrict __format, ...) { return 0; } #define thd_log_fatal printf #define thd_log_error printf #define thd_log_warn printf #define thd_log_debug dummy_printf #define thd_log_info printf #endif #endif // Common return value defines #define THD_SUCCESS 0 #define THD_ERROR -1 #define THD_FATAL_ERROR -2 // Dbus related /* Well-known name for this service. */ #define THD_SERVICE_NAME "org.freedesktop.thermald" #define THD_SERVICE_OBJECT_PATH "/org/freedesktop/thermald" #define THD_SERVICE_INTERFACE "org.freedesktop.thermald" class cthd_engine; class cthd_engine_therm_sysfs; extern cthd_engine *thd_engine; extern int thd_poll_interval; #endif thermald-1.5/src/android_main.cpp0000664000175000017500000001513412661205366015555 0ustar kingking/* * android_main.cpp: Thermal Daemon entry point tuned for Android * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * * This is the main entry point for thermal daemon. This has main function * which parses command line arguments, setup logs and starts thermal * engine. */ #include "thermald.h" #include "thd_preference.h" #include "thd_engine.h" #include "thd_engine_default.h" #include "thd_parse.h" #include // getdtablesize() is removed from bionic/libc in LPDK*/ // use POSIX alternative available. Otherwise fail # ifdef _POSIX_OPEN_MAX # define getdtablesize() (_POSIX_OPEN_MAX) # endif // for AID_* constatns #include // getdtablesize() is removed from bionic/libc in LPDK*/ // use POSIX alternative available. Otherwise fail # ifdef _POSIX_OPEN_MAX # define getdtablesize() (_POSIX_OPEN_MAX) # endif // poll mode int thd_poll_interval = 4; //in seconds static int pid_file_handle; // Stop daemon static void daemonShutdown() { if (pid_file_handle) close(pid_file_handle); thd_engine->thd_engine_terminate(); sleep(1); delete thd_engine; } // signal handler static void signal_handler(int sig) { switch (sig) { case SIGHUP: thd_log_warn("Received SIGHUP signal. \n"); break; case SIGINT: case SIGTERM: thd_log_info("Daemon exiting \n"); daemonShutdown(); exit(EXIT_SUCCESS); break; default: thd_log_warn("Unhandled signal %s\n", strsignal(sig)); break; } } static void daemonize(char *rundir, char *pidfile) { int pid, sid, i; char str[10]; struct sigaction sig_actions; sigset_t sig_set; if (getppid() == 1) { return; } sigemptyset(&sig_set); sigaddset(&sig_set, SIGCHLD); sigaddset(&sig_set, SIGTSTP); sigaddset(&sig_set, SIGTTOU); sigaddset(&sig_set, SIGTTIN); sigprocmask(SIG_BLOCK, &sig_set, NULL); sig_actions.sa_handler = signal_handler; sigemptyset(&sig_actions.sa_mask); sig_actions.sa_flags = 0; sigaction(SIGHUP, &sig_actions, NULL); sigaction(SIGTERM, &sig_actions, NULL); sigaction(SIGINT, &sig_actions, NULL); pid = fork(); if (pid < 0) { /* Could not fork */ exit(EXIT_FAILURE); } if (pid > 0) { thd_log_info("Child process created: %d\n", pid); exit(EXIT_SUCCESS); } umask(027); sid = setsid(); if (sid < 0) { exit(EXIT_FAILURE); } /* close all descriptors */ for (i = getdtablesize(); i >= 0; --i) { close(i); } i = open("/dev/null", O_RDWR); dup(i); dup(i); chdir(rundir); pid_file_handle = open(pidfile, O_RDWR | O_CREAT, 0600); if (pid_file_handle == -1) { /* Couldn't open lock file */ thd_log_info("Could not open PID lock file %s, exiting\n", pidfile); exit(EXIT_FAILURE); } /* Try to lock file */ #ifdef LOCKF_SUPPORT if (lockf(pid_file_handle, F_TLOCK, 0) == -1) { #else if (flock(pid_file_handle,LOCK_EX|LOCK_NB) < 0) { #endif /* Couldn't get lock on lock file */ thd_log_info("Couldn't get lock file %d\n", getpid()); exit(EXIT_FAILURE); } thd_log_info("Thermal PID %d\n", getpid()); snprintf(str, sizeof(str), "%d\n", getpid()); write(pid_file_handle, str, strlen(str)); } static void print_usage(FILE* stream, int exit_code) { fprintf(stream, "Usage: thermal-daemon options [ ... ]\n"); fprintf(stream, " --help Display this usage information.\n" " --version Show version.\n" " --no-daemon No daemon.\n" " --poll-interval Poll interval 0 to disable.\n" " --exclusive_control To act as exclusive thermal controller.\n" " --config-file Configuration file to use other than the default config. \n"); exit(exit_code); } int main(int argc, char *argv[]) { int c; int option_index = 0; bool no_daemon = false; bool exclusive_control = false; bool test_mode = false; bool is_privileged_user = false; char *conf_file = NULL; const char* const short_options = "hvnp:detc:"; static struct option long_options[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 'v' }, { "no-daemon", no_argument, 0, 'n' }, { "poll-interval", required_argument, 0, 'p' }, { "exclusive_control", no_argument, 0, 'e' }, { "test-mode", no_argument, 0, 't' }, { "config-file", required_argument, 0, 'c' }, { NULL, 0, NULL, 0 } }; if (argc > 1) { while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) { switch (c) { case 'h': print_usage(stdout, 0); break; case 'v': fprintf(stdout, "1.1\n"); exit(EXIT_SUCCESS); break; case 'n': no_daemon = true; break; case 'p': thd_poll_interval = atoi(optarg); break; case 'e': exclusive_control = true; break; case 't': test_mode = true; break; case 'c': conf_file = optarg; break; case -1: case 0: break; default: break; } } } is_privileged_user = (getuid() == 0) || (getuid() == AID_SYSTEM); if (!is_privileged_user && !test_mode) { thd_log_error("You do not have correct permissions to run thermal dameon!\n"); exit(1); } if (mkdir(TDRUNDIR, 0755) != 0) { if (errno != EEXIST) { fprintf(stderr, "Cannot create '%s': %s\n", TDRUNDIR, strerror(errno)); exit(EXIT_FAILURE); } } mkdir(TDCONFDIR, 0755); // Don't care return value as directory if (!no_daemon) { daemonize((char *) "/tmp/", (char *) "/tmp/thermald.pid"); } else signal(SIGINT, signal_handler); thd_log_info( "Linux Thermal Daemon is starting mode %d : poll_interval %d :ex_control %d\n", no_daemon, thd_poll_interval, exclusive_control); if (thd_engine_create_default_engine(false, exclusive_control, conf_file) != THD_SUCCESS) { exit(EXIT_FAILURE); } #ifdef VALGRIND_TEST // lots of STL lib function don't free memory // when called with exit(). // Here just run for some time and gracefully return. sleep(10); if (pid_file_handle) close(pid_file_handle); thd_engine->thd_engine_terminate(); sleep(1); delete thd_engine; #else for (;;) sleep(0xffff); thd_log_info("Linux Thermal Daemon is exiting \n"); #endif return 0; } thermald-1.5/src/thd_zone_dynamic.cpp0000664000175000017500000000300112661205366016435 0ustar kingking/* * thd_zone_dynamic.cpp * * Created on: Sep 19, 2014 * Author: spandruvada */ #include "thd_zone_dynamic.h" #include "thd_engine.h" cthd_zone_dynamic::cthd_zone_dynamic(int index, std::string _name, unsigned int _trip_temp, trip_point_type_t _trip_type, std::string _sensor, std::string _cdev) : cthd_zone(index, ""), name(_name), trip_temp(_trip_temp), trip_type(_trip_type), sensor_name( _sensor), cdev_name(_cdev) { type_str = name; } int cthd_zone_dynamic::read_trip_points() { cthd_sensor *sensor = thd_engine->search_sensor(sensor_name); if (!sensor) { thd_log_warn("dynamic sensor: invalid sensor type \n"); return THD_ERROR; } thd_log_info("XX index = %d\n", index); cthd_trip_point trip_pt(0, trip_type, trip_temp, 0, index, sensor->get_index()); if (trip_type == MAX) { thd_model.set_max_temperature(trip_temp); if (thd_model.get_set_point()) { trip_pt.update_trip_temp(thd_model.get_set_point()); } } trip_points.push_back(trip_pt); cthd_cdev *cdev = thd_engine->search_cdev(cdev_name); if (cdev) { trip_pt.thd_trip_point_add_cdev(*cdev, cthd_trip_point::default_influence); zone_cdev_set_binded(); } else return THD_ERROR; return THD_SUCCESS; } int cthd_zone_dynamic::read_cdev_trip_points() { return 0; } int cthd_zone_dynamic::zone_bind_sensors() { cthd_sensor *sensor = thd_engine->search_sensor(sensor_name); if (!sensor) { thd_log_warn("dynamic sensor: invalid sensor type \n"); return THD_ERROR; } bind_sensor(sensor); return THD_SUCCESS; } thermald-1.5/src/thd_zone_surface.cpp0000664000175000017500000000574412661205366016461 0ustar kingking/* * thd_zone_surface.cpp: zone implementation for external surface * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_zone_surface.h" const char *skin_sensors[] = { "TSKN", "SKIN", "skin", "tskin", "TSKIN", "cover", NULL }; cthd_zone_surface::cthd_zone_surface(int index) : cthd_zone(index, ""), sensor(NULL) { type_str = "Surface"; } int cthd_zone_surface::read_trip_points() { cthd_trip_point *trip_ptr = NULL; bool add = false; int i = 0; cthd_zone *ref_zone = NULL; if (!sensor) return THD_ERROR; while (skin_sensors[i]) { cthd_zone *zone; zone = thd_engine->search_zone(skin_sensors[i]); if (zone) { ref_zone = zone; if (zone->zone_active_status()) { thd_log_error("A skin sensor zone is already active \n"); return THD_ERROR; } break; } ++i; } for (unsigned int j = 0; j < trip_points.size(); ++j) { if (trip_points[j].get_trip_type() == PASSIVE) { thd_log_debug("updating existing trip temp \n"); trip_points[j].update_trip_temp(passive_trip_temp); trip_points[j].update_trip_hyst(passive_trip_hyst); trip_ptr = &trip_points[j]; break; } } if (!trip_ptr) { trip_ptr = new cthd_trip_point(trip_points.size(), MAX, passive_trip_temp, passive_trip_hyst, index, sensor->get_index(), SEQUENTIAL); if (!trip_ptr) { thd_log_warn("Mem alloc error for new trip \n"); return THD_ERROR; } add = true; } cthd_cdev *cdev = thd_engine->search_cdev("rapl_controller"); if (cdev) { trip_ptr->thd_trip_point_add_cdev(*cdev, cthd_trip_point::default_influence, surface_sampling_period); } cdev = thd_engine->search_cdev("intel_powerclamp"); if (cdev) { trip_ptr->thd_trip_point_add_cdev(*cdev, cthd_trip_point::default_influence, surface_sampling_period); } if (add) { trip_points.push_back(*trip_ptr); } delete trip_ptr; if (ref_zone) ref_zone->zone_cdev_set_binded(); return THD_SUCCESS; } int cthd_zone_surface::zone_bind_sensors() { int i = 0; while (skin_sensors[i]) { sensor = thd_engine->search_sensor(skin_sensors[i]); if (sensor) break; ++i; } if (!sensor) { thd_log_error("No SKIN sensor \n"); return THD_ERROR; } bind_sensor(sensor); return THD_SUCCESS; } int cthd_zone_surface::read_cdev_trip_points() { return THD_SUCCESS; } thermald-1.5/src/thd_cpu_default_binding.h0000664000175000017500000000415512661205366017423 0ustar kingking/* * thd_default_binding.h: Default binding of thermal zones * interface file * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_DEFAULT_BINDING_H_ #define THD_DEFAULT_BINDING_H_ #include "thd_engine.h" #include "thd_cdev.h" typedef struct { char zone_name[50 + 1]; int failures; } cpu_zone_stat_t; typedef struct { std::string zone_name; cthd_cdev *cdev_gate_entry; cthd_cdev *cdev_gate_exit; cthd_zone *zone; } cpu_zone_binding_t; class cthd_cpu_default_binding { private: int thd_read_default_thermal_zones(); unsigned int cpu_package_max_power; bool blacklist_match(std::string name); public: static const int def_gating_cdev_sampling_period = 30; static const unsigned int def_starting_power_differential = 4000000; std::vector cdev_list; cthd_cpu_default_binding() : cpu_package_max_power(0) { } ~ cthd_cpu_default_binding() { for (unsigned int i = 0; i < cdev_list.size(); ++i) { cpu_zone_binding_t *cdev_binding_info = cdev_list[i]; delete cdev_binding_info->cdev_gate_exit; delete cdev_binding_info->cdev_gate_entry; delete cdev_binding_info; } cdev_list.clear(); } void do_default_binding(std::vector &cdevs); bool check_cpu_load(); int read_zone_stat(std::string zone_name, cpu_zone_stat_t *stat); void update_zone_stat(std::string zone_name, int fail_cnt); }; #endif /* THD_DEFAULT_BINDING_H_ */ thermald-1.5/src/thd_engine_default.cpp0000664000175000017500000004344412661205366016746 0ustar kingking/* * cthd_engine_defualt.cpp: Default thermal engine * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include #include #include #include "thd_engine_default.h" #include "thd_zone_cpu.h" #include "thd_zone_generic.h" #include "thd_cdev_gen_sysfs.h" #include "thd_cdev_cpufreq.h" #include "thd_cdev_rapl.h" #include "thd_cdev_intel_pstate_driver.h" #include "thd_zone_surface.h" #include "thd_cdev_rapl_dram.h" #include "thd_sensor_virtual.h" #include "thd_cdev_backlight.h" // Default CPU cooling devices, which are not part of thermal sysfs // Since non trivial initialization is not supported, we init all fields even if they are not needed /* Some security scan handler can't parse, the following block and generate unnecessary errors. * hiding good ones. So init in old style compatible to C++ static cooling_dev_t cpu_def_cooling_devices[] = { { .status = true, .mask = CDEV_DEF_BIT_UNIT_VAL | CDEV_DEF_BIT_READ_BACK | CDEV_DEF_BIT_MIN_STATE | CDEV_DEF_BIT_STEP, .index = 0, .unit_val = ABSOULUTE_VALUE, .min_state = 0, .max_state = 0, .inc_dec_step = 5, .read_back = false, .auto_down_control = false, .type_string = "intel_powerclamp", .path_str = "", .debounce_interval = 4, .pid_enable = false, .pid = {0.0, 0.0, 0.0}}, }; */ static cooling_dev_t cpu_def_cooling_devices[] = { { true, CDEV_DEF_BIT_UNIT_VAL | CDEV_DEF_BIT_READ_BACK | CDEV_DEF_BIT_MIN_STATE | CDEV_DEF_BIT_STEP, 0, ABSOULUTE_VALUE, 0, 0, 5, false, false, "intel_powerclamp", "", 4, false, { 0.0, 0.0, 0.0 } }, { true, CDEV_DEF_BIT_UNIT_VAL | CDEV_DEF_BIT_READ_BACK | CDEV_DEF_BIT_MIN_STATE | CDEV_DEF_BIT_STEP, 0, ABSOULUTE_VALUE, 0, 100, 5, false, false, "LCD", "", 4, false, { 0.0, 0.0, 0.0 } } }; cthd_engine_default::~cthd_engine_default() { } int cthd_engine_default::read_thermal_sensors() { int index; DIR *dir; struct dirent *entry; int sensor_mask = 0x0f; cthd_sensor *sensor; const std::string base_path[] = { "/sys/devices/platform/", "/sys/class/hwmon/" }; int i; thd_read_default_thermal_sensors(); index = current_sensor_index; sensor = search_sensor("pkg-temp-0"); if (sensor) { // Force this to support async sensor->set_async_capable(true); } sensor = search_sensor("x86_pkg_temp"); if (sensor) { // Force this to support async sensor->set_async_capable(true); } sensor = search_sensor("soc_dts0"); if (sensor) { // Force this to support async sensor->set_async_capable(true); } sensor = search_sensor("acpitz"); if (sensor) { // Force this to support async sensor->set_async_capable(true); } // Default CPU temperature zone // Find path to read DTS temperature for (i = 0; i < 2; ++i) { if ((dir = opendir(base_path[i].c_str())) != NULL) { while ((entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "coretemp.", strlen("coretemp.")) || !strncmp(entry->d_name, "hwmon", strlen("hwmon"))) { // Check name std::string name_path = base_path[i] + entry->d_name + "/name"; csys_fs name_sysfs(name_path.c_str()); if (!name_sysfs.exists()) { thd_log_info("dts %s doesn't exist\n", name_path.c_str()); continue; } std::string name; if (name_sysfs.read("", name) < 0) { thd_log_info("dts name read failed for %s\n", name_path.c_str()); continue; } if (name != "coretemp") continue; int cnt = 0; unsigned int mask = 0x1; do { if (sensor_mask & mask) { std::stringstream temp_input_str; std::string path = base_path[i] + entry->d_name + "/"; csys_fs dts_sysfs(path.c_str()); temp_input_str << "temp" << cnt << "_input"; if (dts_sysfs.exists(temp_input_str.str())) { cthd_sensor *sensor = new cthd_sensor(index, base_path[i] + entry->d_name + "/" + temp_input_str.str(), "hwmon", SENSOR_TYPE_RAW); if (sensor->sensor_update() != THD_SUCCESS) { delete sensor; closedir(dir); return THD_ERROR; } sensors.push_back(sensor); ++index; } } mask = (mask << 1); cnt++; } while (mask != 0); } } closedir(dir); } if (index != current_sensor_index) break; } if (index == current_sensor_index) { // No coretemp sysfs exist, try hwmon thd_log_warn("Thermal DTS: No coretemp sysfs found\n"); } current_sensor_index = index; // Add from XML sensor config if (!parser_init() && parser.platform_matched()) { for (int i = 0; i < parser.sensor_count(); ++i) { thermal_sensor_t *sensor_config = parser.get_sensor_dev_index(i); if (!sensor_config) continue; cthd_sensor *sensor = search_sensor(sensor_config->name); if (sensor) { if (sensor_config->mask & SENSOR_DEF_BIT_PATH) sensor->update_path(sensor_config->path); if (sensor_config->mask & SENSOR_DEF_BIT_ASYNC_CAPABLE) sensor->set_async_capable(sensor_config->async_capable); } else { cthd_sensor *sensor_new = NULL; if (sensor_config->virtual_sensor) { cthd_sensor_virtual *sensor_virt = new cthd_sensor_virtual( index, sensor_config->name, sensor_config->sensor_link.name, sensor_config->sensor_link.multiplier, sensor_config->sensor_link.offset); if (sensor_virt->sensor_update() != THD_SUCCESS) { delete sensor_virt; continue; } sensor_new = sensor_virt; } else { sensor_new = new cthd_sensor(index, sensor_config->path, sensor_config->name, SENSOR_TYPE_RAW); if (sensor_new->sensor_update() != THD_SUCCESS) { delete sensor_new; continue; } } if (sensor_new) { sensors.push_back(sensor_new); ++index; } } } } current_sensor_index = index; for (unsigned int i = 0; i < sensors.size(); ++i) { sensors[i]->sensor_dump(); } return THD_SUCCESS; } int cthd_engine_default::read_thermal_zones() { int index; DIR *dir; struct dirent *entry; const std::string base_path[] = { "/sys/devices/platform/", "/sys/class/hwmon/" }; int i; thd_read_default_thermal_zones(); index = current_zone_index; if (!search_zone("cpu")) { bool cpu_zone_created = false; thd_log_info("zone cpu will be created \n"); // Default CPU temperature zone // Find path to read DTS temperature for (i = 0; i < 2; ++i) { if ((dir = opendir(base_path[i].c_str())) != NULL) { while ((entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "coretemp.", strlen("coretemp.")) || !strncmp(entry->d_name, "hwmon", strlen("hwmon"))) { std::string name_path = base_path[i] + entry->d_name + "/name"; csys_fs name_sysfs(name_path.c_str()); if (!name_sysfs.exists()) { thd_log_info("dts zone %s doesn't exist\n", name_path.c_str()); continue; } std::string name; if (name_sysfs.read("", name) < 0) { thd_log_info("dts zone name read failed for %s\n", name_path.c_str()); continue; } thd_log_info("%s->%s\n", name_path.c_str(), name.c_str()); if (name != "coretemp") continue; cthd_zone_cpu *zone = new cthd_zone_cpu(index, base_path[i] + entry->d_name + "/", atoi(entry->d_name + strlen("coretemp."))); if (zone->zone_update() == THD_SUCCESS) { zone->set_zone_active(); zones.push_back(zone); cpu_zone_created = true; ++index; } else { delete zone; } } } closedir(dir); } if (cpu_zone_created) break; } if (!cpu_zone_created) { thd_log_error( "Thermal DTS or hwmon: No Zones present Need to configure manually\n"); } } current_zone_index = index; // Add from XML thermal zone if (!parser_init() && parser.platform_matched()) { for (int i = 0; i < parser.zone_count(); ++i) { bool activate; thermal_zone_t *zone_config = parser.get_zone_dev_index(i); if (!zone_config) continue; thd_log_debug("Look for Zone [%s] \n", zone_config->type.c_str()); cthd_zone *zone = search_zone(zone_config->type); if (zone) { activate = false; thd_log_info("Zone already present %s \n", zone_config->type.c_str()); for (unsigned int k = 0; k < zone_config->trip_pts.size(); ++k) { trip_point_t &trip_pt_config = zone_config->trip_pts[k]; thd_log_debug( "Trip %d, temperature %d, Look for Search sensor %s\n", k, trip_pt_config.temperature, trip_pt_config.sensor_type.c_str()); cthd_sensor *sensor = search_sensor( trip_pt_config.sensor_type); if (!sensor) { thd_log_error("XML zone: invalid sensor type [%s]\n", trip_pt_config.sensor_type.c_str()); // This will update the trip temperature for the matching // trip type if (trip_pt_config.temperature) { cthd_trip_point trip_pt(zone->get_trip_count(), trip_pt_config.trip_pt_type, trip_pt_config.temperature, trip_pt_config.hyst, zone->get_zone_index(), -1, trip_pt_config.control_type); zone->update_trip_temp(trip_pt); } continue; } zone->bind_sensor(sensor); if (trip_pt_config.temperature) { cthd_trip_point trip_pt(zone->get_trip_count(), trip_pt_config.trip_pt_type, trip_pt_config.temperature, trip_pt_config.hyst, zone->get_zone_index(), sensor->get_index(), trip_pt_config.control_type); // bind cdev for (unsigned int j = 0; j < trip_pt_config.cdev_trips.size(); ++j) { cthd_cdev *cdev = search_cdev( trip_pt_config.cdev_trips[j].type); if (cdev) { trip_pt.thd_trip_point_add_cdev(*cdev, trip_pt_config.cdev_trips[j].influence, trip_pt_config.cdev_trips[j].sampling_period, trip_pt_config.cdev_trips[j].target_state); zone->zone_cdev_set_binded(); activate = true; } } zone->add_trip(trip_pt); } else { thd_log_debug("Trip temp == 0 is in zone %s \n", zone_config->type.c_str()); // Try to find some existing non zero trips and associate the cdevs // This is the way from an XML config a generic cooling device // can be bound. For example from ACPI thermal relationships tables for (unsigned int j = 0; j < trip_pt_config.cdev_trips.size(); ++j) { cthd_cdev *cdev = search_cdev( trip_pt_config.cdev_trips[j].type); if (!cdev) { thd_log_info("cdev for type %s not found\n", trip_pt_config.cdev_trips[j].type.c_str()); } if (cdev) { if (zone->bind_cooling_device( trip_pt_config.trip_pt_type, 0, cdev, trip_pt_config.cdev_trips[j].influence, trip_pt_config.cdev_trips[j].sampling_period, trip_pt_config.cdev_trips[j].target_state) == THD_SUCCESS) { thd_log_debug( "bind %s to trip to sensor %s\n", cdev->get_cdev_type().c_str(), sensor->get_sensor_type().c_str()); activate = true; } else { thd_log_debug( "bind_cooling_device failed for cdev %s trip %s\n", cdev->get_cdev_type().c_str(), sensor->get_sensor_type().c_str()); } } } } } if (activate) { thd_log_debug("Activate zone %s\n", zone->get_zone_type().c_str()); zone->set_zone_active(); } } else { cthd_zone_generic *zone = new cthd_zone_generic(index, i, zone_config->type); if (zone->zone_update() == THD_SUCCESS) { zones.push_back(zone); ++index; zone->set_zone_active(); } else delete zone; } } } current_zone_index = index; #ifdef ACTIVATE_SURFACE // Enable when skin sensors are standardized cthd_zone *surface; surface = search_zone("Surface"); if (!surface || (surface && !surface->zone_active_status())) { cthd_zone_surface *zone = new cthd_zone_surface(index); if (zone->zone_update() == THD_SUCCESS) { zones.push_back(zone); ++index; zone->set_zone_active(); } else delete zone; } else { thd_log_info("TSKN sensor was activated by config \n"); } current_zone_index = index; #endif if (!zones.size()) { thd_log_info("No Thermal Zones found \n"); return THD_FATAL_ERROR; } #ifdef AUTO_DETECT_RELATIONSHIP def_binding.do_default_binding(cdevs); #endif for (unsigned int i = 0; i < zones.size(); ++i) { zones[i]->zone_dump(); } return THD_SUCCESS; } int cthd_engine_default::add_replace_cdev(cooling_dev_t *config) { cthd_cdev *cdev; bool cdev_present = false; bool percent_unit = false; // Check if there is existing cdev with this name and path cdev = search_cdev(config->type_string); if (cdev) { cdev_present = true; // Also check for path, some device like FAN has multiple paths for same type_str std::string base_path = cdev->get_base_path(); if (config->path_str.size() && config->path_str != base_path) { cdev_present = false; } } if (!cdev_present) { // create new cdev = new cthd_gen_sysfs_cdev(current_cdev_index, config->path_str); if (!cdev) return THD_ERROR; cdev->set_cdev_type(config->type_string); if (cdev->update() != THD_SUCCESS) { delete cdev; return THD_ERROR; } cdevs.push_back(cdev); ++current_cdev_index; } if (config->mask & CDEV_DEF_BIT_UNIT_VAL) { if (config->unit_val == RELATIVE_PERCENTAGES) percent_unit = true; } if (config->mask & CDEV_DEF_BIT_AUTO_DOWN) cdev->set_down_adjust_control(config->auto_down_control); if (config->mask & CDEV_DEF_BIT_STEP) { if (percent_unit) cdev->set_inc_dec_value( cdev->get_curr_state() * config->inc_dec_step / 100); else cdev->set_inc_dec_value(config->inc_dec_step); } if (config->mask & CDEV_DEF_BIT_MIN_STATE) { if (percent_unit) cdev->thd_cdev_set_min_state_param( cdev->get_curr_state() * config->min_state / 100); else cdev->thd_cdev_set_min_state_param(config->min_state); } if (config->mask & CDEV_DEF_BIT_MAX_STATE) { if (percent_unit) cdev->thd_cdev_set_max_state_param( cdev->get_curr_state() * config->max_state / 100); else cdev->thd_cdev_set_max_state_param(config->max_state); } if (config->mask & CDEV_DEF_BIT_READ_BACK) cdev->thd_cdev_set_read_back_param(config->read_back); if (config->mask & CDEV_DEF_BIT_DEBOUNCE_VAL) cdev->set_debounce_interval(config->debounce_interval); if (config->mask & CDEV_DEF_BIT_PID_PARAMS) { cdev->enable_pid(); cdev->set_pid_param(config->pid.Kp, config->pid.Ki, config->pid.Kd); } return THD_SUCCESS; } int cthd_engine_default::read_cooling_devices() { int size; int i; // Read first all the default cooling devices added by kernel thd_read_default_cooling_devices(); // Add RAPL cooling device cthd_sysfs_cdev_rapl *rapl_dev = new cthd_sysfs_cdev_rapl( current_cdev_index, 0); rapl_dev->set_cdev_type("rapl_controller"); if (rapl_dev->update() == THD_SUCCESS) { cdevs.push_back(rapl_dev); ++current_cdev_index; } else { delete rapl_dev; } // Add Intel P state driver as cdev cthd_intel_p_state_cdev *pstate_dev = new cthd_intel_p_state_cdev( current_cdev_index); pstate_dev->set_cdev_type("intel_pstate"); if (pstate_dev->update() == THD_SUCCESS) { cdevs.push_back(pstate_dev); ++current_cdev_index; } else delete pstate_dev; // Add statically defined cooling devices size = sizeof(cpu_def_cooling_devices) / sizeof(cooling_dev_t); for (i = 0; i < size; ++i) { add_replace_cdev(&cpu_def_cooling_devices[i]); } // Add from XML cooling device config if (!parser_init() && parser.platform_matched()) { for (int i = 0; i < parser.cdev_count(); ++i) { cooling_dev_t *cdev_config = parser.get_cool_dev_index(i); if (!cdev_config) continue; add_replace_cdev(cdev_config); } } cthd_cdev_cpufreq *cpu_freq_dev = new cthd_cdev_cpufreq(current_cdev_index, -1); cpu_freq_dev->set_cdev_type("cpufreq"); if (cpu_freq_dev->update() == THD_SUCCESS) { cdevs.push_back(cpu_freq_dev); ++current_cdev_index; } else delete cpu_freq_dev; cthd_sysfs_cdev_rapl_dram *rapl_dram_dev = new cthd_sysfs_cdev_rapl_dram( current_cdev_index, 0); rapl_dram_dev->set_cdev_type("rapl_controller_dram"); if (rapl_dram_dev->update() == THD_SUCCESS) { cdevs.push_back(rapl_dram_dev); ++current_cdev_index; } else delete rapl_dram_dev; cthd_cdev *cdev = search_cdev("LCD"); if (!cdev) { cthd_cdev_backlight *backlight_dev = new cthd_cdev_backlight( current_cdev_index, 0); backlight_dev->set_cdev_type("LCD"); if (backlight_dev->update() == THD_SUCCESS) { cdevs.push_back(backlight_dev); ++current_cdev_index; } else delete backlight_dev; } // Dump all cooling devices for (unsigned i = 0; i < cdevs.size(); ++i) { cdevs[i]->cdev_dump(); } return THD_SUCCESS; } // Thermal engine cthd_engine *thd_engine; int thd_engine_create_default_engine(bool ignore_cpuid_check, bool exclusive_control, const char *conf_file) { thd_engine = new cthd_engine_default(); if (exclusive_control) thd_engine->set_control_mode(EXCLUSIVE); // Initialize thermald objects thd_engine->set_poll_interval(thd_poll_interval); if (conf_file) thd_engine->set_config_file(conf_file); if (thd_engine->thd_engine_start(ignore_cpuid_check) != THD_SUCCESS) { thd_log_error("THD engine start failed\n"); return THD_ERROR; } return THD_SUCCESS; } thermald-1.5/src/acpi_thermal_rel_ioct.h0000664000175000017500000000275712661205366017115 0ustar kingking#ifndef __ACPI_ACPI_THERMAL_H #define __ACPI_ACPI_THERMAL_H #include #define ACPI_THERMAL_MAGIC 's' #define ACPI_THERMAL_GET_TRT_LEN _IOR(ACPI_THERMAL_MAGIC, 1, unsigned long) #define ACPI_THERMAL_GET_ART_LEN _IOR(ACPI_THERMAL_MAGIC, 2, unsigned long) #define ACPI_THERMAL_GET_TRT_COUNT _IOR(ACPI_THERMAL_MAGIC, 3, unsigned long) #define ACPI_THERMAL_GET_ART_COUNT _IOR(ACPI_THERMAL_MAGIC, 4, unsigned long) #define ACPI_THERMAL_GET_TRT _IOR(ACPI_THERMAL_MAGIC, 5, unsigned long) #define ACPI_THERMAL_GET_ART _IOR(ACPI_THERMAL_MAGIC, 6, unsigned long) #ifndef __KERNEL__ #define u64 unsigned long long #endif union art_object { struct { char source_device[8]; /* ACPI single name */ char target_device[8]; /* ACPI single name */ u64 weight; u64 ac0_max_level; u64 ac1_max_level; u64 ac2_max_level; u64 ac3_max_level; u64 ac4_max_level; u64 ac5_max_level; u64 ac6_max_level; u64 ac7_max_level; u64 ac8_max_level; u64 ac9_max_level; }acpi_art_entry; u64 __data[13]; }; union trt_object { struct { char source_device[8]; /* ACPI single name */ char target_device[8]; /* ACPI single name */ u64 influence; u64 sample_period; u64 reserved[4]; } acpi_trt_entry; u64 __data[8]; }; #ifdef __KERNEL__ int acpi_thermal_rel_misc_device_add(acpi_handle handle); int acpi_thermal_rel_misc_device_remove(acpi_handle handle); #endif #endif /* __ACPI_ACPI_THERMAL_H */ thermald-1.5/src/thd_cdev_rapl_dram.h0000664000175000017500000000233712661205366016400 0ustar kingking/* * cthd_cdev_rapl_dram.h: thermal cooling class interface * using RAPL DRAM * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_RAPL_DRAM_H_ #define THD_CDEV_RAPL_DRAM_H_ #include "thd_cdev_rapl.h" class cthd_sysfs_cdev_rapl_dram: public cthd_sysfs_cdev_rapl { private: bool calculate_phy_max(); public: cthd_sysfs_cdev_rapl_dram(unsigned int _index, int _package) : cthd_sysfs_cdev_rapl(_index, _package) { } virtual int update(); }; #endif /* THD_CDEV_RAPL_DRAM_H_ */ thermald-1.5/src/thd_sensor_virtual.cpp0000664000175000017500000000375612661205366017056 0ustar kingking/* * thd_sensor_virtual.h: thermal sensor virtual class implementation * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_sensor_virtual.h" #include "thd_engine.h" cthd_sensor_virtual::cthd_sensor_virtual(int _index, std::string _type_str, std::string _link_type_str, double _multiplier, double _offset) : cthd_sensor(_index, "none", _type_str), link_sensor(NULL), link_type_str( _link_type_str), multiplier(_multiplier), offset(_offset) { virtual_sensor = true; } cthd_sensor_virtual::~cthd_sensor_virtual() { } int cthd_sensor_virtual::sensor_update() { cthd_sensor *sensor = thd_engine->search_sensor(link_type_str); if (sensor) link_sensor = sensor; else return THD_ERROR; return THD_SUCCESS; } unsigned int cthd_sensor_virtual::read_temperature() { unsigned int temp; temp = link_sensor->read_temperature(); temp = temp * multiplier + offset; thd_log_debug("cthd_sensor_virtual::read_temperature %u\n", temp); return temp; } int cthd_sensor_virtual::sensor_update_param(std::string new_dep_sensor, double slope, double intercept) { cthd_sensor *sensor = thd_engine->search_sensor(new_dep_sensor); if (sensor) link_sensor = sensor; else return THD_ERROR; multiplier = slope; offset = intercept; return THD_SUCCESS; } thermald-1.5/src/thd_zone_cpu.cpp0000664000175000017500000002054012661205366015607 0ustar kingking/* * thd_zone_dts.cpp: thermal engine DTS class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * * This implementation allows to use core temperature interface. */ /* Implementation of DTS sensor Zone. This * - Identifies DTS sensors, and use maximum reported temperature to control * - Prioritize the cooling device order * - Sets one control point starting from target temperature (max) not critical. * Very first time it reaches this temperature cthd_model, calculates a set point when * cooling device needs to be activated. * */ #include #include "thd_zone_cpu.h" #include "thd_engine_default.h" #include "thd_cdev_order_parser.h" const char *def_cooling_devices[] = { "rapl_controller", "intel_pstate", "intel_powerclamp", "cpufreq", "Processor", NULL }; cthd_zone_cpu::cthd_zone_cpu(int index, std::string path, int package_id) : cthd_zone(index, path, SENSORS_CORELATED), dts_sysfs(path.c_str()), critical_temp( 0), max_temp(0), set_point(0), prev_set_point(0), trip_point_cnt( 0), sensor_mask(0), phy_package_id(package_id), pkg_thres_th_zone( -1), pkg_temp_poll_enable(false) { type_str = "cpu"; thd_log_debug("zone dts syfs: %s, package id %d \n", path.c_str(), package_id); } int cthd_zone_cpu::init() { critical_temp = 0; int temp = 0; bool found = false; max_temp = 0; critical_temp = 0; // Calculate the temperature trip points using the settings in coretemp for (int i = 0; i < max_dts_sensors; ++i) { std::stringstream temp_crit_str; std::stringstream temp_max_str; temp_crit_str << "temp" << i << "_crit"; temp_max_str << "temp" << i << "_max"; if (dts_sysfs.exists(temp_crit_str.str())) { std::string temp_str; dts_sysfs.read(temp_crit_str.str(), temp_str); std::istringstream(temp_str) >> temp; if (critical_temp == 0 || temp < critical_temp) critical_temp = temp; } if (dts_sysfs.exists(temp_max_str.str())) { // Set which index is present sensor_mask = sensor_mask | (1 << i); std::string temp_str; dts_sysfs.read(temp_max_str.str(), temp_str); std::istringstream(temp_str) >> temp; if (max_temp == 0 || temp < max_temp) max_temp = temp; found = true; } else if (dts_sysfs.exists(temp_crit_str.str())) { thd_log_info( "DTS: MAX target temp not found, using (crit - offset) \n"); // Set which index is present sensor_mask = sensor_mask | (1 << i); std::string temp_str; dts_sysfs.read(temp_crit_str.str(), temp_str); std::istringstream(temp_str) >> temp; // Adjust offset from critical (target temperature for cooling) temp = temp - def_offset_from_critical; if (max_temp == 0 || temp < max_temp) max_temp = temp; found = true; } } if (!found) { thd_log_error("DTS temperature path not found \n"); return THD_ERROR; } thd_log_info("Core temp DTS :critical %d, max %d\n", critical_temp, max_temp); if (critical_temp == 0) critical_temp = def_critical_temp; if (max_temp == 0) { max_temp = def_critical_temp - def_offset_from_critical; thd_log_info("Force max temp to %d\n", max_temp); } else if ((critical_temp - max_temp) < def_offset_from_critical) { max_temp = critical_temp - def_offset_from_critical; thd_log_info("Buggy max temp: to close to critical %d\n", max_temp); } thd_model.set_max_temperature(max_temp + ((critical_temp - max_temp) / 2)); prev_set_point = set_point = thd_model.get_set_point(); return THD_SUCCESS; } int cthd_zone_cpu::load_cdev_xml(cthd_trip_point &trip_pt, std::vector &list) { cthd_cdev *cdev; for (unsigned int i = 0; i < list.size(); ++i) { thd_log_debug("- %s\n", list[i].c_str()); cdev = thd_engine->search_cdev(list[i]); if (cdev) { trip_pt.thd_trip_point_add_cdev(*cdev, cthd_trip_point::default_influence); } } return THD_SUCCESS; } int cthd_zone_cpu::parse_cdev_order() { cthd_cdev_order_parse parser; std::vector order_list; int ret = THD_ERROR; if ((ret = parser.parser_init()) == THD_SUCCESS) { if ((ret = parser.start_parse()) == THD_SUCCESS) { ret = parser.get_order_list(order_list); if (ret == THD_SUCCESS) { cthd_trip_point trip_pt_max(trip_point_cnt, MAX, set_point, def_hystersis, index, DEFAULT_SENSOR_ID); trip_pt_max.thd_trip_point_set_control_type(SEQUENTIAL); load_cdev_xml(trip_pt_max, order_list); trip_points.push_back(trip_pt_max); trip_point_cnt++; cthd_trip_point trip_pt_passive(trip_point_cnt, PASSIVE, max_temp, def_hystersis, index, DEFAULT_SENSOR_ID); trip_pt_passive.thd_trip_point_set_control_type(SEQUENTIAL); load_cdev_xml(trip_pt_passive, order_list); trip_points.push_back(trip_pt_passive); trip_point_cnt++; } } parser.parser_deinit(); return ret; } return ret; } int cthd_zone_cpu::read_trip_points() { int ret; cthd_cdev *cdev; int i; ret = parse_cdev_order(); if (ret == THD_SUCCESS) { thd_log_info("CDEVS order specified in thermal-cpu-cdev-order.xml\n"); return THD_SUCCESS; } cthd_trip_point trip_pt_max(trip_point_cnt, MAX, set_point, def_hystersis, index, DEFAULT_SENSOR_ID); trip_point_cnt++; cthd_trip_point trip_pt_passive(trip_point_cnt, PASSIVE, max_temp, def_hystersis, index, DEFAULT_SENSOR_ID); trip_pt_passive.thd_trip_point_set_control_type(SEQUENTIAL); trip_pt_max.thd_trip_point_set_control_type(SEQUENTIAL); i = 0; while (def_cooling_devices[i]) { cdev = thd_engine->search_cdev(def_cooling_devices[i]); if (cdev) { trip_pt_max.thd_trip_point_add_cdev(*cdev, cthd_trip_point::default_influence); trip_pt_passive.thd_trip_point_add_cdev(*cdev, cthd_trip_point::default_influence); } ++i; } trip_points.push_back(trip_pt_max); trip_points.push_back(trip_pt_passive); trip_point_cnt++; // Add active trip point at the end // This is required for setting up async trip point cthd_trip_point trip_pt_active(trip_point_cnt, ACTIVE, set_point, def_hystersis, index, DEFAULT_SENSOR_ID); trip_pt_active.thd_trip_point_set_control_type(SEQUENTIAL); cdev = thd_engine->search_cdev("Fan"); if (cdev) { trip_pt_active.thd_trip_point_add_cdev(*cdev, cthd_trip_point::default_influence); trip_points.push_back(trip_pt_active); trip_point_cnt++; } return THD_SUCCESS; } int cthd_zone_cpu::zone_bind_sensors() { cthd_sensor *sensor; int status = THD_ERROR; bool async_sensor = false; if (init() != THD_SUCCESS) return THD_ERROR; if (!thd_engine->rt_kernel_status()) { sensor = thd_engine->search_sensor("pkg-temp-0"); if (sensor) { bind_sensor(sensor); async_sensor = true; } } if (!thd_engine->rt_kernel_status()) { sensor = thd_engine->search_sensor("x86_pkg_temp"); if (sensor) { bind_sensor(sensor); async_sensor = true; } } sensor = thd_engine->search_sensor("soc_dts0"); if (sensor) { bind_sensor(sensor); async_sensor = true; } if (async_sensor) { sensor = thd_engine->search_sensor("hwmon"); if (sensor) { sensor->set_async_capable(true); } return THD_SUCCESS; } // No package temp sensor fallback to core temp int cnt = 0; unsigned int mask = 0x1; do { if (sensor_mask & mask) { std::stringstream temp_input_str; temp_input_str << "temp" << cnt << "_input"; cthd_sensor *sensor; sensor = thd_engine->search_sensor(temp_input_str.str()); if (sensor) { bind_sensor(sensor); status = THD_SUCCESS; } } mask = (mask << 1); cnt++; } while (mask != 0); if (status != THD_SUCCESS) { thd_log_info("Trying to bind hwmon sensor \n"); sensor = thd_engine->search_sensor("hwmon"); if (sensor) { bind_sensor(sensor); status = THD_SUCCESS; thd_log_info("Bind hwmon sensor \n"); } } return status; } int cthd_zone_cpu::read_cdev_trip_points() { return THD_SUCCESS; } thermald-1.5/src/thd_pid.h0000664000175000017500000000223712661205366014211 0ustar kingking/* * thd_pid.h: pid interface * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thermald.h" #include class cthd_pid { private: double err_sum, last_err; time_t last_time; unsigned int target_temp; public: cthd_pid(); double kp, ki, kd; int pid_output(unsigned int curr_temp); void set_target_temp(unsigned int temp) { target_temp = temp; } void reset() { err_sum = last_err = last_time = 0; } }; thermald-1.5/src/thd_cdev.h0000664000175000017500000001212412661205366014352 0ustar kingking/* * thd_cdev.h: thermal cooling class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_H #define THD_CDEV_H #include #include #include "thd_common.h" #include "thd_sys_fs.h" #include "thd_preference.h" #include "thd_pid.h" typedef struct { int zone; int trip; int target_value; } zone_trip_limits_t; #define ZONE_TRIP_LIMIT_COUNT 12 class cthd_cdev { protected: int index; csys_fs cdev_sysfs; unsigned int trip_point; int max_state; int min_state; int curr_state; unsigned long zone_mask; unsigned long trip_mask; int curr_pow; int base_pow_state; int inc_dec_val; bool auto_down_adjust; bool read_back; std::string type_str; int debounce_interval; time_t last_action_time; bool trend_increase; bool pid_enable; cthd_pid pid_ctrl; int last_state; std::vector zone_trip_limits; private: unsigned int int_2_pow(int pow) { int i; int _pow = 1; for (i = 0; i < pow; ++i) _pow = _pow * 2; return _pow; } int thd_cdev_exponential_controller(int set_point, int target_temp, int temperature, int state, int arg); public: static const int default_debounce_interval = 3; // In seconds cthd_cdev(unsigned int _index, std::string control_path) : index(_index), cdev_sysfs(control_path.c_str()), trip_point(0), max_state( 0), min_state(0), curr_state(0), zone_mask(0), trip_mask(0), curr_pow( 0), base_pow_state(0), inc_dec_val(1), auto_down_adjust( false), read_back(true), debounce_interval( default_debounce_interval), last_action_time(0), trend_increase( false), pid_enable(false), pid_ctrl(), last_state(0) { } virtual ~cthd_cdev() { } virtual int thd_cdev_set_state(int set_point, int target_temp, int temperature, int state, int zone_id, int trip_id, int target_value); virtual int thd_cdev_set_min_state(int zone_id); virtual void thd_cdev_set_min_state_param(int arg) { min_state = arg; } virtual void thd_cdev_set_max_state_param(int arg) { max_state = arg; } virtual void thd_cdev_set_read_back_param(bool arg) { read_back = arg; } virtual int thd_cdev_get_index() { return index; } virtual int init() { return 0; } ; virtual int control_begin() { if (pid_enable) { pid_ctrl.reset(); } return 0; } ; virtual int control_end() { return 0; } ; virtual void set_curr_state(int state, int arg) { } virtual void set_curr_state_raw(int state, int arg) { set_curr_state(state, arg); } virtual int get_curr_state() { return curr_state; } virtual int get_min_state() { return min_state; } virtual int get_max_state() { return max_state; } ; virtual int update() { return 0; } ; virtual void set_inc_dec_value(int value) { inc_dec_val = value; } virtual void set_down_adjust_control(bool value) { auto_down_adjust = value; } void set_debounce_interval(int interval) { debounce_interval = interval; } void set_min_state(int _min_state) { min_state = _min_state; } void set_max_state(int _max_state) { max_state = _max_state; } bool in_min_state() { if ((min_state < max_state && get_curr_state() <= min_state) || (min_state > max_state && get_curr_state() >= min_state)) return true; return false; } bool in_max_state() { if ((min_state < max_state && get_curr_state() >= get_max_state()) || (min_state > max_state && get_curr_state() <= get_max_state())) return true; return false; } int cmp_current_state(int state) { if (get_curr_state() == state) return 0; if (min_state < max_state) { if (state > get_curr_state()) return 1; else return -1; } if (min_state > max_state) { if (state > get_curr_state()) return -1; else return 1; } return 0; } std::string get_cdev_type() { return type_str; } std::string get_base_path() { return cdev_sysfs.get_base_path(); } void set_cdev_type(std::string _type_str) { type_str = _type_str; } void set_pid_param(double kp, double ki, double kd) { pid_ctrl.kp = kp; pid_ctrl.ki = ki; pid_ctrl.kd = kd; thd_log_info("set_pid_param %d [%g.%g,%g]\n", index, kp, ki, kd); } void enable_pid() { thd_log_info("PID control enabled %d\n", index); pid_enable = true; } void cdev_dump() { thd_log_info("%d: %s, C:%d MN: %d MX:%d ST:%d pt:%s rd_bk %d \n", index, type_str.c_str(), curr_state, min_state, max_state, inc_dec_val, get_base_path().c_str(), read_back); } }; #endif thermald-1.5/src/thd_rapl_power_meter.cpp0000664000175000017500000002056212661205366017337 0ustar kingking/* * thd_rapl_power_meter.cpp: thermal cooling class implementation * using RAPL * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_rapl_power_meter.h" #include #include #include static void *rapl_periodic_callback(void *data) { cthd_rapl_power_meter *rapl_cl = (cthd_rapl_power_meter*) data; for (;;) { if (!rapl_cl->rapl_energy_loop()) break; sleep(rapl_cl->rapl_callback_timeout); } return NULL; } cthd_rapl_power_meter::cthd_rapl_power_meter(unsigned int mask) : rapl_present(true), rapl_sysfs("/sys/class/powercap/intel-rapl/"), domain_list( 0), last_time(0), poll_thread(0), measure_mask(mask), enable_measurement( false) { if (rapl_sysfs.exists()) { thd_log_debug("RAPL sysfs present \n"); rapl_present = true; last_time = time(NULL); rapl_read_domains(rapl_sysfs.get_base_path()); } else { thd_log_warn("NO RAPL sysfs present \n"); rapl_present = false; } } void cthd_rapl_power_meter::rapl_read_domains(const char *dir_name) { int count = 0; csys_fs sys_fs; if (rapl_present) { DIR *dir; struct dirent *dir_entry; thd_log_debug("RAPL base path %s\n", dir_name); if ((dir = opendir(dir_name)) != NULL) { while ((dir_entry = readdir(dir)) != NULL) { std::string buffer; std::stringstream path; int status; rapl_domain_t domain; domain.half_way = 0; domain.energy_counter = 0; domain.energy_cumulative_counter = 0; domain.max_energy_range = 0; domain.max_energy_range_threshold = 0; domain.power = 0; domain.max_power = 0; domain.min_power = 0; domain.type = PACKAGE; if (!strcmp(dir_entry->d_name, ".") || !strcmp(dir_entry->d_name, "..")) continue; thd_log_debug("RAPL domain dir %s\n", dir_entry->d_name); path << dir_name << dir_entry->d_name << "/" << "name"; if (!sys_fs.exists(path.str())) { thd_log_debug(" %s doesn't exist\n", path.str().c_str()); continue; } status = sys_fs.read(path.str(), buffer); if (status < 0) continue; thd_log_debug("name %s\n", buffer.c_str()); if (fnmatch("package-*", buffer.c_str(), 0) == 0) { domain.type = PACKAGE; std::stringstream path; path << dir_name << dir_entry->d_name << "/"; rapl_read_domains(path.str().c_str()); } else if (buffer == "core") { domain.type = CORE; } else if (buffer == "uncore") { domain.type = UNCORE; } else if (buffer == "dram") { domain.type = DRAM; } if (measure_mask & domain.type) { domain.name = buffer; domain.path = std::string(dir_name) + std::string(dir_entry->d_name); domain_list.push_back(domain); ++count; } } closedir(dir); } else { thd_log_debug("opendir failed %s :%s\n", strerror(errno), rapl_sysfs.get_base_path()); } } thd_log_info("RAPL domain count %d\n", count); } void cthd_rapl_power_meter::rapl_enable_periodic_timer() { pthread_attr_init(&thd_attr); pthread_attr_setdetachstate(&thd_attr, PTHREAD_CREATE_DETACHED); pthread_create(&poll_thread, &thd_attr, rapl_periodic_callback, (void*) this); } bool cthd_rapl_power_meter::rapl_energy_loop() { csys_fs sys_fs; int status; unsigned long long counter; unsigned long long diff; time_t curr_time; if (!enable_measurement) return false; curr_time = time(NULL); if ((curr_time - last_time) <= 0) return true; for (unsigned int i = 0; i < domain_list.size(); ++i) { std::string buffer; std::string path; if (!domain_list[i].max_energy_range) { std::string _path; std::string _buffer; _path = domain_list[i].path + "/" + "max_energy_range_uj"; status = sys_fs.read(_path, _buffer); if (status >= 0) domain_list[i].max_energy_range = atoll(_buffer.c_str()) / 1000; domain_list[i].max_energy_range_threshold = domain_list[i].max_energy_range / 2; } path = domain_list[i].path + "/" + "energy_uj"; status = sys_fs.read(path, buffer); if (status >= 0) { counter = domain_list[i].energy_counter; domain_list[i].energy_counter = atoll(buffer.c_str()) / 1000; // To milli Js diff = 0; if (domain_list[i].half_way && domain_list[i].energy_counter < domain_list[i].max_energy_range_threshold) { // wrap around domain_list[i].energy_cumulative_counter += domain_list[i].max_energy_range; diff = domain_list[i].max_energy_range - counter; counter = 0; domain_list[i].half_way = 0; } else if (domain_list[i].energy_counter > domain_list[i].max_energy_range_threshold) domain_list[i].half_way = 1; if (counter) domain_list[i].power = (domain_list[i].energy_counter - counter + diff) / (curr_time - last_time); if (domain_list[i].power > domain_list[i].max_power) domain_list[i].max_power = domain_list[i].power; if (domain_list[i].min_power == 0) domain_list[i].min_power = domain_list[i].power; else if (domain_list[i].power < domain_list[i].min_power) domain_list[i].min_power = domain_list[i].power; thd_log_debug(" energy %d:%lld:%lld mj: %u mw \n", domain_list[i].type, domain_list[i].energy_cumulative_counter, domain_list[i].energy_counter + domain_list[i].energy_cumulative_counter, domain_list[i].power); } } last_time = curr_time; return true; } unsigned long long cthd_rapl_power_meter::rapl_action_get_energy( domain_type type) { unsigned long long value = 0; for (unsigned int i = 0; i < domain_list.size(); ++i) { if (type == domain_list[i].type) { value = (domain_list[i].energy_counter + domain_list[i].energy_cumulative_counter) * 1000; if (!value) { rapl_energy_loop(); value = (domain_list[i].energy_counter + domain_list[i].energy_cumulative_counter) * 1000; } break; } } return value; } unsigned int cthd_rapl_power_meter::rapl_action_get_power(domain_type type) { unsigned int value = 0; if (!rapl_present) return 0; for (unsigned int i = 0; i < domain_list.size(); ++i) { if (type == domain_list[i].type) { value = domain_list[i].power * 1000; if (!value) { rapl_energy_loop(); sleep(1); rapl_energy_loop(); value = domain_list[i].power * 1000; } break; } } return value; } unsigned int cthd_rapl_power_meter::rapl_action_get_max_power( domain_type type) { unsigned int value = 0; if (!rapl_present) return 0; for (unsigned int i = 0; i < domain_list.size(); ++i) { if (type == domain_list[i].type) { int status; std::string _path; std::string _buffer; csys_fs sys_fs; unsigned int const_0_val, const_1_val; const_0_val = 0; const_1_val = 0; _path = domain_list[i].path + "/" + "constraint_0_max_power_uw"; status = sys_fs.read(_path, _buffer); if (status >= 0) const_0_val = atoi(_buffer.c_str()); _path = domain_list[i].path + "/" + "constraint_1_max_power_uw"; status = sys_fs.read(_path, _buffer); if (status >= 0) const_1_val = atoi(_buffer.c_str()); value = const_1_val > const_0_val ? const_1_val : const_0_val; if (value) return value; } } return value; } unsigned int cthd_rapl_power_meter::rapl_action_get_power(domain_type type, unsigned int *max_power, unsigned int *min_power) { unsigned int value = 0; if (!rapl_present) return 0; for (unsigned int i = 0; i < domain_list.size(); ++i) { if (type == domain_list[i].type) { value = domain_list[i].power * 1000; if (!value) { rapl_energy_loop(); sleep(1); rapl_energy_loop(); value = domain_list[i].power * 1000; } *max_power = domain_list[i].max_power * 1000; *min_power = domain_list[i].min_power * 1000; break; } } return value; } void cthd_rapl_power_meter::rapl_measure_power() { if (rapl_present && enable_measurement) rapl_energy_loop(); } thermald-1.5/src/thd_zone_surface.h0000664000175000017500000000250712661205366016120 0ustar kingking/* * thd_zone_surface.h: zone interface for external surface * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_ZONE_SURFACE_H_ #define THD_ZONE_SURFACE_H_ #include "thd_zone_therm_sys_fs.h" #include "thd_engine.h" class cthd_zone_surface: public cthd_zone { private: cthd_sensor *sensor; public: static const int passive_trip_temp = 50000; static const int passive_trip_hyst = 1000; static const int surface_sampling_period = 12; cthd_zone_surface(int count); int read_trip_points(); int read_cdev_trip_points(); int zone_bind_sensors(); }; #endif /* THD_ZONE_SURFACE_H_ */ thermald-1.5/src/thd_model.h0000664000175000017500000000460512661205366014536 0ustar kingking/* * thd_model.h: thermal model class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef _THD_MODEL_H #define _THD_MODEL_H #include "thermald.h" #include #include #include class cthd_model { private: static const int def_max_temperature = 100 * 1000; static const unsigned int safety_margin = 1 * 1000; static const int angle_increment = 1; static const int def_setpoint_delay_cnt = 3; static const int max_compensation = 5000; static const unsigned int hot_zone_percent = 20; //20% static const time_t set_point_delay_tm = 4 * 3; // 12 seconds std::string zone_type; time_t trend_increase_start; int max_temp; int set_point; int hot_zone; int last_temp; time_t trend_decrease_start; time_t max_temp_reached; int current_angle; bool set_point_reached; int delay_cnt; bool max_temp_seen; bool updated_set_point; bool use_pid_param; time_t set_point_delay_start; bool user_forced_set_point_change; unsigned int update_set_point(unsigned int curr_temp); void store_set_point(); int read_set_point(); int read_user_set_max_temp(); double kp, ki, kd, err_sum, last_err; time_t last_time; public: cthd_model(std::string _zone_type, bool use_pid = false); void add_sample(int temperature); void set_max_temperature(int temp); bool update_user_set_max_temp(); void set_zone_type(std::string _zone_type) { zone_type = _zone_type; } void use_pid() { use_pid_param = true; } unsigned int get_set_point() { return set_point; } unsigned int get_hot_zone_trigger_point() { return hot_zone; } bool is_set_point_reached() { return (set_point_reached || updated_set_point); } ; }; #endif thermald-1.5/src/thd_sensor_virtual.h0000664000175000017500000000316312661205366016513 0ustar kingking/* * thd_sensor_virtual.h: thermal sensor virtual class interface * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_SENSOR_VIRTUAL_H_ #define THD_SENSOR_VIRTUAL_H_ #include "thd_sensor.h" class cthd_sensor_virtual: public cthd_sensor { private: cthd_sensor *link_sensor; std::string link_type_str; double multiplier; double offset; public: cthd_sensor_virtual(int _index, std::string _type_str, std::string _link_type_str, double multiplier, double offset); ~cthd_sensor_virtual(); int sensor_update(); unsigned int read_temperature(); virtual void sensor_dump() { if (link_sensor) thd_log_info("sensor index:%d %s virtual link %s %f %f \n", index, type_str.c_str(), link_sensor->get_sensor_type().c_str(), multiplier, offset); } int sensor_update_param(std::string new_dep_sensor, double slope, double intercept); }; #endif /* THD_SENSOR_VIRTUAL_H_ */ thermald-1.5/src/thd_cdev_rapl.h0000664000175000017500000000414212661205366015371 0ustar kingking/* * cthd_cdev_rapl.h: thermal cooling class interface * using RAPL * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_RAPL_H_ #define THD_CDEV_RAPL_H_ #include "thd_cdev.h" #include "thd_sys_fs.h" class cthd_sysfs_cdev_rapl: public cthd_cdev { protected: unsigned long phy_max; int package_id; int constraint_index; bool dynamic_phy_max_enable; unsigned int pl0_max_pwr; unsigned int pl0_min_pwr; unsigned int pl0_min_window; unsigned int pl0_step_pwr; bool bios_locked; virtual bool calculate_phy_max(); virtual bool read_ppcc_power_limits(); public: static const int rapl_no_time_windows = 6; static const long def_rapl_time_window = 1000000; // micro seconds static const unsigned int rapl_min_default_step = 500000; //0.5W static const int rapl_low_limit_percent = 25; static const int rapl_power_dec_percent = 5; cthd_sysfs_cdev_rapl(unsigned int _index, int package) : cthd_cdev(_index, "/sys/devices/virtual/powercap/intel-rapl/intel-rapl:0/"), phy_max( 0), package_id(package), constraint_index(0), dynamic_phy_max_enable( false), pl0_max_pwr(0), pl0_min_pwr(0), pl0_min_window(0), pl0_step_pwr( 0) { } virtual void set_curr_state(int state, int arg); virtual int get_curr_state(); virtual int get_max_state(); virtual int update(); virtual void set_curr_state_raw(int state, int arg); }; #endif /* THD_CDEV_RAPL_H_ */ thermald-1.5/src/thd_rapl_power_meter.h0000664000175000017500000000467712661205366017015 0ustar kingking/* * thd_rapl_power_meter.h: thermal cooling class interface * using RAPL * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_RAPL_POWER_METER_H_ #define THD_CDEV_RAPL_POWER_METER_H_ #include "thd_common.h" #include "thd_sys_fs.h" #include typedef enum { PACKAGE = 0x01, DRAM = 0x02, CORE = 0x04, UNCORE = 0x08 } domain_type; typedef struct { domain_type type; std::string name; std::string path; // Store in milli-units to have a bigger range unsigned long long max_energy_range; unsigned long long max_energy_range_threshold; int half_way; unsigned long long energy_cumulative_counter; unsigned long long energy_counter; unsigned int power; unsigned int max_power; unsigned int min_power; } rapl_domain_t; class cthd_rapl_power_meter { private: bool rapl_present; csys_fs rapl_sysfs; std::vector domain_list; time_t last_time; pthread_t poll_thread; pthread_attr_t thd_attr; unsigned int measure_mask; bool enable_measurement; public: static const int rapl_callback_timeout = 10; //seconds cthd_rapl_power_meter(unsigned int mask = PACKAGE | DRAM); void rapl_read_domains(const char *base_path); void rapl_enable_periodic_timer(); bool rapl_energy_loop(); void rapl_measure_power(); void rapl_start_measure_power() { enable_measurement = true; } void rapl_stop_measure_power() { enable_measurement = false; } // return in micro units to be compatible with kernel ABI unsigned long long rapl_action_get_energy(domain_type type); unsigned int rapl_action_get_power(domain_type type); unsigned int rapl_action_get_power(domain_type type, unsigned int *max_power, unsigned int *min_power); unsigned int rapl_action_get_max_power(domain_type type); }; #endif thermald-1.5/src/thd_zone_generic.h0000664000175000017500000000243312661205366016102 0ustar kingking/* * thd_zone_generic.h: zone interface for xml conf * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_ZONE_GENERIC_H_ #define THD_ZONE_GENERIC_H_ #include "thd_zone.h" class cthd_zone_generic: public cthd_zone { private: int trip_point_cnt; int config_index; cthd_zone *zone; std::vector sensor_list; public: cthd_zone_generic(int index, int _config_index, std::string type); virtual int read_trip_points(); virtual int read_cdev_trip_points(); virtual int zone_bind_sensors(); }; #endif /* THD_ZONE_GENERIC_H_ */ thermald-1.5/src/main.cpp0000664000175000017500000002163212661205366014055 0ustar kingking/* * main.cpp: Thermal Daemon entry point * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * * This is the main entry point for thermal daemon. This has main function * which parses command line arguments, set up dbus server and log related * functions. */ /* This implements main() function. This will parse command line options and * a new instance of cthd_engine object. By default it will create a engine * which uses dts engine, which DTS sensor and use P states to control * temperature, without any configuration. Alternatively if the * thermal-conf.xml has exact UUID match then it can use the zones and * cooling devices defined it to control thermals. This file will allow fine * tune ACPI thermal config or create new thermal config using custom * sensors. * Dbus interface allows user to switch between active/passive thermal controls * if the thermal-conf.xml defines parameters. */ #include #include #include "thermald.h" #include "thd_preference.h" #include "thd_engine.h" #include "thd_engine_default.h" #include "thd_parse.h" #include #if !defined(TD_DIST_VERSION) #define TD_DIST_VERSION PACKAGE_VERSION #endif extern int thd_dbus_server_init(void (*exit_handler)(int)); // Lock file static int lock_file_handle = -1; static const char *lock_file = TDRUNDIR "/thermald.pid"; // Default log level static int thd_log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING; // Daemonize or not static gboolean thd_daemonize; // Disable dbus static gboolean dbus_enable; // poll mode int thd_poll_interval = 4; //in seconds // check cpuid static gboolean ignore_cpuid_check = false; gboolean exclusive_control = FALSE; static GMainLoop *g_main_loop; // g_log handler. All logs will be directed here void thd_logger(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) { if (!(thd_log_level & log_level)) return; if (thd_daemonize) { int syslog_priority; switch (log_level) { case G_LOG_LEVEL_ERROR: syslog_priority = LOG_CRIT; break; case G_LOG_LEVEL_CRITICAL: syslog_priority = LOG_ERR; break; case G_LOG_LEVEL_WARNING: syslog_priority = LOG_WARNING; break; case G_LOG_LEVEL_MESSAGE: syslog_priority = LOG_NOTICE; break; case G_LOG_LEVEL_DEBUG: syslog_priority = LOG_DEBUG; break; case G_LOG_LEVEL_INFO: default: syslog_priority = LOG_INFO; break; } syslog(syslog_priority, "%s", message); } else g_print("%s", message); } void clean_up_lockfile(void) { if (lock_file_handle != -1) { (void) close(lock_file_handle); (void) unlink(lock_file); } } bool check_thermald_running() { lock_file_handle = open(lock_file, O_RDWR | O_CREAT, 0600); if (lock_file_handle == -1) { /* Couldn't open lock file */ thd_log_error("Could not open PID lock file %s, exiting\n", lock_file); return false; } /* Try to lock file */ if (lockf(lock_file_handle, F_TLOCK, 0) == -1) { /* Couldn't get lock on lock file */ thd_log_error("Couldn't get lock file %d\n", getpid()); close(lock_file_handle); return true; } return false; } // SIGTERM & SIGINT handler void sig_int_handler(int signum) { thd_engine->thd_engine_terminate(); sleep(1); if (g_main_loop) g_main_loop_quit(g_main_loop); delete thd_engine; clean_up_lockfile(); exit(EXIT_SUCCESS); } // main function int main(int argc, char *argv[]) { gboolean show_version = FALSE; gboolean log_info = FALSE; gboolean log_debug = FALSE; gboolean no_daemon = FALSE; gboolean test_mode = FALSE; gchar *conf_file = NULL; gint poll_interval = -1; gboolean success; GOptionContext *opt_ctx; thd_daemonize = TRUE; dbus_enable = FALSE; GOptionEntry options[] = { { "version", 0, 0, G_OPTION_ARG_NONE, &show_version, N_("Print thermald version and exit"), NULL }, { "no-daemon", 0, 0, G_OPTION_ARG_NONE, &no_daemon, N_( "Don't become a daemon: Default is daemon mode"), NULL }, { "loglevel=info", 0, 0, G_OPTION_ARG_NONE, &log_info, N_( "log severity: info level and up"), NULL }, { "loglevel=debug", 0, 0, G_OPTION_ARG_NONE, &log_debug, N_( "log severity: debug level and up: Max logging"), NULL }, { "test-mode", 0, 0, G_OPTION_ARG_NONE, &test_mode, N_( "Test Mode only: Allow non root user"), NULL }, { "poll-interval", 0, 0, G_OPTION_ARG_INT, &poll_interval, N_("Poll interval in seconds: Poll for zone temperature changes. " "If want to disable polling set to zero."), NULL }, { "dbus-enable", 0, 0, G_OPTION_ARG_NONE, &dbus_enable, N_( "Enable Dbus."), NULL }, { "exclusive-control", 0, 0, G_OPTION_ARG_NONE, &exclusive_control, N_( "Take over thermal control from kernel thermal driver."), NULL }, { "ignore-cpuid-check", 0, 0, G_OPTION_ARG_NONE, &ignore_cpuid_check, N_("Ignore CPU ID check."), NULL }, { "config-file", 0, 0, G_OPTION_ARG_STRING, &conf_file, N_( "configuration file"), NULL }, { NULL } }; if (!g_module_supported()) { fprintf(stderr, "GModules are not supported on your platform!\n"); exit(EXIT_FAILURE); } /* Set locale to be able to use environment variables */ setlocale(LC_ALL, ""); bindtextdomain(GETTEXT_PACKAGE, TDLOCALEDIR); bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); textdomain(GETTEXT_PACKAGE); /* Parse options */ opt_ctx = g_option_context_new(NULL); g_option_context_set_translation_domain(opt_ctx, GETTEXT_PACKAGE); g_option_context_set_ignore_unknown_options(opt_ctx, FALSE); g_option_context_set_help_enabled(opt_ctx, TRUE); g_option_context_add_main_entries(opt_ctx, options, NULL); g_option_context_set_summary(opt_ctx, "Thermal daemon monitors temperature sensors and decides the best action " "based on the temperature readings and user preferences."); success = g_option_context_parse(opt_ctx, &argc, &argv, NULL); g_option_context_free(opt_ctx); if (!success) { fprintf(stderr, "Invalid option. Please use --help to see a list of valid options.\n"); exit(EXIT_FAILURE); } if (show_version) { fprintf(stdout, TD_DIST_VERSION "\n"); exit(EXIT_SUCCESS); } if (getuid() != 0 && !test_mode) { fprintf(stderr, "You must be root to run thermald!\n"); exit(EXIT_FAILURE); } if (g_mkdir_with_parents(TDRUNDIR, 0755) != 0) { fprintf(stderr, "Cannot create '%s': %s", TDRUNDIR, strerror(errno)); exit(EXIT_FAILURE); } g_mkdir_with_parents(TDCONFDIR, 0755); // Don't care return value as directory // may already exist if (log_info) { thd_log_level |= G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO; } if (log_debug) { thd_log_level |= G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG; } if (poll_interval >= 0) { fprintf(stdout, "Polling enabled: %d\n", poll_interval); thd_poll_interval = poll_interval; } openlog("thermald", LOG_PID, LOG_USER | LOG_DAEMON | LOG_SYSLOG); // Don't care return val //setlogmask(LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_DEBUG | LOG_INFO); thd_daemonize = !no_daemon; g_log_set_handler(NULL, G_LOG_LEVEL_MASK, thd_logger, NULL); if (check_thermald_running()) { thd_log_error( "An instance of thermald is already running, exiting ...\n"); exit(EXIT_FAILURE); } if (no_daemon) { signal(SIGINT, sig_int_handler); signal(SIGTERM, sig_int_handler); } // Initialize the GType/GObject system g_type_init(); // Create a main loop that will dispatch callbacks g_main_loop = g_main_loop_new(NULL, FALSE); if (g_main_loop == NULL) { clean_up_lockfile(); thd_log_error("Couldn't create GMainLoop:\n"); return THD_FATAL_ERROR; } if (dbus_enable) thd_dbus_server_init(sig_int_handler); if (!no_daemon) { printf("Ready to serve requests: Daemonizing.. %d\n", thd_daemonize); thd_log_info( "thermald ver %s: Ready to serve requests: Daemonizing..\n", TD_DIST_VERSION); if (daemon(0, 0) != 0) { clean_up_lockfile(); thd_log_error("Failed to daemonize.\n"); return THD_FATAL_ERROR; } } if (thd_engine_create_default_engine((bool) ignore_cpuid_check, (bool) exclusive_control, conf_file) != THD_SUCCESS) { clean_up_lockfile(); closelog(); exit(EXIT_FAILURE); } // Start service requests on the D-Bus thd_log_debug("Start main loop\n"); g_main_loop_run(g_main_loop); thd_log_warn("Oops g main loop exit..\n"); fprintf(stdout, "Exiting ..\n"); clean_up_lockfile(); closelog(); } thermald-1.5/src/thd_cdev_therm_sys_fs.h0000664000175000017500000000243712661205366017145 0ustar kingking/* * cthd_sysfs_cdev.cpp: thermal cooling class interface * for thermal sysfs * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_THERM_SYS_FS_H_ #define THD_CDEV_THERM_SYS_FS_H_ #include "thd_cdev.h" class cthd_sysfs_cdev: public cthd_cdev { protected: public: cthd_sysfs_cdev(unsigned int _index, std::string control_path) : cthd_cdev(_index, control_path) { } virtual void set_curr_state(int state, int arg); virtual int get_curr_state(); virtual int get_max_state(); virtual int update(); }; #endif /* THD_CDEV_THERM_SYS_FS_H_ */ thermald-1.5/src/thd_msr.cpp0000664000175000017500000003540212661205366014571 0ustar kingking/* thd_msr.cpp: thermal engine msr class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ /* Abstracts all the MSR accesses for the thermal daemon. There shouldn't be any * MSR access other module. * */ #include "thd_msr.h" // MSR defines used in this module #define MSR_IA32_MISC_ENABLE 0x000001a0 #define MSR_IA32_MISC_ENABLE_TURBO_DISABLE (1ULL << 38) #define MSR_IA32_THERM_CONTROL 0x0000019a #define MSR_IA32_CLK_MOD_ENABLE (1ULL << 4) #define MSR_IA32_CLK_MOD_DUTY_CYCLE_MASK (0xF) #define MSR_IA32_PERF_CTL 0x0199 #define TURBO_DISENGAGE_BIT (1ULL << 32) #define PERF_CTL_CLK_SHIFT (8) #define PERF_CTL_CLK_MASK (0xff00) #define IA32_ENERGY_PERF_BIAS 0x01B0 #define MSR_IA32_PLATFORM_INFO 0xCE #define MSR_IA32_PLATFORM_INFO_MIN_FREQ(value) ((value >> 40) & 0xFF) #define MSR_IA32_PLATFORM_INFO_MAX_FREQ(value) ((value >> 8) & 0xFF) #define MSR_TURBO_RATIO_LIMIT 0x1AD #define TURBO_RATIO_1C_MASK 0xFF #define TURBO_RATIO_2C_MASK 0xFF00 #define TURBO_RATIO_2C_SHIFT (8) #define TURBO_RATIO_3C_MASK 0xFF0000 #define TURBO_RATIO_3C_SHIFT (16) #define TURBO_RATIO_4C_MASK 0xFF000000 #define TURBO_RATIO_4C_SHIFT (24) #define MSR_IA32_APERF 0xE8 #define MSR_IA32_MPERF 0xE7 cthd_msr::cthd_msr() : msr_sysfs("/dev/cpu/"), no_of_cpus(0) { } int cthd_msr::read_msr(int cpu, unsigned int idx, unsigned long long *val) { int ret = -1; std::stringstream file_name_str; file_name_str << cpu << "/msr"; if (msr_sysfs.exists(file_name_str.str())) { ret = msr_sysfs.read(file_name_str.str(), idx, (char*) val, sizeof(*val)); } if (ret < 0) { thd_log_warn("MSR READ Failed \n"); } return ret; } int cthd_msr::write_msr(int cpu, unsigned int idx, unsigned long long val) { int ret = -1; std::stringstream file_name_str; file_name_str << cpu << "/msr"; if (msr_sysfs.exists(file_name_str.str())) { ret = msr_sysfs.write(file_name_str.str(), idx, val); } if (ret < 0) { thd_log_warn("MSR WRITE Failed \n"); } return ret; } int cthd_msr::get_no_cpus() { int count = 0; if (no_of_cpus) return no_of_cpus; for (int i = 0; i < 64; ++i) { std::stringstream file_name_str; file_name_str << i; if (msr_sysfs.exists(file_name_str.str())) { count++; } } no_of_cpus = count; return count; } bool cthd_msr::check_turbo_status() { int cpu_count = get_no_cpus(); unsigned long long val; int ret; // Return false even if one of the core is not enabled for (int i = 0; i < cpu_count; ++i) { ret = read_msr(i, MSR_IA32_MISC_ENABLE, &val); if (ret < 0) return false; if (val & MSR_IA32_MISC_ENABLE_TURBO_DISABLE) return false; } return true; } int cthd_msr::enable_turbo_per_cpu(int cpu) { unsigned long long val; int ret; ret = read_msr(cpu, MSR_IA32_PERF_CTL, &val); if (ret < 0) return THD_ERROR; val &= ~TURBO_DISENGAGE_BIT; ret = write_msr(cpu, MSR_IA32_PERF_CTL, val); if (ret < 0) return THD_ERROR; return THD_SUCCESS; } int cthd_msr::enable_turbo() { int cpu_count = get_no_cpus(); unsigned long long val; int ret; for (int i = 0; i < cpu_count; ++i) { /* This method is recommended to be used only in BIOS ret = read_msr(i, MSR_IA32_MISC_ENABLE, &val); if (ret < 0) return THD_ERROR; val &= ~MSR_IA32_MISC_ENABLE_TURBO_DISABLE; ret = write_msr(i, MSR_IA32_MISC_ENABLE, val); if (ret < 0) return THD_ERROR; */ ret = read_msr(i, MSR_IA32_PERF_CTL, &val); if (ret < 0) return THD_ERROR; val &= ~TURBO_DISENGAGE_BIT; ret = write_msr(i, MSR_IA32_PERF_CTL, val); if (ret < 0) return THD_ERROR; } thd_log_info("Turbo enabled \n"); return THD_SUCCESS; } int cthd_msr::disable_turbo_per_cpu(int cpu) { unsigned long long val; int ret; ret = read_msr(cpu, MSR_IA32_PERF_CTL, &val); if (ret < 0) return THD_ERROR; val |= TURBO_DISENGAGE_BIT; ret = write_msr(cpu, MSR_IA32_PERF_CTL, val); if (ret < 0) return THD_ERROR; return THD_SUCCESS; } int cthd_msr::disable_turbo() { int cpu_count = get_no_cpus(); unsigned long long val; int ret; for (int i = 0; i < cpu_count; ++i) { /* This method is recommended only for BIOS ret = read_msr(i, MSR_IA32_MISC_ENABLE, &val); if (ret < 0) return THD_ERROR; val |= MSR_IA32_MISC_ENABLE_TURBO_DISABLE; ret = write_msr(i, MSR_IA32_MISC_ENABLE, val); if (ret < 0) return THD_ERROR; */ ret = read_msr(i, MSR_IA32_PERF_CTL, &val); if (ret < 0) return THD_ERROR; val |= TURBO_DISENGAGE_BIT; ret = write_msr(i, MSR_IA32_PERF_CTL, val); if (ret < 0) return THD_ERROR; } thd_log_info("Turbo disabled \n"); return THD_SUCCESS; } int cthd_msr::set_clock_mod_duty_cycle_per_cpu(int cpu, int state) { unsigned long long val; int ret; // First bit is reserved state = state << 1; ret = read_msr(cpu, MSR_IA32_THERM_CONTROL, &val); if (ret < 0) return THD_ERROR; if (!state) { val &= ~MSR_IA32_CLK_MOD_ENABLE; } else { val |= MSR_IA32_CLK_MOD_ENABLE; } val &= ~MSR_IA32_CLK_MOD_DUTY_CYCLE_MASK; val |= (state & MSR_IA32_CLK_MOD_DUTY_CYCLE_MASK); ret = write_msr(cpu, MSR_IA32_THERM_CONTROL, val); if (ret < 0) { thd_log_warn("set_clock_mod_duty_cycle current set failed to write\n"); return THD_ERROR; } return THD_SUCCESS; } int cthd_msr::set_clock_mod_duty_cycle(int state) { int cpu_count = get_no_cpus(); unsigned long long val; int ret; thd_log_info("Set T stated %d \n", state); // First bit is reserved state = state << 1; for (int i = 0; i < cpu_count; ++i) { ret = read_msr(i, MSR_IA32_THERM_CONTROL, &val); thd_log_debug("set_clock_mod_duty_cycle current %x\n", (unsigned int) val); if (ret < 0) return THD_ERROR; if (!state) { val &= ~MSR_IA32_CLK_MOD_ENABLE; } else { val |= MSR_IA32_CLK_MOD_ENABLE; } val &= ~MSR_IA32_CLK_MOD_DUTY_CYCLE_MASK; val |= (state & MSR_IA32_CLK_MOD_DUTY_CYCLE_MASK); thd_log_debug("set_clock_mod_duty_cycle current set to %x\n", (unsigned int) val); ret = write_msr(i, MSR_IA32_THERM_CONTROL, val); if (ret < 0) { thd_log_warn( "set_clock_mod_duty_cycle current set failed to write\n"); return THD_ERROR; } } return THD_SUCCESS; } int cthd_msr::get_clock_mod_duty_cycle() { int ret, state = 0; unsigned long long val; // Just get for cpu 0 and return ret = read_msr(0, MSR_IA32_THERM_CONTROL, &val); thd_log_debug("get_clock_mod_duty_cycle current %x\n", (unsigned int) val); if (ret < 0) return THD_ERROR; if (val & MSR_IA32_CLK_MOD_ENABLE) { state = val & MSR_IA32_CLK_MOD_DUTY_CYCLE_MASK; state = state >> 1; thd_log_debug("current state %x\n", state); } return state; } int cthd_msr::get_min_freq() { int ret; unsigned long long val; // Just get for cpu 0 and return ret = read_msr(0, MSR_IA32_PLATFORM_INFO, &val); if (ret < 0) return THD_ERROR; return MSR_IA32_PLATFORM_INFO_MIN_FREQ(val); } int cthd_msr::get_min_turbo_freq() { int ret; unsigned long long val; // Read turbo ratios ret = read_msr(0, MSR_TURBO_RATIO_LIMIT, &val); if (ret < 0) return THD_ERROR; // We are in a thermal zone. that means we already running all cores at full speed // So take the value for all 4 cores running val &= TURBO_RATIO_4C_MASK; if (val) return val >> TURBO_RATIO_4C_SHIFT; return 0; } int cthd_msr::get_max_turbo_freq() { int ret; unsigned long long val; // Read turbo ratios ret = read_msr(0, MSR_TURBO_RATIO_LIMIT, &val); if (ret < 0) return THD_ERROR; // We are in a thermal zone. that means we already running all cores at full speed // So take the value for all 4 cores running val &= 0xff; return val; } int cthd_msr::get_max_freq() { int ret; unsigned long long val; ret = read_msr(0, MSR_IA32_PLATFORM_INFO, &val); if (ret < 0) return THD_ERROR; return MSR_IA32_PLATFORM_INFO_MAX_FREQ(val); } int cthd_msr::dec_freq_state_per_cpu(int cpu) { unsigned long long val; int ret; int current_clock; ret = read_msr(cpu, MSR_IA32_PERF_CTL, &val); thd_log_debug("perf_ctl current %x\n", (unsigned int) val); if (ret < 0) return THD_ERROR; current_clock = (val >> 8) & 0xff; current_clock--; val = (current_clock << PERF_CTL_CLK_SHIFT); thd_log_debug("perf_ctl write %x\n", (unsigned int) val); ret = write_msr(cpu, MSR_IA32_PERF_CTL, val); if (ret < 0) { thd_log_warn("per control msr failded to write\n"); return THD_ERROR; } ret = read_msr(cpu, MSR_IA32_PERF_CTL, &val); thd_log_debug("perf_ctl read back %x\n", (unsigned int) val); if (ret < 0) return THD_ERROR; return THD_SUCCESS; } int cthd_msr::dec_freq_state() { int cpu_count = get_no_cpus(); unsigned long long val; int ret; int current_clock; thd_log_info("dec freq \n"); for (int i = 0; i < cpu_count; ++i) { ret = read_msr(i, MSR_IA32_PERF_CTL, &val); thd_log_debug("perf_ctl current %x\n", (unsigned int) val); if (ret < 0) return THD_ERROR; current_clock = (val >> 8) & 0xff; current_clock--; val = (current_clock << PERF_CTL_CLK_SHIFT); thd_log_debug("perf_ctl write %x\n", (unsigned int) val); ret = write_msr(i, MSR_IA32_PERF_CTL, val); if (ret < 0) { thd_log_warn("per control msr failed to write\n"); return THD_ERROR; } ret = read_msr(i, MSR_IA32_PERF_CTL, &val); thd_log_debug("perf_ctl read back %x\n", (unsigned int) val); if (ret < 0) return THD_ERROR; } return THD_SUCCESS; } int cthd_msr::inc_freq_state_per_cpu(int cpu) { unsigned long long val; int ret; int current_clock; ret = read_msr(cpu, MSR_IA32_PERF_CTL, &val); if (ret < 0) return THD_ERROR; current_clock = (val >> 8) & 0xff; current_clock++; val = (current_clock << PERF_CTL_CLK_SHIFT); ret = write_msr(cpu, MSR_IA32_PERF_CTL, val); if (ret < 0) { thd_log_warn("per control msr failded to write\n"); return THD_ERROR; } ret = read_msr(cpu, MSR_IA32_PERF_CTL, &val); thd_log_debug("perf_ctl read back %x\n", (unsigned int) val); if (ret < 0) return THD_ERROR; return THD_SUCCESS; } int cthd_msr::inc_freq_state() { int cpu_count = get_no_cpus(); unsigned long long val; int ret; int current_clock; thd_log_info("inc freq state \n"); for (int i = 0; i < cpu_count; ++i) { ret = read_msr(i, MSR_IA32_PERF_CTL, &val); if (ret < 0) return THD_ERROR; thd_log_debug("perf_ctl current %x\n", (unsigned int) val); current_clock = (val >> 8) & 0xff; current_clock++; val = (current_clock << PERF_CTL_CLK_SHIFT); thd_log_debug("perf_ctl write %x\n", (unsigned int) val); ret = write_msr(i, MSR_IA32_PERF_CTL, val); if (ret < 0) { thd_log_warn("per control msr failded to write\n"); return THD_ERROR; } ret = read_msr(i, MSR_IA32_PERF_CTL, &val); thd_log_debug("perf_ctl read back %x\n", (unsigned int) val); if (ret < 0) return THD_ERROR; } return THD_SUCCESS; } int cthd_msr::set_freq_state_per_cpu(int cpu, int state) { unsigned long long val; int ret; ret = read_msr(cpu, MSR_IA32_PERF_CTL, &val); if (ret < 0) return THD_ERROR; val &= ~PERF_CTL_CLK_MASK; val |= (state << PERF_CTL_CLK_SHIFT); thd_log_debug("perf_ctl current %x\n", (unsigned int) val); ret = write_msr(cpu, MSR_IA32_PERF_CTL, val); if (ret < 0) { thd_log_warn("per control msr failded to write\n"); return THD_ERROR; } #ifdef READ_BACK_VERIFY ret = read_msr(cpu, MSR_IA32_PERF_CTL, &val); thd_log_debug("perf_ctl read back %x\n", val); if(ret < 0) return THD_ERROR; #endif return THD_SUCCESS; } int cthd_msr::set_freq_state(int state) { int cpu_count = get_no_cpus(); unsigned long long val; int ret; thd_log_info("set_freq_state \n"); for (int i = 0; i < cpu_count; ++i) { ret = read_msr(i, MSR_IA32_PERF_CTL, &val); if (ret < 0) return THD_ERROR; val &= ~PERF_CTL_CLK_MASK; val |= (state << PERF_CTL_CLK_SHIFT); thd_log_debug("perf_ctl write %x\n", (unsigned int) val); ret = write_msr(i, MSR_IA32_PERF_CTL, val); if (ret < 0) { thd_log_warn("per control msr failded to write\n"); return THD_ERROR; } #ifdef READ_BACK_VERIFY ret = read_msr(i, MSR_IA32_PERF_CTL, &val); thd_log_debug("perf_ctl read back %x\n", val); if(ret < 0) return THD_ERROR; #endif } return THD_SUCCESS; } int cthd_msr::set_perf_bias_performace() { int cpu_count = get_no_cpus(); unsigned long long val; int ret; thd_log_info("set_perf_bias_performace \n"); val = 0; for (int i = 0; i < cpu_count; ++i) { ret = read_msr(i, IA32_ENERGY_PERF_BIAS, &val); if (ret < 0) { thd_log_warn("per control msr failed to read\n"); return THD_ERROR; } val &= ~0x0f; ret = write_msr(i, IA32_ENERGY_PERF_BIAS, val); if (ret < 0) { thd_log_warn("per control msr failed to write\n"); return THD_ERROR; } } return THD_SUCCESS; } int cthd_msr::set_perf_bias_balaced() { int cpu_count = get_no_cpus(); unsigned long long val; int ret; thd_log_info("set_perf_bias_balaced \n"); for (int i = 0; i < cpu_count; ++i) { ret = read_msr(i, IA32_ENERGY_PERF_BIAS, &val); if (ret < 0) { thd_log_warn("per control msr failed to read\n"); return THD_ERROR; } val &= ~0x0f; val |= 6; ret = write_msr(i, IA32_ENERGY_PERF_BIAS, val); if (ret < 0) { thd_log_warn("per control msr failed to write\n"); return THD_ERROR; } } return THD_SUCCESS; } int cthd_msr::set_perf_bias_energy() { int cpu_count = get_no_cpus(); unsigned long long val; int ret; thd_log_info("set_perf_bias_energy \n"); for (int i = 0; i < cpu_count; ++i) { ret = read_msr(i, IA32_ENERGY_PERF_BIAS, &val); if (ret < 0) { thd_log_warn("per control msr failed to read\n"); return THD_ERROR; } val &= ~0x0f; val |= 15; ret = write_msr(i, IA32_ENERGY_PERF_BIAS, val); if (ret < 0) { thd_log_warn("per control msr failed to write\n"); return THD_ERROR; } } return THD_SUCCESS; } int cthd_msr::get_mperf_value(int cpu, unsigned long long *value) { int ret; if (cpu >= get_no_cpus()) return THD_ERROR; ret = read_msr(cpu, MSR_IA32_MPERF, value); if (ret < 0) { thd_log_warn("get_mperf_value failed to read\n"); return THD_ERROR; } return THD_SUCCESS; } int cthd_msr::get_aperf_value(int cpu, unsigned long long *value) { int ret; if (cpu >= get_no_cpus()) return THD_ERROR; ret = read_msr(cpu, MSR_IA32_APERF, value); if (ret < 0) { thd_log_warn("get_Aperf_value failed to read\n"); return THD_ERROR; } return THD_SUCCESS; } thermald-1.5/src/thd_zone.h0000664000175000017500000001111212661205366014400 0ustar kingking/* * thd_zone.h: thermal zone class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_ZONE_H #define THD_ZONE_H #include #include "thd_common.h" #include "thd_sys_fs.h" #include "thd_preference.h" #include "thd_cdev.h" #include "thd_trip_point.h" #include "thd_sensor.h" #include "thd_model.h" typedef struct { int zone; int type; unsigned int data; } thermal_zone_notify_t; // If the zone has multiple sensors, there are two possibilities // Either the are independent, means that each has own set of trip points // Or related. In this case one trip point. Here we take max of the sensor reading // and then apply trip typedef enum { SENSOR_INDEPENDENT, SENSORS_CORELATED } sensor_relate_t; class cthd_zone { protected: int index; std::vector trip_points; std::string temperature_sysfs_path; csys_fs zone_sysfs; unsigned int zone_temp; bool zone_active; bool zone_cdev_binded_status; std::string type_str; std::vector sensors; sensor_relate_t sensor_rel; cthd_model thd_model; virtual int zone_bind_sensors() = 0; void thermal_zone_temp_change(int id, unsigned int temp, int pref); private: public: static const unsigned int def_async_trip_offset = 5000; cthd_zone(int _index, std::string control_path, sensor_relate_t rel = SENSOR_INDEPENDENT); virtual ~cthd_zone(); void zone_temperature_notification(int type, int data); int zone_update(); virtual void update_zone_preference(); void zone_reset(); virtual int read_trip_points() = 0; virtual int read_cdev_trip_points() = 0; virtual void read_zone_temp(); int get_zone_index() { return index; } void add_trip(cthd_trip_point &trip); void update_trip_temp(cthd_trip_point &trip); void set_zone_active() { zone_active = true; } ; void set_zone_inactive() { zone_active = false; } bool zone_active_status() { return zone_active; } bool zone_cdev_binded() { return zone_cdev_binded_status; } void zone_cdev_set_binded() { thd_log_info("zone %s bounded \n", type_str.c_str()); zone_cdev_binded_status = true; } std::string get_zone_type() { return type_str; } std::string get_zone_path() { return zone_sysfs.get_base_path(); } void set_zone_type(std::string type) { type_str = type; } void bind_sensor(cthd_sensor *sensor) { for (unsigned int i = 0; i < sensors.size(); ++i) { if (sensors[i] == sensor) return; } sensors.push_back(sensor); } // Even if one sensor, it is using doesn't // provide async control, return false bool check_sensor_async_status() { for (unsigned int i = 0; i < sensors.size(); ++i) { cthd_sensor *sensor = sensors[i]; if (!sensor->check_async_capable()) { return false; } } return true; } unsigned int get_trip_count() { return trip_points.size(); } int update_max_temperature(int max_temp); int update_psv_temperature(int psv_temp); int read_user_set_psv_temp(); int bind_cooling_device(trip_point_type_t type, unsigned int trip_temp, cthd_cdev *cdev, int influence, int sampling_period = 0, int target_state = TRIP_PT_INVALID_TARGET_STATE); int get_sensor_count() { return sensors.size(); } cthd_sensor *get_sensor_at_index(unsigned int index) { if (index < sensors.size()) return sensors[index]; else return NULL; } cthd_trip_point *get_trip_at_index(unsigned int index) { if (index < trip_points.size()) return &trip_points[index]; else return NULL; } void zone_dump() { thd_log_info("Zone %d: %s, Active:%d Bind:%d Sensor_cnt:%lu\n", index, type_str.c_str(), zone_active, zone_cdev_binded_status, (unsigned long) sensors.size()); thd_log_info("..sensors.. \n"); for (unsigned int i = 0; i < sensors.size(); ++i) { sensors[i]->sensor_dump(); } thd_log_info("..trips.. \n"); for (unsigned int i = 0; i < trip_points.size(); ++i) { trip_points[i].trip_dump(); } } ; }; #endif thermald-1.5/src/thd_sys_fs.cpp0000664000175000017500000001151012661205366015270 0ustar kingking/* * thd_sys_fs.cpp: sysfs class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_sys_fs.h" #include "thd_common.h" #include int csys_fs::write(const std::string &path, const std::string &buf) { std::string p = base_path + path; int fd = ::open(p.c_str(), O_WRONLY); if (fd < 0) { thd_log_warn("sysfs write failed %s\n", path.c_str()); return -errno; } int ret = ::write(fd, buf.c_str(), buf.size()); if (ret < 0) { ret = -errno; thd_log_warn("sysfs write failed %s\n", path.c_str()); } close(fd); return ret; } int csys_fs::write(const std::string &path, unsigned int position, unsigned long long data) { std::string p = base_path + path; int fd = ::open(p.c_str(), O_WRONLY); if (fd < 0) { thd_log_warn("sysfs write failed %s\n", path.c_str()); return -errno; } if (::lseek(fd, position, SEEK_CUR) == -1) { thd_log_warn("sysfs write failed %s\n", path.c_str()); close(fd); return -errno; } int ret = ::write(fd, &data, sizeof(data)); if (ret < 0) thd_log_warn("sysfs write failed %s\n", path.c_str()); close(fd); return ret; } int csys_fs::write(const std::string &path, unsigned int data) { std::ostringstream os; os << data; return csys_fs::write(path, os.str()); } int csys_fs::read(const std::string &path, char *buf, int len) { std::string p = base_path + path; int fd = ::open(p.c_str(), O_RDONLY); if (fd < 0) { thd_log_warn("sysfs read failed %s\n", path.c_str()); return -errno; } int ret = ::read(fd, buf, len); if (ret < 0) thd_log_warn("sysfs read failed %s\n", path.c_str()); close(fd); return ret; } int csys_fs::read(const std::string &path, unsigned int position, char *buf, int len) { std::string p = base_path + path; int fd = ::open(p.c_str(), O_RDONLY); if (fd < 0) { thd_log_warn("sysfs read failed %s\n", path.c_str()); return -errno; } if (::lseek(fd, position, SEEK_CUR) == -1) { thd_log_warn("sysfs read failed %s\n", path.c_str()); close(fd); return -errno; } int ret = ::read(fd, buf, len); if (ret < 0) thd_log_warn("sysfs read failed %s\n", path.c_str()); close(fd); return ret; } int csys_fs::read(const std::string &path, unsigned int *ptr_val) { std::string p = base_path + path; char str[16]; int ret; int fd = ::open(p.c_str(), O_RDONLY); if (fd < 0) { thd_log_warn("sysfs read failed %s\n", path.c_str()); return -errno; } ret = ::read(fd, str, sizeof(str)); if (ret > 0) *ptr_val = atoi(str); else thd_log_warn("sysfs read failed %s\n", path.c_str()); close(fd); return ret; } int csys_fs::read(const std::string &path, unsigned long *ptr_val) { std::string p = base_path + path; char str[32]; int ret; int fd = ::open(p.c_str(), O_RDONLY); if (fd < 0) { thd_log_warn("sysfs read failed %s\n", path.c_str()); return -errno; } ret = ::read(fd, str, sizeof(str)); if (ret > 0) *ptr_val = atol(str); else thd_log_warn("sysfs read failed %s\n", path.c_str()); close(fd); return ret; } int csys_fs::read(const std::string &path, std::string &buf) { std::string p = base_path + path; int ret = 0; #ifndef ANDROID try { #endif std::ifstream f(p.c_str(), std::fstream::in); if (f.fail()) { thd_log_warn("sysfs read failed %s\n", path.c_str()); return -EINVAL; } f >> buf; if (f.bad()) { thd_log_warn("sysfs read failed %s\n", path.c_str()); ret = -EIO; } f.close(); #ifndef ANDROID } catch (...) { thd_log_warn("csys_fs::read exception %s\n", path.c_str()); ret = -EIO; } #endif return ret; } bool csys_fs::exists(const std::string &path) { struct stat s; return (bool) (stat((base_path + path).c_str(), &s) == 0); } bool csys_fs::exists() { return csys_fs::exists(""); } mode_t csys_fs::get_mode(const std::string &path) { struct stat s; if (stat((base_path + path).c_str(), &s) == 0) return s.st_mode; else return 0; } int csys_fs::read_symbolic_link_value(const std::string &path, char *buf, int len) { std::string p = base_path + path; int ret = ::readlink(p.c_str(), buf, len); if (ret < 0) { *buf = '\0'; thd_log_warn("read_symbolic_link %s\n", path.c_str()); return -errno; } buf[ret] = '\0'; return 0; } thermald-1.5/src/thd_cdev_rapl.cpp0000664000175000017500000001777712661205366015746 0ustar kingking/* * cthd_cdev_rapl.cpp: thermal cooling class implementation * using RAPL * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_cdev_rapl.h" #include "thd_engine.h" /* This uses Intel RAPL driver to cool the system. RAPL driver show * mas thermal spec power in max_state. Each state can compensate * rapl_power_dec_percent, from the max state. * */ void cthd_sysfs_cdev_rapl::set_curr_state(int state, int arg) { std::stringstream tc_state_dev; std::stringstream state_str; int new_state, ret; if (bios_locked) return; if (state < inc_dec_val) { curr_state = 0; cdev_sysfs.write("enabled", "0"); new_state = phy_max; } else { if (dynamic_phy_max_enable) { if (!calculate_phy_max()) { curr_state = state; return; } } new_state = phy_max - state; curr_state = state; cdev_sysfs.write("enabled", "1"); } state_str << new_state; thd_log_debug("set cdev state index %d state %d wr:%d\n", index, state, new_state); tc_state_dev << "constraint_" << constraint_index << "_power_limit_uw"; ret = cdev_sysfs.write(tc_state_dev.str(), state_str.str()); if (ret < 0) { curr_state = (state == 0) ? 0 : max_state; if (ret == -ENODATA) { thd_log_info("powercap RAPL is BIOS locked, cannot update\n"); bios_locked = true; } } } void cthd_sysfs_cdev_rapl::set_curr_state_raw(int state, int arg) { std::stringstream state_str; std::stringstream tc_state_dev; int new_state, ret; if (bios_locked) return; if (state <= min_state) new_state = phy_max; else { if (dynamic_phy_max_enable) { if (!calculate_phy_max()) { curr_state = state; return; } } new_state = phy_max - state; } curr_state = state; state_str << new_state; tc_state_dev << "constraint_" << constraint_index << "_power_limit_uw"; ret = cdev_sysfs.write(tc_state_dev.str(), state_str.str()); if (ret < 0) { curr_state = (state == 0) ? 0 : max_state; if (ret == -ENODATA) { thd_log_info("powercap RAPL is BIOS locked, cannot update\n"); bios_locked = true; } } thd_log_debug("set cdev state raw index %d state %d wr:%d\n", index, state, new_state); } bool cthd_sysfs_cdev_rapl::calculate_phy_max() { if (dynamic_phy_max_enable) { unsigned int curr_max_phy; curr_max_phy = thd_engine->rapl_power_meter.rapl_action_get_power( PACKAGE); thd_log_debug("curr_phy_max = %u \n", curr_max_phy); if (curr_max_phy < rapl_min_default_step) return false; if (phy_max < curr_max_phy) { phy_max = curr_max_phy; set_inc_dec_value(phy_max * (float) rapl_power_dec_percent / 100); max_state = phy_max; max_state -= (float) max_state * rapl_low_limit_percent / 100; thd_log_debug("PHY_MAX %lu, step %d, max_state %d\n", phy_max, inc_dec_val, max_state); } } return true; } int cthd_sysfs_cdev_rapl::get_curr_state() { return curr_state; } int cthd_sysfs_cdev_rapl::get_max_state() { return max_state; } int cthd_sysfs_cdev_rapl::update() { int i; std::stringstream temp_str; int _index = -1; unsigned long constraint_phy_max; bool ppcc = false; std::string domain_name; for (i = 0; i < rapl_no_time_windows; ++i) { temp_str << "constraint_" << i << "_name"; if (cdev_sysfs.exists(temp_str.str())) { std::string type_str; cdev_sysfs.read(temp_str.str(), type_str); if (type_str == "long_term") { _index = i; break; } } } if (_index < 0) { thd_log_info("powercap RAPL no long term time window\n"); return THD_ERROR; } cdev_sysfs.read("name", domain_name); if (domain_name == "package-0") ppcc = read_ppcc_power_limits(); if (ppcc) { phy_max = pl0_max_pwr; set_inc_dec_value(pl0_step_pwr); max_state = pl0_max_pwr - pl0_min_pwr; } else { temp_str.str(std::string()); temp_str << "constraint_" << _index << "_max_power_uw"; if (!cdev_sysfs.exists(temp_str.str())) { thd_log_info("powercap RAPL no max power limit range %s \n", temp_str.str().c_str()); return THD_ERROR; } if (cdev_sysfs.read(temp_str.str(), &phy_max) < 0) { thd_log_info("%s:powercap RAPL invalid max power limit range \n", domain_name.c_str()); thd_log_info("Calculate dynamically phy_max \n"); phy_max = 0; thd_engine->rapl_power_meter.rapl_start_measure_power(); max_state = rapl_min_default_step; set_inc_dec_value(rapl_min_default_step); dynamic_phy_max_enable = true; return THD_SUCCESS; } std::stringstream temp_power_str; temp_power_str.str(std::string()); temp_power_str << "constraint_" << _index << "_power_limit_uw"; if (!cdev_sysfs.exists(temp_power_str.str())) { thd_log_info("powercap RAPL no power limit uw %s \n", temp_str.str().c_str()); return THD_ERROR; } if (cdev_sysfs.read(temp_power_str.str(), &constraint_phy_max) <= 0) { thd_log_info("powercap RAPL invalid max power limit range \n"); constraint_phy_max = 0; } if (constraint_phy_max > phy_max) { thd_log_info( "Default constraint power limit is more than max power %lu:%lu\n", constraint_phy_max, phy_max); phy_max = constraint_phy_max; } thd_log_info("powercap RAPL max power limit range %lu \n", phy_max); set_inc_dec_value(phy_max * (float) rapl_power_dec_percent / 100); max_state = phy_max; max_state -= (float) max_state * rapl_low_limit_percent / 100; } std::stringstream time_window; temp_str.str(std::string()); temp_str << "constraint_" << _index << "_time_window_us"; if (!cdev_sysfs.exists(temp_str.str())) { thd_log_info("powercap RAPL no time_window_us %s \n", temp_str.str().c_str()); return THD_ERROR; } if (pl0_min_window) time_window << pl0_min_window; else time_window << def_rapl_time_window; cdev_sysfs.write(temp_str.str(), time_window.str()); std::stringstream enable; temp_str.str(std::string()); temp_str << "enabled"; if (!cdev_sysfs.exists(temp_str.str())) { thd_log_info("powercap RAPL not enabled %s \n", temp_str.str().c_str()); return THD_ERROR; } cdev_sysfs.write(temp_str.str(), "0"); thd_log_debug("RAPL max limit %d increment: %d\n", max_state, inc_dec_val); constraint_index = _index; set_pid_param(1000, 100, 10); return THD_SUCCESS; } bool cthd_sysfs_cdev_rapl::read_ppcc_power_limits() { csys_fs sys_fs; if (sys_fs.exists("/sys/bus/pci/devices/0000:00:04.0/power_limits/")) sys_fs.update_path("/sys/bus/pci/devices/0000:00:04.0/power_limits/"); else if (sys_fs.exists("/sys/bus/pci/devices/0000:00:0b.0/power_limits/")) sys_fs.update_path("/sys/bus/pci/devices/0000:00:0b.0/power_limits/"); else if (sys_fs.exists( "/sys/bus/platform/devices/INT3401:00/power_limits/")) sys_fs.update_path( "/sys/bus/platform/devices/INT3401:00/power_limits/"); else return false; if (sys_fs.exists("power_limit_0_max_uw")) { if (sys_fs.read("power_limit_0_max_uw", &pl0_max_pwr) <= 0) return false; } if (sys_fs.exists("power_limit_0_min_uw")) { if (sys_fs.read("power_limit_0_min_uw", &pl0_min_pwr) <= 0) return false; } if (sys_fs.exists("power_limit_0_tmin_us")) { if (sys_fs.read("power_limit_0_tmin_us", &pl0_min_window) <= 0) return false; } if (sys_fs.exists("power_limit_0_step_uw")) { if (sys_fs.read("power_limit_0_step_uw", &pl0_step_pwr) <= 0) return false; } if (pl0_max_pwr && pl0_min_pwr && pl0_min_window && pl0_step_pwr) { thd_log_debug("ppcc limits max:%u min:%u min_win:%u step:%u\n", pl0_max_pwr, pl0_min_pwr, pl0_min_window, pl0_step_pwr); return true; } return false; } thermald-1.5/src/thd_rapl_interface.cpp0000664000175000017500000004013612661205366016746 0ustar kingking/* rapl_interface.cpp: rapl interface for power top implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include #include #include #include #include #include #include #include "thd_common.h" #include "thd_rapl_interface.h" #if 1 #define RAPL_DBG_PRINT thd_log_debug #define RAPL_ERROR_PRINT thd_log_warn #else #define RAPL_DBG_PRINT(...) ((void) 0) #define RAPL_ERROR_PRINT(...) ((void) 0) #endif #define RAPL_INFO_PRINT printf #define MAX_TEMP_STR_SIZE 20 // RAPL interface #define MSR_RAPL_POWER_UNIT 0x606 #define MSR_PKG_POWER_LIMIT 0x610 #define MSR_PKG_ENERY_STATUS 0x611 #define MSR_PKG_POWER_INFO 0x614 #define MSR_PKG_PERF_STATUS 0x613 #define MSR_DRAM_POWER_LIMIT 0x618 #define MSR_DRAM_ENERY_STATUS 0x619 #define MSR_DRAM_PERF_STATUS 0x61B #define MSR_DRAM_POWER_INFO 0x61c #define MSR_PP0_POWER_LIMIT 0x638 #define MSR_PP0_ENERY_STATUS 0x639 #define MSR_PP0_POLICY 0x63A #define MSR_PP0_PERF_STATUS 0x63B #define MSR_PP1_POWER_LIMIT 0x640 #define MSR_PP1_ENERY_STATUS 0x641 #define MSR_PP1_POLICY 0x642 #define PKG_DOMAIN_PRESENT 0x01 #define DRAM_DOMAIN_PRESENT 0x02 #define PP0_DOMAIN_PRESENT 0x04 #define PP1_DOMAIN_PRESENT 0x08 c_rapl_interface::c_rapl_interface(int cpu) : measurment_interval(def_sampling_interval), first_cpu(cpu), last_pkg_energy_status( 0.0), last_dram_energy_status(0.0), last_pp0_energy_status(0.0), last_pp1_energy_status( 0.0), default_pkg_power_limit_msr_value(0) { unsigned long long value; int ret; RAPL_INFO_PRINT("RAPL device for cpu %d\n", cpu); rapl_domains = 0; // presence of each domain // Check presence of PKG domain ret = read_msr(first_cpu, MSR_PKG_ENERY_STATUS, &value); if (ret > 0) { rapl_domains |= PKG_DOMAIN_PRESENT; RAPL_DBG_PRINT("Domain : PKG present\n"); } else { RAPL_DBG_PRINT("Domain : PKG Not present\n"); } #ifdef RAPL_SERVER_CONFIG // Check presence of DRAM domain ret = read_msr(first_cpu, MSR_DRAM_ENERY_STATUS, &value); if (ret > 0) { rapl_domains |= DRAM_DOMAIN_PRESENT; RAPL_DBG_PRINT("Domain : DRAM present\n"); } else { RAPL_DBG_PRINT("Domain : DRAM Not present\n"); } #endif // Check presence of PP0 domain ret = read_msr(first_cpu, MSR_PP0_ENERY_STATUS, &value); if (ret > 0) { rapl_domains |= PP0_DOMAIN_PRESENT; RAPL_DBG_PRINT("Domain : PP0 present\n"); } else { RAPL_DBG_PRINT("Domain : PP0 Not present\n"); } // Check presence of PP1 domain ret = read_msr(first_cpu, MSR_PP1_ENERY_STATUS, &value); if (ret > 0) { rapl_domains |= PP1_DOMAIN_PRESENT; RAPL_DBG_PRINT("Domain : PP1 present\n"); } else { RAPL_DBG_PRINT("Domain : PP1 Not present\n"); } power_units = get_power_unit(); energy_status_units = get_energy_status_unit(); time_units = get_time_unit(); RAPL_DBG_PRINT("power_units %g\n", power_units); RAPL_DBG_PRINT("energy_units %g\n", energy_status_units); RAPL_DBG_PRINT("time_units %g\n", time_units); RAPL_DBG_PRINT("RAPL Domain mask: %x\n", rapl_domains); } bool c_rapl_interface::pkg_domain_present() { if ((rapl_domains & PKG_DOMAIN_PRESENT)) { return true; } return false; } bool c_rapl_interface::dram_domain_present() { if ((rapl_domains & DRAM_DOMAIN_PRESENT)) { return true; } return false; } bool c_rapl_interface::pp0_domain_present() { if ((rapl_domains & PP0_DOMAIN_PRESENT)) { return true; } return false; } bool c_rapl_interface::pp1_domain_present() { if ((rapl_domains & PP1_DOMAIN_PRESENT)) { return true; } return false; } int c_rapl_interface::read_msr(int cpu, unsigned int idx, unsigned long long *val) { return msr.read_msr(cpu, idx, val); } int c_rapl_interface::write_msr(int cpu, unsigned int idx, unsigned long long val) { RAPL_DBG_PRINT("write_msr %X\n", (unsigned int) val); return msr.write_msr(cpu, idx, val); } int c_rapl_interface::get_rapl_power_unit(unsigned long long *value) { int ret; ret = read_msr(first_cpu, MSR_RAPL_POWER_UNIT, value); return ret; } double c_rapl_interface::get_power_unit() { int ret; unsigned long long value; double units; ret = get_rapl_power_unit(&value); if (ret < 0) { return ret; } units = (double) 1 / pow(2.0, (int) value & 0xf); if (units == 0.0) return THD_ERROR; return units; } double c_rapl_interface::get_energy_status_unit() { int ret; unsigned long long value; double units; ret = get_rapl_power_unit(&value); if (ret < 0) { return ret; } units = (double) 1 / pow(2.0, (int) (value & 0x1f00) >> 8); if (units == 0.0) return THD_ERROR; return units; } double c_rapl_interface::get_time_unit() { int ret; unsigned long long value; double units; ret = get_rapl_power_unit(&value); if (ret < 0) { return ret; } units = (double) 1 / pow(2.0, (int) (value & 0xf0000) >> 16); if (units == 0.0) return THD_ERROR; return units; } int c_rapl_interface::get_pkg_energy_status(double *status) { int ret; unsigned long long value; if (!pkg_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PKG_ENERY_STATUS, &value); if (ret < 0) { RAPL_ERROR_PRINT("get_pkg_energy_status failed\n"); return ret; } *status = (double) (value & 0xffffffff) * get_energy_status_unit(); return ret; } int c_rapl_interface::get_pkg_power_info(double *thermal_spec_power, double *max_power, double *min_power, double *max_time_window) { int ret; unsigned long long value; if (!pkg_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PKG_POWER_INFO, &value); if (ret < 0) { RAPL_ERROR_PRINT("get_pkg_power_info failed\n"); return ret; } *thermal_spec_power = (value & 0x7FFF) * power_units; *min_power = ((value & 0x7FFF0000) >> 16) * power_units; *max_power = ((value & 0x7FFF00000000) >> 32) * power_units; *max_time_window = ((value & 0x3f000000000000) >> 48) * time_units; return ret; } int c_rapl_interface::get_pkg_power_limit_msr(unsigned long long *value) { int ret; if (!pkg_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PKG_POWER_LIMIT, value); if (ret < 0) { RAPL_ERROR_PRINT("get_pkg_power_limit failed\n"); return ret; } return ret; } int c_rapl_interface::set_pkg_power_limit_msr(unsigned long long value) { int ret; RAPL_DBG_PRINT("set_pkg_power_limit_msr %X\n", (unsigned int) value); if (!pkg_domain_present()) { return -1; } ret = write_msr(first_cpu, MSR_PKG_POWER_LIMIT, value); if (ret < 0) { RAPL_ERROR_PRINT("set_pkg_power_limit failed\n"); return ret; } return ret; } // power is in milliwatts int c_rapl_interface::set_pkg_power_limit(int time_window, int power) { /* Package Power Limit #1(bits 14:0): Sets the average power usage limit of the package domain corresponding to time window # 1. The unit of this field is specified by the “Power Units” field of MSR_RAPL_POWER_UNIT. • Enable Power Limit #1(bit 15): 0 = disabled; 1 = enabled. • • Time Window for Power Limit #1 (bits 23:17): Indicates the time window for power limit #1 Package Clamping Limitation #1 (bit 16): Allow going below OS-requested P/T state setting during time window specified by bits 23:17. Time limit = 2^Y * (1.0 + Z/4.0) * Time_Unit Here “Y” is the unsigned integer value represented. by bits 21:17, “Z” is an unsigned integer represented by bits 23:22. “Time_Unit” is specified by the “Time Units” field of MSR_RAPL_POWER_UNIT. */ unsigned long long value = default_pkg_power_limit_msr_value; unsigned int power_limit_mask = 0x7fff; unsigned int power_limit_en_bit = 0x8000; unsigned int power_clamp_en_bit = 0x10000; double time_limit; // = 2^Y * (1.0 + Z/4.0) * Time_Unit unsigned int y, z; int time_limit_int; RAPL_DBG_PRINT("set_pkg_power_limit tm %d %d \n", time_window, power); power = (int) ((double) power / 1000 / power_units); RAPL_DBG_PRINT("power / power units %d \n", power); value = (value & ~power_limit_mask) | power; value |= (power_limit_en_bit | power_clamp_en_bit); RAPL_DBG_PRINT("Try Limit with power %X\n", (unsigned int) value); time_limit = time_window / time_units; #ifdef ANDROID y = (int)log(time_limit) * 1.442695; #else y = (int) log2(time_limit); #endif z = 4 * (time_limit - (1 << y)) / (1 << y); time_limit_int = ((y & 0x1f) | ((z & 0x3) << 5)); RAPL_DBG_PRINT("time_limit %g %d\n", time_limit, time_limit_int); value &= ~0xFE0000; value |= time_limit_int << 17; RAPL_DBG_PRINT("Try new Limit %X\n", (unsigned int) value); return set_pkg_power_limit_msr(value); } int c_rapl_interface::store_pkg_power_limit() { unsigned long long value; int ret; ret = get_pkg_power_limit_msr(&value); if (ret < 0) return ret; default_pkg_power_limit_msr_value = value; RAPL_DBG_PRINT("store: default_pkg_power_limit_msr_value %X\n", (unsigned int) default_pkg_power_limit_msr_value); return 0; } int c_rapl_interface::restore_pkg_power_limit() { if (default_pkg_power_limit_msr_value) set_pkg_power_limit_msr(default_pkg_power_limit_msr_value); RAPL_DBG_PRINT("restore: default_pkg_power_limit_msr_value %X\n", (unsigned int) default_pkg_power_limit_msr_value); return 0; } int c_rapl_interface::get_dram_energy_status(double *status) { int ret; unsigned long long value; if (!dram_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_DRAM_ENERY_STATUS, &value); if (ret < 0) { RAPL_ERROR_PRINT("get_dram_energy_status failed\n"); return ret; } *status = (double) (value & 0xffffffff) * get_energy_status_unit(); return ret; } int c_rapl_interface::get_dram_power_info(double *thermal_spec_power, double *max_power, double *min_power, double *max_time_window) { int ret; unsigned long long value; if (!dram_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_DRAM_POWER_INFO, &value); if (ret < 0) { RAPL_ERROR_PRINT("get_dram_power_info failed\n"); return ret; } *thermal_spec_power = (value & 0x7FFF) * power_units; *min_power = ((value & 0x7FFF0000) >> 16) * power_units; *max_power = ((value & 0x7FFF00000000) >> 32) * power_units; *max_time_window = ((value & 0x3f000000000000) >> 48) * time_units; return ret; } int c_rapl_interface::get_dram_power_limit(unsigned long long *value) { int ret; if (!dram_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_DRAM_POWER_LIMIT, value); if (ret < 0) { RAPL_ERROR_PRINT("get_dram_power_limit failed\n"); return ret; } return ret; } int c_rapl_interface::set_dram_power_limit(unsigned long long value) { int ret; if (!dram_domain_present()) { return -1; } ret = write_msr(first_cpu, MSR_DRAM_POWER_LIMIT, value); if (ret < 0) { RAPL_ERROR_PRINT("set_dram_power_limit failed\n"); return ret; } return ret; } int c_rapl_interface::get_pp0_energy_status(double *status) { int ret; unsigned long long value; if (!pp0_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PP0_ENERY_STATUS, &value); if (ret < 0) { RAPL_ERROR_PRINT("get_pp0_energy_status failed\n"); return ret; } *status = (double) (value & 0xffffffff) * get_energy_status_unit(); return ret; } int c_rapl_interface::get_pp0_power_limit(unsigned long long *value) { int ret; if (!pp0_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PP0_POWER_LIMIT, value); if (ret < 0) { RAPL_ERROR_PRINT("get_pp0_power_limit failed\n"); return ret; } return ret; } int c_rapl_interface::set_pp0_power_limit(unsigned long long value) { int ret; if (!pp0_domain_present()) { return -1; } ret = write_msr(first_cpu, MSR_PP0_POWER_LIMIT, value); if (ret < 0) { RAPL_ERROR_PRINT("set_pp0_power_limit failed\n"); return ret; } return ret; } int c_rapl_interface::get_pp0_power_policy(unsigned int *pp0_power_policy) { int ret; unsigned long long value; if (!pp0_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PP0_POLICY, &value); if (ret < 0) { RAPL_ERROR_PRINT("get_pp0_power_policy failed\n"); return ret; } *pp0_power_policy = value & 0x0f; return ret; } int c_rapl_interface::get_pp1_energy_status(double *status) { int ret; unsigned long long value; if (!pp1_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PP1_ENERY_STATUS, &value); if (ret < 0) { RAPL_ERROR_PRINT("get_pp1_energy_status failed\n"); return ret; } *status = (double) (value & 0xffffffff) * get_energy_status_unit(); return ret; } int c_rapl_interface::get_pp1_power_limit(unsigned long long *value) { int ret; if (!pp1_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PP1_POWER_LIMIT, value); if (ret < 0) { RAPL_ERROR_PRINT("get_pp1_power_info failed\n"); return ret; } return ret; } int c_rapl_interface::set_pp1_power_limit(unsigned long long value) { int ret; if (!pp1_domain_present()) { return -1; } ret = write_msr(first_cpu, MSR_PP1_POWER_LIMIT, value); if (ret < 0) { RAPL_ERROR_PRINT("set_pp1_power_limit failed\n"); return ret; } return ret; } int c_rapl_interface::get_pp1_power_policy(unsigned int *pp1_power_policy) { int ret; unsigned long long value; if (!pp1_domain_present()) { return -1; } ret = read_msr(first_cpu, MSR_PP1_POLICY, &value); if (ret < 0) { RAPL_ERROR_PRINT("get_pp1_power_policy failed\n"); return ret; } *pp1_power_policy = value & 0x0f; return ret; } void c_rapl_interface::rapl_measure_energy() { #ifdef RAPL_TEST_MODE int ret; double energy_status; double thermal_spec_power; double max_power; double min_power; double max_time_window; double pkg_watts = 0; double dram_watts = 0; double pp0_watts = 0; double pp1_watts = 0; double pkg_joules = 0; double dram_joules = 0; double pp0_joules = 0; double pp1_joules = 0; ret = get_pkg_power_info(&thermal_spec_power, &max_power, &min_power, &max_time_window); RAPL_DBG_PRINT("Pkg Power Info: Thermal spec %f watts, max %f watts, min %f watts, max time window %f seconds\n", thermal_spec_power, max_power, min_power, max_time_window); ret = get_dram_power_info(&thermal_spec_power, &max_power, &min_power, &max_time_window); RAPL_DBG_PRINT("DRAM Power Info: Thermal spec %f watts, max %f watts, min %f watts, max time window %f seconds\n", thermal_spec_power, max_power, min_power, max_time_window); for (;;) { if (pkg_domain_present()) { ret = get_pkg_energy_status(&energy_status); if (last_pkg_energy_status == 0) last_pkg_energy_status = energy_status; if (ret > 0) { pkg_joules = energy_status; pkg_watts = (energy_status-last_pkg_energy_status)/measurment_interval; } last_pkg_energy_status = energy_status; } if (dram_domain_present()) { ret = get_dram_energy_status(&energy_status); if (last_dram_energy_status == 0) last_dram_energy_status = energy_status; if (ret > 0) { dram_joules = energy_status; dram_watts = (energy_status-last_dram_energy_status)/measurment_interval; } last_dram_energy_status = energy_status; } if (pp0_domain_present()) { ret = get_pp0_energy_status(&energy_status); if (last_pp0_energy_status == 0) last_pp0_energy_status = energy_status; if (ret > 0) { pp0_joules = energy_status; pp0_watts = (energy_status-last_pp0_energy_status)/measurment_interval; } last_pp0_energy_status = energy_status; } if (pp1_domain_present()) { ret = get_pp1_energy_status(&energy_status); if (last_pp1_energy_status == 0) last_pp1_energy_status = energy_status; if (ret > 0) { pp1_joules = energy_status; pp1_watts = (energy_status-last_pp1_energy_status)/measurment_interval; } last_pp1_energy_status = energy_status; } RAPL_DBG_PRINT("%f, %f, %f, %f\n", pkg_watts, dram_watts, pp0_watts, pp1_watts); sleep(measurment_interval); } #endif } thermald-1.5/src/thd_trt_art_reader.h0000664000175000017500000000452212661205366016435 0ustar kingking/* * thd_trt_art_reader.h: Interface for configuration using ACPI * _ART and _TRT tables * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_TRT_ART_READER_H_ #define THD_TRT_ART_READER_H_ #include #include #include #include #include #include #include #include #include #include struct rel_object_t { std::string target_device; std::string target_sensor; std::vector trt_objects; std::vector art_objects; rel_object_t(std::string name) { target_device = name; target_sensor = name; } }; struct object_finder { object_finder(char *key) : obj_key(key) { } bool operator()(const rel_object_t& o) const { return obj_key == o.target_device; } const std::string obj_key; }; class cthd_acpi_rel { private: std::string rel_cdev; std::string xml_hdr; std::string conf_begin; std::string conf_end; std::string output_file_name; std::ofstream conf_file; std::vector rel_list; unsigned char *trt_data; unsigned int trt_count; unsigned char *art_data; unsigned int art_count; int read_trt(); void dump_trt(); void create_platform_conf(); void create_platform_pref(int perf); void create_thermal_zones(); void create_thermal_zone(std::string type); void add_passive_trip_point(rel_object_t &rel_obj); void add_active_trip_point(rel_object_t &rel_obj); void parse_target_devices(); int read_art(); void dump_art(); public: std::string indentation; cthd_acpi_rel(); int generate_conf(std::string file_name); }; #endif /* THD_TRT_ART_READER_H_ */ thermald-1.5/src/thd_zone_therm_sys_fs.h0000664000175000017500000000257212661205366017177 0ustar kingking/* * thd_zone_therm_sys_fs.h: thermal zone class interface * for thermal sysfs * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_ZONE_THERM_SYS_FS_H_ #define THD_ZONE_THERM_SYS_FS_H_ #include "thd_zone.h" class cthd_sysfs_zone: public cthd_zone { private: int trip_point_cnt; cthd_zone *zone; std::vector initial_trip_values; public: static const int max_trip_points = 50; static const int max_cool_devs = 50; cthd_sysfs_zone(int count, std::string path); ~cthd_sysfs_zone(); virtual int read_trip_points(); virtual int read_cdev_trip_points(); virtual int zone_bind_sensors(); }; #endif /* THD_ZONE_THERM_SYS_FS_H_ */ thermald-1.5/src/thd_cdev_intel_pstate_driver.h0000664000175000017500000000317212661205366020503 0ustar kingking/* * thd_sysfs_intel_pstate_driver.h: thermal cooling class interface * using Intel p state driver * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_INTEL_PSATATE_DRIVER_H_ #define THD_CDEV_INTEL_PSATATE_DRIVER_H_ #include "thd_cdev.h" class cthd_intel_p_state_cdev: public cthd_cdev { private: float unit_value; int min_compensation; int max_offset; bool turbo_status; void set_turbo_disable_status(bool enable); public: static const int intel_pstate_limit_ratio = 2; static const int default_max_state = 10; static const int turbo_disable_percent = 70; cthd_intel_p_state_cdev(unsigned int _index) : cthd_cdev(_index, "/sys/devices/system/cpu/intel_pstate/"), unit_value( 1), min_compensation(0), max_offset(0), turbo_status(false) { } ; void set_curr_state(int state, int arg); int get_max_state(); int update(); }; #endif /* THD_CDEV_INTEL_PSATATE_DRIVER_H_ */ thermald-1.5/src/thd_model.cpp0000664000175000017500000001675712661205366015104 0ustar kingking/* * thd_model.h: thermal model class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_model.h" #include "thd_engine.h" #include "thd_zone.h" #include #include #include #include #include #include #include /* * Dynamically adjust set point based on the amount of time spent on hot zone. */ cthd_model::cthd_model(std::string _zone_type, bool use_pid) : zone_type(_zone_type), trend_increase_start(0), max_temp( def_max_temperature), set_point(def_max_temperature), hot_zone( 0), last_temp(0), trend_decrease_start(0), max_temp_reached(0), current_angle( 0), set_point_reached(false), delay_cnt(0), max_temp_seen( false), updated_set_point(false), use_pid_param(use_pid), set_point_delay_start( 0), user_forced_set_point_change(false) { // set default pid parameters kp = 0.5; ki = kd = 0.0001; last_time = 0; err_sum = 0.0; last_err = 0.0; } unsigned int cthd_model::update_set_point(unsigned int curr_temp) { if (!use_pid_param) { double slope; double delta_x = (max_temp_reached - trend_increase_start) * 1000; double delta_y = max_temp - hot_zone; int _setpoint; double radians; double arc_len; if (delta_y > 0 && delta_x > 0) { slope = delta_y / delta_x; radians = atan(slope); thd_log_info("current slope %g angle before %g (%g degree)\n", slope, radians, 57.2957795 * radians); radians += (0.01746 * (current_angle + angle_increment)); thd_log_info("current slope %g angle before %g (%g degree)\n", slope, radians, 57.2957795 * radians); arc_len = delta_x * tan(radians); _setpoint = max_temp - (unsigned int) (arc_len - delta_y); _setpoint = _setpoint - _setpoint % 1000; thd_log_info("** set point x:%g y:%g arc_len:%g set_point %d\n", delta_x, delta_y, arc_len, _setpoint); if ((_setpoint < 0) || (abs(set_point - _setpoint) > max_compensation)) set_point -= max_compensation; else set_point = _setpoint; if (set_point < hot_zone) set_point = hot_zone; current_angle += angle_increment; } return set_point; } else { double output; double d_err = 0; int _setpoint; time_t now; time(&now); if (last_time == 0) last_time = now; time_t timeChange = (now - last_time); int error = curr_temp - max_temp; err_sum += (error * timeChange); if (timeChange) d_err = (error - last_err) / timeChange; else d_err = 0.0; /*Compute PID Output*/ output = kp * error + ki * err_sum + kd * d_err; _setpoint = max_temp - (unsigned int) output; thd_log_info("update_pid %ld %ld %d %g %d\n", now, last_time, error, output, _setpoint); if ((_setpoint < 0) || (abs(set_point - _setpoint) > max_compensation)) set_point -= max_compensation; else set_point = _setpoint; if (set_point < hot_zone) set_point = hot_zone; /*Remember some variables for next time*/ last_err = error; last_time = now; return set_point; } } void cthd_model::add_sample(int temperature) { time_t tm; time(&tm); updated_set_point = false; if (trend_increase_start == 0 && temperature > hot_zone) { trend_increase_start = tm; thd_log_debug("Trend increase start %ld\n", trend_increase_start); } else if (trend_increase_start && temperature < hot_zone) { int _set_point; thd_log_debug("Trend increase stopped %ld\n", trend_increase_start); trend_increase_start = 0; _set_point = read_set_point(); // Restore set point to a calculated max if (_set_point > set_point) { set_point = _set_point; updated_set_point = true; current_angle = 0; // Reset PID params err_sum = last_err = 0.0; last_time = 0; } } if (temperature > max_temp) { max_temp_reached = tm; // Very first time when we reached max temp // then we need to start tuning if (!max_temp_seen) { int _set_point; update_set_point(temperature); _set_point = read_set_point(); // Update only if the current set point is more than // the stored one. if (_set_point == 0 || set_point > _set_point) store_set_point(); max_temp_seen = true; } // Give some time to cooling device to cool, after that set next set point if (set_point_delay_start && (tm - set_point_delay_start) >= set_point_delay_tm && (last_temp < temperature)) update_set_point(temperature); delay_cnt++; if (!set_point_delay_start) set_point_delay_start = tm; set_point_reached = true; } else { set_point_reached = false; delay_cnt = 0; set_point_delay_start = 0; } if (user_forced_set_point_change) { user_forced_set_point_change = false; set_point_reached = true; } last_temp = temperature; thd_log_debug("update_set_point %u,%d,%u\n", last_temp, current_angle, set_point); } void cthd_model::store_set_point() { std::stringstream filename; filename << TDRUNDIR << "/" << "thermal_set_point." << zone_type << "." << "conf"; std::ofstream fout(filename.str().c_str()); if (fout.good()) { fout << set_point; } thd_log_info("storing set point %d\n", set_point); fout.close(); } int cthd_model::read_set_point() { std::stringstream filename; unsigned int _set_point = 0; filename << TDRUNDIR << "/" << "thermal_set_point." << zone_type << "." << "conf"; std::ifstream ifs(filename.str().c_str(), std::ifstream::in); if (ifs.good()) { ifs >> _set_point; } ifs.close(); thd_log_info("Read set point %u\n", _set_point); return _set_point; } void cthd_model::set_max_temperature(int temp) { int _set_point; int user_defined_max; max_temp = temp - safety_margin; user_defined_max = read_user_set_max_temp(); if (user_defined_max > 0) max_temp = user_defined_max; _set_point = read_set_point(); if (_set_point > 0 && _set_point < max_temp) { set_point = _set_point; } else { set_point = max_temp; } hot_zone = max_temp - ((max_temp * hot_zone_percent) / 100); } bool cthd_model::update_user_set_max_temp() { std::stringstream filename; bool present = false; unsigned int temp; filename << TDRUNDIR << "/" << "thd_user_set_max." << zone_type << "." << "conf"; std::ifstream ifs(filename.str().c_str(), std::ifstream::in); if (ifs.good()) { ifs >> temp; if (temp > 1000) { max_temp = temp; set_point = max_temp; hot_zone = max_temp - ((max_temp * hot_zone_percent) / 100); store_set_point(); present = true; user_forced_set_point_change = true; thd_log_info("User forced maximum temperature is %d\n", max_temp); } } ifs.close(); return present; } int cthd_model::read_user_set_max_temp() { std::stringstream filename; unsigned int user_max = 0; filename << TDRUNDIR << "/" << "thd_user_set_max." << zone_type << "." << "conf"; std::ifstream ifs(filename.str().c_str(), std::ifstream::in); if (ifs.good()) { ifs >> user_max; thd_log_info("User defined max temperature %u\n", user_max); } ifs.close(); return user_max; } thermald-1.5/src/thd_dbus_interface.cpp0000664000175000017500000004157412661205366016754 0ustar kingking/* * thd_dbus_interface.cpp: Thermal Daemon dbus interface * * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thermald.h" #include "thd_preference.h" #include "thd_engine.h" #include "thd_engine_default.h" #include "thd_sensor.h" #include "thd_zone.h" #include "thd_trip_point.h" typedef struct { GObject parent; } PrefObject; typedef struct { GObjectClass parent; } PrefObjectClass; GType pref_object_get_type(void); #define MAX_DBUS_REPLY_STR_LEN 100 #define PREF_TYPE_OBJECT (pref_object_get_type()) G_DEFINE_TYPE(PrefObject, pref_object, G_TYPE_OBJECT) gboolean thd_dbus_interface_terminate(PrefObject *obj, GError **error); gboolean thd_dbus_interface_reinit(PrefObject *obj, GError **error); gboolean thd_dbus_interface_set_current_preference(PrefObject *obj, gchar *pref, GError **error); gboolean thd_dbus_interface_get_current_preference(PrefObject *obj, gchar **pref_out, GError **error); gboolean thd_dbus_interface_set_user_max_temperature(PrefObject *obj, gchar *zone_name, unsigned temperature, GError **error); gboolean thd_dbus_interface_set_user_passive_temperature(PrefObject *obj, gchar *zone_name, unsigned int temperature, GError **error); gboolean thd_dbus_interface_add_sensor(PrefObject *obj, gchar *sensor, gchar *path, GError **error); gboolean thd_dbus_interface_get_sensor_information(PrefObject *obj, gint index, gchar **sensor_out, gchar **path, gint *temp, GError **error); gboolean thd_dbus_interface_add_zone_passive(PrefObject *obj, gchar *zone_name, gint trip_temp, gchar *sensor_name, gchar *cdev_name, GError **error); gboolean thd_dbus_interface_set_zone_status(PrefObject *obj, gchar *zone_name, int status, GError **error); gboolean thd_dbus_interface_get_zone_status(PrefObject *obj, gchar *zone_name, int *status, GError **error); gboolean thd_dbus_interface_delete_zone(PrefObject *obj, gchar *zone_name, GError **error); gboolean thd_dbus_interface_add_virtual_sensor(PrefObject *obj, gchar *name, gchar *dep_sensor, double slope, double intercept, GError **error); gboolean thd_dbus_interface_add_cooling_device(PrefObject *obj, gchar *cdev_name, gchar *path, gint min_state, gint max_state, gint step, GError **error); gboolean thd_dbus_interface_update_cooling_device(PrefObject *obj, gchar *cdev_name, gchar *path, gint min_state, gint max_state, gint step, GError **error); gboolean thd_dbus_interface_get_sensor_count(PrefObject *obj, int *status, GError **error); gboolean thd_dbus_interface_get_sensor_temperature(PrefObject *obj, int index, unsigned int *temperature, GError **error); gboolean thd_dbus_interface_get_zone_count(PrefObject *obj, int *status, GError **error); gboolean thd_dbus_interface_get_zone_information(PrefObject *obj, gint index, gchar **zone_out, gint *sensor_count, gint *trip_count, GError **error); gboolean thd_dbus_interface_get_zone_sensor_at_index(PrefObject *obj, gint zone_index, gint sensor_index, gchar **sensor_out, GError **error); gboolean thd_dbus_interface_get_zone_trip_at_index(PrefObject *obj, gint zone_index, gint trip_index, int *temp, int *trip_type, int *sensor_id, int *cdev_size, GArray **cdev_ids, GError **error); gboolean thd_dbus_interface_get_cdev_count(PrefObject *obj, int *status, GError **error); gboolean thd_dbus_interface_get_cdev_information(PrefObject *obj, gint index, gchar **cdev_out, gint *min_state, gint *max_state, gint *curr_state, GError **error); // To be implemented gboolean thd_dbus_interface_add_trip_point(PrefObject *obj, gchar *name, GError **error) { return FALSE; } gboolean thd_dbus_interface_delete_trip_point(PrefObject *obj, gchar *name, GError **error) { return FALSE; } gboolean thd_dbus_interface_disable_cooling_device(PrefObject *obj, gchar *name, GError **error) { return FALSE; } // This is a generated file, which expects the above prototypes #include "thd_dbus_interface.h" // DBUS Related functions // Dbus object initialization static void pref_object_init(PrefObject *obj) { g_assert(obj != NULL); } // Dbus object class initialization static void pref_object_class_init(PrefObjectClass *_class) { g_assert(_class != NULL); dbus_g_object_type_install_info(PREF_TYPE_OBJECT, &dbus_glib_thd_dbus_interface_object_info); } // Callback function called to inform a sent value via dbus gboolean thd_dbus_interface_set_current_preference(PrefObject *obj, gchar *pref, GError **error) { int ret; thd_log_debug("thd_dbus_interface_set_current_preference %s\n", (char*) pref); g_assert(obj != NULL); cthd_preference thd_pref; ret = thd_pref.set_preference((char*) pref); thd_engine->send_message(PREF_CHANGED, 0, NULL); return ret; } // Callback function called to get value via dbus gboolean thd_dbus_interface_get_current_preference(PrefObject *obj, gchar **pref_out, GError **error) { thd_log_debug("thd_dbus_interface_get_current_preference\n"); g_assert(obj != NULL); gchar *value_out; static char *pref_str; pref_str = g_new(char, MAX_DBUS_REPLY_STR_LEN); if (!pref_str) return FALSE; cthd_preference thd_pref; value_out = (gchar*) thd_pref.get_preference_cstr(); if (!value_out) { g_free(pref_str); return FALSE; } strncpy(pref_str, value_out, MAX_DBUS_REPLY_STR_LEN); free(value_out); thd_log_debug("thd_dbus_interface_get_current_preference out :%s\n", pref_str); *pref_out = pref_str; return TRUE; } void (*thd_dbus_exit_callback)(int); gboolean thd_dbus_interface_terminate(PrefObject *obj, GError **error) { thd_engine->thd_engine_terminate(); if (thd_dbus_exit_callback) thd_dbus_exit_callback(0); return TRUE; } gboolean thd_dbus_interface_reinit(PrefObject *obj, GError **error) { bool exclusive_control = false; thd_engine->thd_engine_terminate(); sleep(1); delete thd_engine; sleep(2); if (thd_engine->get_control_mode() == EXCLUSIVE) exclusive_control = true; std::string config_file = thd_engine->get_config_file(); const char *conf_file = NULL; if (!config_file.empty()) conf_file = config_file.c_str(); if (thd_engine_create_default_engine(true, exclusive_control, conf_file) != THD_SUCCESS) { return FALSE; } return TRUE; } gboolean thd_dbus_interface_set_user_max_temperature(PrefObject *obj, gchar *zone_name, unsigned int temperature, GError **error) { thd_log_debug("thd_dbus_interface_set_user_set_point %s:%d\n", zone_name, temperature); g_assert(obj != NULL); int ret = thd_engine->user_set_max_temp(zone_name, temperature); if (ret == THD_SUCCESS) thd_engine->send_message(PREF_CHANGED, 0, NULL); else return FALSE; return TRUE; } gboolean thd_dbus_interface_set_user_passive_temperature(PrefObject *obj, gchar *zone_name, unsigned int temperature, GError **error) { thd_log_debug("thd_dbus_interface_set_user_passive_temperature %s:%u\n", zone_name, temperature); g_assert(obj != NULL); int ret = thd_engine->user_set_psv_temp(zone_name, temperature); if (ret == THD_SUCCESS) thd_engine->send_message(PREF_CHANGED, 0, NULL); else return FALSE; return TRUE; } gboolean thd_dbus_interface_add_sensor(PrefObject *obj, gchar *sensor, gchar *path, GError **error) { int ret; g_assert(obj != NULL); thd_log_debug("thd_dbus_interface_add_sensor %s:%s\n", (char*) sensor, (char *) path); ret = thd_engine->user_add_sensor(sensor, path); if (ret == THD_SUCCESS) return TRUE; else return FALSE; } // Adjust parameters for the following gboolean thd_dbus_interface_add_virtual_sensor(PrefObject *obj, gchar *name, gchar *dep_sensor, double slope, double intercept, GError **error) { int ret; g_assert(obj != NULL); thd_log_debug("thd_dbus_interface_add_sensor %s:%s\n", (char*) name, (char *) dep_sensor); ret = thd_engine->user_add_virtual_sensor(name, dep_sensor, slope, intercept); if (ret == THD_SUCCESS) return TRUE; else return FALSE; } gboolean thd_dbus_interface_get_sensor_information(PrefObject *obj, gint index, gchar **sensor_out, gchar **path, gint *temp, GError **error) { char *sensor_str; char *path_str; thd_log_debug("thd_dbus_interface_get_sensor_information %d\n", index); cthd_sensor *sensor = thd_engine->user_get_sensor(index); if (!sensor) return FALSE; sensor_str = g_new(char, MAX_DBUS_REPLY_STR_LEN + 1); if (!sensor_str) return FALSE; path_str = g_new(char, MAX_DBUS_REPLY_STR_LEN + 1); if (!path_str) { g_free(sensor_str); return FALSE; } strncpy(sensor_str, sensor->get_sensor_type().c_str(), MAX_DBUS_REPLY_STR_LEN); sensor_str[MAX_DBUS_REPLY_STR_LEN] = '\0'; strncpy(path_str, sensor->get_sensor_path().c_str(), MAX_DBUS_REPLY_STR_LEN); path_str[MAX_DBUS_REPLY_STR_LEN] = '\0'; *temp = (gint) sensor->read_temperature(); *sensor_out = sensor_str; *path = path_str; return TRUE; } gboolean thd_dbus_interface_get_sensor_count(PrefObject *obj, int *count, GError **error) { *count = thd_engine->get_sensor_count(); return TRUE; } gboolean thd_dbus_interface_get_zone_count(PrefObject *obj, int *count, GError **error) { *count = thd_engine->get_zone_count(); return TRUE; } gboolean thd_dbus_interface_get_zone_information(PrefObject *obj, gint index, gchar **zone_out, gint *sensor_count, gint *trip_count, GError **error) { char *zone_str; thd_log_debug("thd_dbus_interface_get_zone_information %d\n", index); cthd_zone *zone = thd_engine->user_get_zone(index); if (!zone) return FALSE; zone_str = g_new(char, MAX_DBUS_REPLY_STR_LEN + 1); if (!zone_str) return FALSE; strncpy(zone_str, zone->get_zone_type().c_str(), MAX_DBUS_REPLY_STR_LEN); zone_str[MAX_DBUS_REPLY_STR_LEN] = '\0'; *zone_out = zone_str; *sensor_count = zone->get_sensor_count(); *trip_count = zone->get_trip_count(); return TRUE; } gboolean thd_dbus_interface_get_zone_sensor_at_index(PrefObject *obj, gint zone_index, gint sensor_index, gchar **sensor_out, GError **error) { char *sensor_str; thd_log_debug("thd_dbus_interface_get_zone_sensor_at_index %d\n", zone_index); cthd_zone *zone = thd_engine->user_get_zone(zone_index); if (!zone) return FALSE; cthd_sensor *sensor = zone->get_sensor_at_index(sensor_index); if (!sensor) return FALSE; sensor_str = g_new(char, MAX_DBUS_REPLY_STR_LEN + 1); if (!sensor_str) return FALSE; strncpy(sensor_str, sensor->get_sensor_type().c_str(), MAX_DBUS_REPLY_STR_LEN); sensor_str[MAX_DBUS_REPLY_STR_LEN] = '\0'; *sensor_out = sensor_str; return TRUE; } gboolean thd_dbus_interface_get_zone_trip_at_index(PrefObject *obj, gint zone_index, gint trip_index, int *temp, int *trip_type, int *sensor_id, int *cdev_size, GArray **cdev_ids, GError **error) { thd_log_debug("thd_dbus_interface_get_zone_sensor_at_index %d\n", zone_index); cthd_zone *zone = thd_engine->user_get_zone(zone_index); if (!zone) return FALSE; cthd_trip_point *trip = zone->get_trip_at_index(trip_index); if (!trip) return FALSE; *temp = trip->get_trip_temp(); *trip_type = trip->get_trip_type(); *sensor_id = trip->get_sensor_id(); *cdev_size = trip->get_cdev_count(); GArray *garray; garray = g_array_new(FALSE, FALSE, sizeof(gint)); for (int i = 0; i < *cdev_size; i++) { trip_pt_cdev_t cdev_trip; int index; cdev_trip = trip->get_cdev_at_index(i); index = cdev_trip.cdev->thd_cdev_get_index(); g_array_prepend_val(garray, index); } *cdev_ids = garray; return TRUE; } gboolean thd_dbus_interface_get_cdev_count(PrefObject *obj, int *count, GError **error) { *count = thd_engine->get_cdev_count(); return TRUE; } gboolean thd_dbus_interface_get_cdev_information(PrefObject *obj, gint index, gchar **cdev_out, gint *min_state, gint *max_state, gint *curr_state, GError **error) { char *cdev_str; thd_log_debug("thd_dbus_interface_get_cdev_information %d\n", index); cthd_cdev *cdev = thd_engine->user_get_cdev(index); if (!cdev) return FALSE; cdev_str = g_new(char, MAX_DBUS_REPLY_STR_LEN + 1); if (!cdev_str) return FALSE; strncpy(cdev_str, cdev->get_cdev_type().c_str(), MAX_DBUS_REPLY_STR_LEN); cdev_str[MAX_DBUS_REPLY_STR_LEN] = '\0'; *cdev_out = cdev_str; *min_state = cdev->get_min_state(); *max_state = cdev->get_max_state(); *curr_state = cdev->get_curr_state(); return TRUE; } gboolean thd_dbus_interface_add_zone_passive(PrefObject *obj, gchar *zone_name, gint trip_temp, gchar *sensor_name, gchar *cdev_name, GError **error) { int ret; g_assert(obj != NULL); thd_log_debug("thd_dbus_interface_add_zone_passive %s\n", (char*) zone_name); ret = thd_engine->user_add_zone(zone_name, trip_temp, sensor_name, cdev_name); if (ret == THD_SUCCESS) return TRUE; else return FALSE; } gboolean thd_dbus_interface_set_zone_status(PrefObject *obj, gchar *zone_name, int status, GError **error) { int ret; g_assert(obj != NULL); thd_log_debug("thd_dbus_interface_set_zone_status %s\n", (char*) zone_name); ret = thd_engine->user_set_zone_status(zone_name, status); if (ret == THD_SUCCESS) return TRUE; else return FALSE; } gboolean thd_dbus_interface_get_zone_status(PrefObject *obj, gchar *zone_name, int *status, GError **error) { int ret; g_assert(obj != NULL); thd_log_debug("thd_dbus_interface_set_zone_status %s\n", (char*) zone_name); ret = thd_engine->user_get_zone_status(zone_name, status); if (ret == THD_SUCCESS) return TRUE; else return FALSE; } gboolean thd_dbus_interface_delete_zone(PrefObject *obj, gchar *zone_name, GError **error) { int ret; g_assert(obj != NULL); thd_log_debug("thd_dbus_interface_delete_zone %s\n", (char*) zone_name); ret = thd_engine->user_delete_zone(zone_name); if (ret == THD_SUCCESS) return TRUE; else return FALSE; } gboolean thd_dbus_interface_add_cooling_device(PrefObject *obj, gchar *cdev_name, gchar *path, gint min_state, gint max_state, gint step, GError **error) { int ret; g_assert(obj != NULL); thd_log_debug("thd_dbus_interface_add_cooling_device %s\n", (char*) cdev_name); // Using a device in /etc is a security issue if ((strlen(path) >= strlen("/etc")) && !strncmp(path, "/etc", strlen("/etc"))) return FALSE; ret = thd_engine->user_add_cdev(cdev_name, path, min_state, max_state, step); if (ret == THD_SUCCESS) return TRUE; else return FALSE; } gboolean thd_dbus_interface_update_cooling_device(PrefObject *obj, gchar *cdev_name, gchar *path, gint min_state, gint max_state, gint step, GError **error) { g_assert(obj != NULL); // Using a device in /etc is a security issue if ((strlen(path) >= strlen("/etc")) && !strncmp(path, "/etc", strlen("/etc"))) return FALSE; return thd_dbus_interface_add_cooling_device(obj, cdev_name, path, min_state, max_state, step, error); } gboolean thd_dbus_interface_get_sensor_temperature(PrefObject *obj, int index, unsigned int *temperature, GError **error) { int ret; ret = thd_engine->get_sensor_temperature(index, temperature); if (ret == THD_SUCCESS) return TRUE; else return FALSE; } // Setup dbus server int thd_dbus_server_init(void (*exit_handler)(int)) { DBusGConnection *bus; DBusGProxy *bus_proxy; GError *error = NULL; guint result; PrefObject *value_obj; thd_dbus_exit_callback = exit_handler; bus = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error); if (error != NULL) { thd_log_error("Couldn't connect to session bus: %s:\n", error->message); return THD_FATAL_ERROR; } // Get a bus proxy instance bus_proxy = dbus_g_proxy_new_for_name(bus, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS); if (bus_proxy == NULL) { thd_log_error("Failed to get a proxy for D-Bus:\n"); return THD_FATAL_ERROR; } thd_log_debug("Registering the well-known name (%s)\n", THD_SERVICE_NAME); // register the well-known name if (!dbus_g_proxy_call(bus_proxy, "RequestName", &error, G_TYPE_STRING, THD_SERVICE_NAME, G_TYPE_UINT, 0, G_TYPE_INVALID, G_TYPE_UINT, &result, G_TYPE_INVALID)) { thd_log_error("D-Bus.RequestName RPC failed: %s\n", error->message); return THD_FATAL_ERROR; } thd_log_debug("RequestName returned %d.\n", result); if (result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { thd_log_error("Failed to get the primary well-known name:\n"); return THD_FATAL_ERROR; } value_obj = (PrefObject*) g_object_new(PREF_TYPE_OBJECT, NULL); if (value_obj == NULL) { thd_log_error("Failed to create one Value instance:\n"); return THD_FATAL_ERROR; } thd_log_debug("Registering it on the D-Bus.\n"); dbus_g_connection_register_g_object(bus, THD_SERVICE_OBJECT_PATH, G_OBJECT(value_obj)); return THD_SUCCESS; } thermald-1.5/src/thd_trip_point.cpp0000664000175000017500000001464212661205366016162 0ustar kingking/* * thd_trip_point.cpp: thermal zone class implentation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include #include #include "thd_trip_point.h" #include "thd_engine.h" cthd_trip_point::cthd_trip_point(int _index, trip_point_type_t _type, unsigned int _temp, unsigned int _hyst, int _zone_id, int _sensor_id, trip_control_type_t _control_type) : index(_index), type(_type), temp(_temp), hyst(_hyst), control_type( _control_type), zone_id(_zone_id), sensor_id(_sensor_id), trip_on( false), poll_on(false) { thd_log_debug("Add trip pt %d:%d:0x%x:%d:%d\n", type, zone_id, sensor_id, temp, hyst); } bool cthd_trip_point::thd_trip_point_check(int id, unsigned int read_temp, int pref, bool *reset) { int on = -1; int off = -1; bool apply = false; *reset = false; if (sensor_id != DEFAULT_SENSOR_ID && sensor_id != id) return false; if (read_temp == 0) { thd_log_debug("TEMP == 0 pref: %d\n", pref); } if (type == CRITICAL) { if (read_temp >= temp) { thd_log_warn("critical temp reached \n"); sync(); reboot(RB_POWER_OFF); } } if (type == POLLING && sensor_id != DEFAULT_SENSOR_ID) { cthd_sensor *sensor = thd_engine->get_sensor(sensor_id); if (sensor && sensor->check_async_capable()) { if (!poll_on && read_temp >= temp) { thd_log_debug("polling trip reached, on \n"); sensor->sensor_poll_trip(true); poll_on = true; sensor->set_threshold(0, temp); } else if (poll_on && read_temp < temp) { thd_log_debug("polling trip reached, off \n"); sensor->sensor_poll_trip(false); thd_log_info("Dropped below poll threshold \n"); *reset = true; poll_on = false; sensor->set_threshold(0, temp); } } return true; } thd_log_debug("pref %d type %d temp %d trip %d \n", pref, type, read_temp, temp); switch (pref) { case PREF_DISABLED: return false; break; case PREF_PERFORMANCE: if (type == ACTIVE || type == MAX) { apply = true; thd_log_debug("Active Trip point applicable \n"); } break; case PREF_ENERGY_CONSERVE: if (type == PASSIVE || type == MAX) { apply = true; thd_log_debug("Passive Trip point applicable \n"); } break; default: break; } if (apply) { if (read_temp >= temp) { thd_log_debug("Trip point applicable > %d:%d \n", index, temp); on = 1; trip_on = true; } else if ((trip_on && (read_temp + hyst) < temp) || (!trip_on && read_temp < temp)) { thd_log_debug("Trip point applicable < %d:%d \n", index, temp); off = 1; trip_on = false; } } else return false; if (on != 1 && off != 1) return true; int i, ret; thd_log_debug("cdev size for this trippoint %lu\n", (unsigned long) cdevs.size()); if (on > 0) { for (unsigned i = 0; i < cdevs.size(); ++i) { cthd_cdev *cdev = cdevs[i].cdev; if (cdevs[i].sampling_priod) { time_t tm; time(&tm); if ((tm - cdevs[i].last_op_time) < cdevs[i].sampling_priod) { thd_log_info("Too early to act index %d tm %ld\n", cdev->thd_cdev_get_index(), tm - cdevs[i].last_op_time); break; } cdevs[i].last_op_time = tm; } thd_log_debug("cdev at index %d:%s\n", cdev->thd_cdev_get_index(), cdev->get_cdev_type().c_str()); /* * When the cdev is already in max state, we skip this cdev. * Also when the target state if any for the current trip is greater * or equal than the current state of the cdev, then also skip. */ if (cdev->in_max_state() || (cdevs[i].target_state != TRIP_PT_INVALID_TARGET_STATE && cdev->cmp_current_state(cdevs[i].target_state) <= 0)) { thd_log_debug("Need to switch to next cdev \n"); // No scope of control with this cdev continue; } ret = cdev->thd_cdev_set_state(temp, temp, read_temp, 1, zone_id, index, cdevs[i].target_state); if (control_type == SEQUENTIAL && ret == THD_SUCCESS) { // Only one cdev activation break; } } } if (off > 0) { for (i = cdevs.size() - 1; i >= 0; --i) { cthd_cdev *cdev = cdevs[i].cdev; thd_log_debug("cdev at index %d:%s\n", cdev->thd_cdev_get_index(), cdev->get_cdev_type().c_str()); if (cdev->in_min_state()) { thd_log_debug("Need to switch to next cdev \n"); // No scope of control with this cdev continue; } cdev->thd_cdev_set_state(temp, temp, read_temp, 0, zone_id, index, TRIP_PT_INVALID_TARGET_STATE); if (control_type == SEQUENTIAL) { // Only one cdev activation break; } } } return true; } void cthd_trip_point::thd_trip_point_add_cdev(cthd_cdev &cdev, int influence, int sampling_period, int target_state) { trip_pt_cdev_t thd_cdev; thd_cdev.cdev = &cdev; thd_cdev.influence = influence; thd_cdev.sampling_priod = sampling_period; thd_cdev.last_op_time = 0; thd_cdev.target_state = target_state; trip_cdev_add(thd_cdev); } int cthd_trip_point::thd_trip_point_add_cdev_index(int _index, int influence) { cthd_cdev *cdev = thd_engine->thd_get_cdev_at_index(_index); if (cdev) { trip_pt_cdev_t thd_cdev; thd_cdev.cdev = cdev; thd_cdev.influence = influence; thd_cdev.sampling_priod = 0; thd_cdev.last_op_time = 0; trip_cdev_add(thd_cdev); return THD_SUCCESS; } else { thd_log_warn("thd_trip_point_add_cdev_index not present %d\n", _index); return THD_ERROR; } } void cthd_trip_point::thd_trip_cdev_state_reset() { thd_log_info("thd_trip_cdev_state_reset \n"); for (int i = cdevs.size() - 1; i >= 0; --i) { cthd_cdev *cdev = cdevs[i].cdev; thd_log_info("thd_trip_cdev_state_reset index %d:%s\n", cdev->thd_cdev_get_index(), cdev->get_cdev_type().c_str()); if (cdev->in_min_state()) { thd_log_debug("Need to switch to next cdev \n"); // No scope of control with this cdev continue; } cdev->thd_cdev_set_min_state(zone_id); } } thermald-1.5/src/thd_zone_generic.cpp0000664000175000017500000000650412661205366016440 0ustar kingking/* * thd_zone_generic.cpp: zone implementation for xml conf * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_zone_generic.h" #include "thd_engine.h" cthd_zone_generic::cthd_zone_generic(int index, int _config_index, std::string type) : cthd_zone(index, ""), trip_point_cnt(0), config_index(_config_index), zone( NULL) { type_str = type; } int cthd_zone_generic::read_trip_points() { thermal_zone_t *zone_config = thd_engine->parser.get_zone_dev_index( config_index); int trip_point_cnt = 0; if (!zone_config) return THD_ERROR; for (unsigned int i = 0; i < zone_config->trip_pts.size(); ++i) { trip_point_t &trip_pt_config = zone_config->trip_pts[i]; if (!trip_pt_config.temperature) continue; cthd_sensor *sensor = thd_engine->search_sensor( trip_pt_config.sensor_type); if (!sensor) { thd_log_error("XML zone: invalid sensor type \n"); continue; } sensor_list.push_back(sensor); cthd_trip_point trip_pt(trip_point_cnt, trip_pt_config.trip_pt_type, trip_pt_config.temperature, trip_pt_config.hyst, index, sensor->get_index(), trip_pt_config.control_type); if (trip_pt_config.trip_pt_type == MAX) { thd_model.set_max_temperature(trip_pt_config.temperature); if (thd_model.get_set_point()) { trip_pt.update_trip_temp(thd_model.get_set_point()); } } // bind cdev for (unsigned int j = 0; j < trip_pt_config.cdev_trips.size(); ++j) { cthd_cdev *cdev = thd_engine->search_cdev( trip_pt_config.cdev_trips[j].type); if (cdev) { trip_pt.thd_trip_point_add_cdev(*cdev, trip_pt_config.cdev_trips[j].influence, trip_pt_config.cdev_trips[j].sampling_period, trip_pt_config.cdev_trips[j].target_state); zone_cdev_set_binded(); } } trip_points.push_back(trip_pt); ++trip_point_cnt; } if (!trip_points.size()) { thd_log_info( " cthd_zone_generic::read_trip_points fail: No valid trips\n"); return THD_ERROR; } return 0; } int cthd_zone_generic::read_cdev_trip_points() { return 0; } int cthd_zone_generic::zone_bind_sensors() { cthd_sensor *sensor; thermal_zone_t *zone_config = thd_engine->parser.get_zone_dev_index( config_index); if (!zone_config) return THD_ERROR; sensor = NULL; for (unsigned int i = 0; i < zone_config->trip_pts.size(); ++i) { trip_point_t &trip_pt_config = zone_config->trip_pts[i]; sensor = thd_engine->search_sensor(trip_pt_config.sensor_type); if (!sensor) { thd_log_error("XML zone: invalid sensor type %s\n", trip_pt_config.sensor_type.c_str()); continue; } bind_sensor(sensor); } if (!sensor) return THD_ERROR; return THD_SUCCESS; } thermald-1.5/src/thd_cdev.cpp0000664000175000017500000002175012661205366014712 0ustar kingking/* * thd_cdev.cpp: thermal cooling class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ /* * This is parent class for all cooling devices. Most of the functions * are implemented in interface file except set state. * set_state uses the interface to get the current state, max state and * set the device state. * When state = 0, it causes reduction in the cooling device state * when state = 1, it increments cooling device state * When increments, it goes step by step, unless it finds that the temperature * can't be controlled by previous state with in def_poll_interval, otherwise * it will increase exponentially. * Reduction is always uses step by step to reduce ping pong affect. * */ #include "thd_cdev.h" #include "thd_engine.h" int cthd_cdev::thd_cdev_exponential_controller(int set_point, int target_temp, int temperature, int state, int zone_id) { curr_state = get_curr_state(); if ((min_state < max_state && curr_state < min_state) || (min_state > max_state && curr_state > min_state)) curr_state = min_state; max_state = get_max_state(); thd_log_debug("thd_cdev_set_%d:curr state %d max state %d\n", index, curr_state, max_state); if (state) { if ((min_state < max_state && curr_state < max_state) || (min_state > max_state && curr_state > max_state)) { int state = curr_state + inc_dec_val; if (trend_increase) { if (curr_pow == 0) base_pow_state = curr_state; ++curr_pow; state = base_pow_state + int_2_pow(curr_pow) * inc_dec_val; thd_log_info( "cdev index:%d consecutive call, increment exponentially state %d\n", index, state); if ((min_state < max_state && state >= max_state) || (min_state > max_state && state <= max_state)) { state = max_state; curr_pow = 0; curr_state = max_state; } } else { curr_pow = 0; } trend_increase = true; if ((min_state < max_state && state > max_state) || (min_state > max_state && state < max_state)) state = max_state; thd_log_debug("op->device:%s %d\n", type_str.c_str(), state); set_curr_state(state, zone_id); } } else { curr_pow = 0; trend_increase = false; if (((min_state < max_state && curr_state > min_state) || (min_state > max_state && curr_state < min_state)) && auto_down_adjust == false) { int state = curr_state - inc_dec_val; if ((min_state < max_state && state < min_state) || (min_state > max_state && state > min_state)) state = min_state; thd_log_debug("op->device:%s %d\n", type_str.c_str(), state); set_curr_state(state, zone_id); } else { thd_log_debug("op->device: force min %s %d\n", type_str.c_str(), min_state); set_curr_state(min_state, zone_id); } } thd_log_info( "Set : threshold:%d, temperature:%d, cdev:%d(%s), curr_state:%d, max_state:%d\n", set_point, temperature, index, type_str.c_str(), get_curr_state(), max_state); thd_log_debug("<>thd_cdev_set_state index:%d state:%d :%d:%d:%d\n", index, state, zone_id, trip_id, target_value); if (last_state == state && (tm - last_action_time) <= debounce_interval) { thd_log_debug( "Ignore: delay < debounce interval : %d, %d, %d, %d, %d\n", set_point, temperature, index, get_curr_state(), max_state); return THD_SUCCESS; } last_state = state; if (state) { zone_mask |= (1 << zone_id); trip_mask |= (1 << trip_id); if (target_value != TRIP_PT_INVALID_TARGET_STATE) { zone_trip_limits_t limit; bool found = false; for (unsigned int i = 0; i < zone_trip_limits.size(); ++i) { if (zone_trip_limits[i].zone == zone_id && zone_trip_limits[i].trip == trip_id) { found = true; break; } } if (!found) { limit.zone = zone_id; limit.trip = trip_id; limit.target_value = target_value; thd_log_debug("Added zone %d trip %d clamp %d\n", limit.zone, limit.trip, limit.target_value); zone_trip_limits.push_back(limit); std::sort(zone_trip_limits.begin(), zone_trip_limits.end(), sort_clamp_values); } set_curr_state_raw(target_value, zone_id); curr_state = target_value; last_action_time = tm; thd_log_info( "Set : threshold:%d, temperature:%d, cdev:%d(%s), curr_state:%d, max_state:%d\n", set_point, temperature, index, type_str.c_str(), get_curr_state(), max_state); return THD_SUCCESS; } } else { if (zone_mask & (1 << zone_id)) { if (trip_mask & (1 << trip_id)) { trip_mask &= ~(1 << trip_id); zone_mask &= ~(1 << zone_id); } } if (zone_trip_limits.size() > 0) { int length = zone_trip_limits.size(); int i; // Just remove the current zone requesting to turn off for (i = 0; i < length; ++i) { if (zone_trip_limits[i].zone == zone_id && zone_trip_limits[i].trip == trip_id) { zone_trip_limits.erase(zone_trip_limits.begin() + i); thd_log_debug("Erased [%d: %d\n", zone_id, trip_id); break; } } zone_trip_limits_t limit; if (zone_trip_limits.size() == 0) { limit.target_value = get_min_state(); limit.zone = zone_id; limit.trip = trip_id; } else { limit = zone_trip_limits[zone_trip_limits.size() - 1]; } if (cmp_current_state(limit.target_value) < 0) { thd_log_info( "new active zone; next in line %d trip %d clamp %d\n", limit.zone, limit.trip, limit.target_value); set_curr_state_raw(limit.target_value, zone_id); thd_log_info( "Set : threshold:%d, temperature:%d, cdev:%d(%s), curr_state:%d, max_state:%d\n", set_point, temperature, index, type_str.c_str(), get_curr_state(), max_state); } return THD_SUCCESS; } else if (zone_mask != 0 || trip_mask != 0) { thd_log_debug( "skip to reduce current state as this is controlled by two zone or trip actions and one is still on %lx:%lx\n", zone_mask, trip_mask); return THD_SUCCESS; } } last_action_time = tm; curr_state = get_curr_state(); if (curr_state == get_min_state()) { control_begin(); } if (pid_enable) { pid_ctrl.set_target_temp(target_temp); ret = pid_ctrl.pid_output(temperature); ret += get_curr_state(); if (ret > get_max_state()) ret = get_max_state(); if (ret < get_min_state()) ret = get_min_state(); set_curr_state_raw(ret, zone_id); thd_log_debug("Set : %d, %d, %d, %d, %d\n", set_point, temperature, index, get_curr_state(), max_state); ret = THD_SUCCESS; } else { ret = thd_cdev_exponential_controller(set_point, target_temp, temperature, state, zone_id); } if (curr_state == get_max_state()) { control_end(); } return ret; } ; int cthd_cdev::thd_cdev_set_min_state(int zone_id) { zone_mask &= ~(1 << zone_id); if (zone_mask != 0) { thd_log_debug( "skip to reduce current state as this is controlled by two zone actions and one is still on %x\n", (unsigned int) zone_mask); return THD_SUCCESS; } trend_increase = false; set_curr_state(min_state, zone_id); return THD_SUCCESS; } thermald-1.5/src/thd_parse.cpp0000664000175000017500000006473012661205366015110 0ustar kingking/* * thd_engine.cpp: thermal engine class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ /* Parser to parse thermal configuration file. This uses libxml2 API. * */ #include "thd_parse.h" #include #include #include "thd_sys_fs.h" #include "thd_trt_art_reader.h" #define DEBUG_PARSER_PRINT(x,...) void cthd_parse::string_trim(std::string &str) { std::string chars = "\n \t\r"; for (unsigned int i = 0; i < chars.length(); ++i) { str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end()); } } char *cthd_parse::char_trim(char *str) { int i; if (!str) return NULL; if (str[0] == '\0') return str; while (isspace(*str)) str++; for (i = strlen(str) - 1; (isspace(str[i])); i--) ; str[i + 1] = '\0'; return str; } cthd_parse::cthd_parse() : matched_thermal_info_index(-1), doc(NULL), root_element(NULL) { std::string name_run = TDRUNDIR; filename = name_run + "/" + "thermal-conf.xml"; filename_auto = name_run + "/" + "thermal-conf.xml.auto"; } int cthd_parse::parser_init(std::string config_file) { cthd_acpi_rel rel; const char *xml_config_file; int ret; if (config_file.empty()) { ret = rel.generate_conf(filename_auto); if (!ret) { thd_log_warn("Using generated %s\n", filename_auto.c_str()); xml_config_file = filename_auto.c_str(); } else { xml_config_file = filename.c_str(); } } else { xml_config_file = config_file.c_str(); } doc = xmlReadFile(xml_config_file, NULL, 0); if (doc == NULL) { thd_log_warn("error: could not parse file %s\n", xml_config_file); return THD_ERROR; } root_element = xmlDocGetRootElement(doc); if (root_element == NULL) { thd_log_warn("error: could not get root element \n"); return THD_ERROR; } return THD_SUCCESS; } int cthd_parse::parse_new_trip_cdev(xmlNode * a_node, xmlDoc *doc, trip_cdev_t *trip_cdev) { xmlNode *cur_node = NULL; char *tmp_value; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (char *) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char*) cur_node->name, "type")) { trip_cdev->type.assign((const char*) tmp_value); string_trim(trip_cdev->type); } else if (!strcasecmp((const char*) cur_node->name, "influence")) { trip_cdev->influence = atoi(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "SamplingPeriod")) { trip_cdev->sampling_period = atoi(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "TargetState")) { trip_cdev->target_state = atoi(tmp_value); } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_new_trip_point(xmlNode * a_node, xmlDoc *doc, trip_point_t *trip_pt) { xmlNode *cur_node = NULL; char *tmp_value; trip_cdev_t trip_cdev; trip_pt->temperature = 0; trip_pt->trip_pt_type = ACTIVE; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (char *) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char*) cur_node->name, "Temperature")) { trip_pt->temperature = atoi(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "Hyst")) { trip_pt->hyst = atoi(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "CoolingDevice")) { trip_cdev.influence = 0; trip_cdev.sampling_period = 0; trip_cdev.target_state = TRIP_PT_INVALID_TARGET_STATE; trip_cdev.type.clear(); parse_new_trip_cdev(cur_node->children, doc, &trip_cdev); trip_pt->cdev_trips.push_back(trip_cdev); } else if (!strcasecmp((const char*) cur_node->name, "SensorType")) { trip_pt->sensor_type.assign(tmp_value); string_trim(trip_pt->sensor_type); } else if (!strcasecmp((const char*) cur_node->name, "type")) { char *type_val = char_trim(tmp_value); if (type_val && !strcasecmp(type_val, "active")) trip_pt->trip_pt_type = ACTIVE; else if (type_val && !strcasecmp(type_val, "passive")) trip_pt->trip_pt_type = PASSIVE; else if (type_val && !strcasecmp(type_val, "critical")) trip_pt->trip_pt_type = CRITICAL; else if (type_val && !strcasecmp(type_val, "max")) trip_pt->trip_pt_type = MAX; } else if (!strcasecmp((const char*) cur_node->name, "ControlType")) { char *ctrl_val = char_trim(tmp_value); if (ctrl_val && !strcasecmp(ctrl_val, "SEQUENTIAL")) trip_pt->control_type = SEQUENTIAL; else trip_pt->control_type = PARALLEL; } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_trip_points(xmlNode * a_node, xmlDoc *doc, thermal_zone_t *info_ptr) { xmlNode *cur_node = NULL; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); if (!strcasecmp((const char*) cur_node->name, "TripPoint")) { trip_point_t trip_pt; trip_pt.hyst = trip_pt.temperature = 0; trip_pt.trip_pt_type = PASSIVE; trip_pt.control_type = PARALLEL; trip_pt.influence = 100; trip_pt.sensor_type.clear(); if (parse_new_trip_point(cur_node->children, doc, &trip_pt) == THD_SUCCESS) info_ptr->trip_pts.push_back(trip_pt); } } } return THD_SUCCESS; } int cthd_parse::parse_pid_values(xmlNode * a_node, xmlDoc *doc, pid_control_t *pid_ptr) { xmlNode *cur_node = NULL; char *tmp_value; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (char*) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char*) cur_node->name, "Kp")) { pid_ptr->Kp = atof(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "Kd")) { pid_ptr->Kd = atof(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "Ki")) { pid_ptr->Ki = atof(tmp_value); } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_new_zone(xmlNode * a_node, xmlDoc *doc, thermal_zone_t *info_ptr) { xmlNode *cur_node = NULL; char *tmp_value; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (char*) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char*) cur_node->name, "TripPoints")) { parse_trip_points(cur_node->children, doc, info_ptr); } else if (!strcasecmp((const char*) cur_node->name, "Type")) { info_ptr->type.assign((const char*) tmp_value); string_trim(info_ptr->type); } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_new_cooling_dev(xmlNode * a_node, xmlDoc *doc, cooling_dev_t *cdev) { xmlNode *cur_node = NULL; char *tmp_value; cdev->max_state = cdev->min_state = 0; cdev->mask = 0; cdev->inc_dec_step = 1; cdev->read_back = true; cdev->auto_down_control = false; cdev->status = 0; cdev->pid_enable = false; cdev->unit_val = ABSOULUTE_VALUE; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (char*) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char *) cur_node->name, "Index")) { cdev->index = atoi(tmp_value); } else if (!strcasecmp((const char *) cur_node->name, "Type")) { cdev->type_string.assign((const char*) tmp_value); string_trim(cdev->type_string); } else if (!strcasecmp((const char *) cur_node->name, "Path")) { cdev->mask |= CDEV_DEF_BIT_PATH; cdev->path_str.assign((const char*) tmp_value); string_trim(cdev->path_str); } else if (!strcasecmp((const char *) cur_node->name, "MinState")) { cdev->mask |= CDEV_DEF_BIT_MIN_STATE; cdev->min_state = atoi(tmp_value); } else if (!strcasecmp((const char *) cur_node->name, "MaxState")) { cdev->mask |= CDEV_DEF_BIT_MAX_STATE; cdev->max_state = atoi(tmp_value); } else if (!strcasecmp((const char *) cur_node->name, "IncDecStep")) { cdev->mask |= CDEV_DEF_BIT_STEP; cdev->inc_dec_step = atoi(tmp_value); } else if (!strcasecmp((const char *) cur_node->name, "ReadBack")) { cdev->mask |= CDEV_DEF_BIT_READ_BACK; cdev->read_back = atoi(tmp_value); } else if (!strcasecmp((const char *) cur_node->name, "DebouncePeriod")) { cdev->mask |= CDEV_DEF_BIT_DEBOUNCE_VAL; cdev->debounce_interval = atoi(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "PidControl")) { cdev->mask |= CDEV_DEF_BIT_PID_PARAMS; cdev->pid_enable = true; parse_pid_values(cur_node->children, doc, &cdev->pid); } else if (!strcasecmp((const char *) cur_node->name, "AutoOffMode")) { cdev->mask |= CDEV_DEF_BIT_AUTO_DOWN; if (atoi(tmp_value)) cdev->auto_down_control = true; else cdev->auto_down_control = false; } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_cooling_devs(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr) { xmlNode *cur_node = NULL; cooling_dev_t cdev; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); if (!strcasecmp((const char*) cur_node->name, "CoolingDevice")) { cdev.index = cdev.max_state = cdev.min_state = 0; cdev.inc_dec_step = 1; cdev.auto_down_control = false; cdev.path_str.clear(); cdev.type_string.clear(); parse_new_cooling_dev(cur_node->children, doc, &cdev); info_ptr->cooling_devs.push_back(cdev); } } } return THD_SUCCESS; } int cthd_parse::parse_thermal_zones(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr) { xmlNode *cur_node = NULL; thermal_zone_t zone; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); if (!strcasecmp((const char*) cur_node->name, "ThermalZone")) { zone.trip_pts.clear(); parse_new_zone(cur_node->children, doc, &zone); info_ptr->zones.push_back(zone); } } } return THD_SUCCESS; } int cthd_parse::parse_new_sensor_link(xmlNode * a_node, xmlDoc *doc, thermal_sensor_link_t *info_ptr) { xmlNode *cur_node = NULL; char *tmp_value; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (char*) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char*) cur_node->name, "SensorType")) { info_ptr->name.assign(tmp_value); string_trim(info_ptr->name); } else if (!strcasecmp((const char*) cur_node->name, "Multiplier")) { info_ptr->multiplier = atof(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "Offset")) { info_ptr->offset = atof(tmp_value); } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_new_sensor(xmlNode * a_node, xmlDoc *doc, thermal_sensor_t *info_ptr) { xmlNode *cur_node = NULL; char *tmp_value; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (char*) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char*) cur_node->name, "Type")) { info_ptr->name.assign(tmp_value); string_trim(info_ptr->name); } else if (!strcasecmp((const char*) cur_node->name, "Path")) { info_ptr->mask |= SENSOR_DEF_BIT_PATH; info_ptr->path.assign(tmp_value); string_trim(info_ptr->path); } else if (!strcasecmp((const char*) cur_node->name, "AsyncCapable")) { info_ptr->async_capable = atoi(tmp_value); info_ptr->mask |= SENSOR_DEF_BIT_ASYNC_CAPABLE; } else if (!strcasecmp((const char*) cur_node->name, "Virtual")) { info_ptr->virtual_sensor = atoi(tmp_value); } else if (!strcasecmp((const char*) cur_node->name, "SensorLink")) { parse_new_sensor_link(cur_node->children, doc, &info_ptr->sensor_link); } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_thermal_sensors(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr) { xmlNode *cur_node = NULL; thermal_sensor_t sensor; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); if (!strcasecmp((const char*) cur_node->name, "ThermalSensor")) { sensor.name.clear(); sensor.path.clear(); sensor.async_capable = false; sensor.mask = 0; sensor.virtual_sensor = false; parse_new_sensor(cur_node->children, doc, &sensor); info_ptr->sensors.push_back(sensor); } } } return THD_SUCCESS; } int cthd_parse::parse_new_platform_info(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr) { xmlNode *cur_node = NULL; char *tmp_value; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (char*) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char*) cur_node->name, "uuid")) { info_ptr->uuid.assign((const char*) tmp_value); string_trim(info_ptr->uuid); } else if (!strcasecmp((const char*) cur_node->name, "ProductName")) { info_ptr->product_name.assign((const char*) tmp_value); string_trim(info_ptr->product_name); } else if (!strcasecmp((const char*) cur_node->name, "Name")) { info_ptr->name.assign((const char*) tmp_value); string_trim(info_ptr->name); } else if (!strcasecmp((const char*) cur_node->name, "Preference")) { char *pref_val = char_trim(tmp_value); if (pref_val && !strcasecmp(pref_val, "PERFORMANCE")) info_ptr->default_prefernce = PREF_PERFORMANCE; else info_ptr->default_prefernce = PREF_ENERGY_CONSERVE; } else if (!strcasecmp((const char*) cur_node->name, "ThermalZones")) { parse_thermal_zones(cur_node->children, doc, info_ptr); } else if (!strcasecmp((const char*) cur_node->name, "ThermalSensors")) { parse_thermal_sensors(cur_node->children, doc, info_ptr); } else if (!strcasecmp((const char*) cur_node->name, "CoolingDevices")) { parse_cooling_devs(cur_node->children, doc, info_ptr); } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_new_platform(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr) { xmlNode *cur_node = NULL; unsigned char *tmp_value; thermal_info_t info; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); tmp_value = (unsigned char*) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (!strcasecmp((const char*) cur_node->name, "Platform")) { info.cooling_devs.clear(); info.zones.clear(); parse_new_platform_info(cur_node->children, doc, &info); thermal_info_list.push_back(info); } if (tmp_value) xmlFree(tmp_value); } } return THD_SUCCESS; } int cthd_parse::parse_new_thermal_conf(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr) { xmlNode *cur_node = NULL; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); if (!strcasecmp((const char*) cur_node->name, "ThermalConfiguration")) { parse_new_platform(cur_node->children, doc, info_ptr); } } } return THD_SUCCESS; } int cthd_parse::parse(xmlNode * a_node, xmlDoc *doc) { xmlNode *cur_node = NULL; thermal_info_t info; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { DEBUG_PARSER_PRINT("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); if (!strcasecmp((const char*) cur_node->name, "ThermalConfiguration")) { parse_new_platform(cur_node->children, doc, &info); } } } return THD_SUCCESS; } int cthd_parse::start_parse() { parse(root_element, doc); return THD_SUCCESS; } void cthd_parse::parser_deinit() { for (unsigned int i = 0; i < thermal_info_list.size(); ++i) { thermal_info_list[i].sensors.clear(); for (unsigned int j = 0; j < thermal_info_list[i].zones.size(); ++j) { thermal_info_list[i].zones[j].trip_pts.clear(); } thermal_info_list[i].zones.clear(); thermal_info_list[i].cooling_devs.clear(); } xmlFreeDoc(doc); } void cthd_parse::dump_thermal_conf() { thd_log_info(" Dumping parsed XML Data\n"); for (unsigned int i = 0; i < thermal_info_list.size(); ++i) { thd_log_info(" *** Index %u ***\n", i); thd_log_info("Name: %s\n", thermal_info_list[i].name.c_str()); thd_log_info("UUID: %s\n", thermal_info_list[i].uuid.c_str()); thd_log_info("type: %d\n", thermal_info_list[i].default_prefernce); for (unsigned int j = 0; j < thermal_info_list[i].sensors.size(); ++j) { thd_log_info("\tSensor %u \n", j); thd_log_info("\t Name: %s\n", thermal_info_list[i].sensors[j].name.c_str()); thd_log_info("\t Path: %s\n", thermal_info_list[i].sensors[j].path.c_str()); thd_log_info("\t Async Capable: %d\n", thermal_info_list[i].sensors[j].async_capable); thd_log_info("\t Virtual: %d\n", thermal_info_list[i].sensors[j].virtual_sensor); if (thermal_info_list[i].sensors[j].virtual_sensor) { thd_log_info("\t\t Link type: %s\n", thermal_info_list[i].sensors[j].sensor_link.name.c_str()); thd_log_info("\t\t Link mult: %f\n", thermal_info_list[i].sensors[j].sensor_link.multiplier); thd_log_info("\t\t Link offset: %f\n", thermal_info_list[i].sensors[j].sensor_link.offset); } } for (unsigned int j = 0; j < thermal_info_list[i].zones.size(); ++j) { thd_log_info("\tZone %u \n", j); thd_log_info("\t Name: %s\n", thermal_info_list[i].zones[j].type.c_str()); for (unsigned int k = 0; k < thermal_info_list[i].zones[j].trip_pts.size(); ++k) { thd_log_info("\t\t Trip Point %u \n", k); thd_log_info("\t\t temp %d \n", thermal_info_list[i].zones[j].trip_pts[k].temperature); thd_log_info("\t\t trip type %d \n", thermal_info_list[i].zones[j].trip_pts[k].trip_pt_type); thd_log_info("\t\t hyst id %d \n", thermal_info_list[i].zones[j].trip_pts[k].hyst); thd_log_info("\t\t sensor type %s \n", thermal_info_list[i].zones[j].trip_pts[k].sensor_type.c_str()); for (unsigned int l = 0; l < thermal_info_list[i].zones[j].trip_pts[k].cdev_trips.size(); ++l) { thd_log_info("\t\t cdev index %u \n", l); thd_log_info("\t\t\t type %s \n", thermal_info_list[i].zones[j].trip_pts[k].cdev_trips[l].type.c_str()); thd_log_info("\t\t\t influence %d \n", thermal_info_list[i].zones[j].trip_pts[k].cdev_trips[l].influence); thd_log_info("\t\t\t SamplingPeriod %d \n", thermal_info_list[i].zones[j].trip_pts[k].cdev_trips[l].sampling_period); if (thermal_info_list[i].zones[j].trip_pts[k].cdev_trips[l].target_state != TRIP_PT_INVALID_TARGET_STATE) thd_log_info("\t\t\t TargetState %d \n", thermal_info_list[i].zones[j].trip_pts[k].cdev_trips[l].target_state); } } } for (unsigned int l = 0; l < thermal_info_list[i].cooling_devs.size(); ++l) { thd_log_info("\tCooling Dev %u \n", l); thd_log_info("\t\tType: %s\n", thermal_info_list[i].cooling_devs[l].type_string.c_str()); thd_log_info("\t\tPath: %s\n", thermal_info_list[i].cooling_devs[l].path_str.c_str()); thd_log_info("\t\tMin: %d\n", thermal_info_list[i].cooling_devs[l].min_state); thd_log_info("\t\tMax: %d\n", thermal_info_list[i].cooling_devs[l].max_state); thd_log_info("\t\tStep: %d\n", thermal_info_list[i].cooling_devs[l].inc_dec_step); thd_log_info("\t\tAutoDownControl: %d\n", thermal_info_list[i].cooling_devs[l].auto_down_control); if (thermal_info_list[i].cooling_devs[l].pid_enable) { thd_log_info("\t PID: Kp %f\n", thermal_info_list[i].cooling_devs[l].pid.Kp); thd_log_info("\t PID: Ki %f\n", thermal_info_list[i].cooling_devs[l].pid.Ki); thd_log_info("\t PID: Kd %f\n", thermal_info_list[i].cooling_devs[l].pid.Kd); } } } } bool cthd_parse::platform_matched() { std::string line; std::ifstream product_uuid("/sys/class/dmi/id/product_uuid"); if (product_uuid.is_open() && getline(product_uuid, line)) { for (unsigned int i = 0; i < thermal_info_list.size(); ++i) { if (!thermal_info_list[i].uuid.size()) continue; string_trim(line); thd_log_debug("config product uuid [%s] match with [%s]\n", thermal_info_list[i].uuid.c_str(), line.c_str()); if (thermal_info_list[i].uuid == "*") { matched_thermal_info_index = i; thd_log_info("UUID matched [wildcard]\n"); return true; } if (line == thermal_info_list[i].uuid) { matched_thermal_info_index = i; thd_log_info("UUID matched \n"); return true; } } } std::ifstream product_name("/sys/class/dmi/id/product_name"); if (product_name.is_open() && getline(product_name, line)) { for (unsigned int i = 0; i < thermal_info_list.size(); ++i) { if (!thermal_info_list[i].product_name.size()) continue; string_trim(line); thd_log_debug("config product name [%s] match with [%s]\n", thermal_info_list[i].product_name.c_str(), line.c_str()); if (thermal_info_list[i].product_name == "*") { matched_thermal_info_index = i; thd_log_info("Product Name matched [wildcard]\n"); return true; } if (line == thermal_info_list[i].product_name) { matched_thermal_info_index = i; thd_log_info("Product Name matched \n"); return true; } } } for (unsigned int i = 0; i < thermal_info_list.size(); ++i) { if (!thermal_info_list[i].uuid.size()) continue; if (!thermal_info_list[i].product_name.compare(0, 1, "*")) { matched_thermal_info_index = i; thd_log_info("Product Name matched \n"); return true; } } return false; } int cthd_parse::trip_count(unsigned int zone_index) { if (zone_index < thermal_info_list[matched_thermal_info_index].zones.size()) { return thermal_info_list[matched_thermal_info_index].zones[zone_index].trip_pts.size(); } else return -1; } trip_point_t* cthd_parse::get_trip_point(unsigned int zone_index, unsigned int trip_index) { if (zone_index < thermal_info_list[matched_thermal_info_index].zones.size()) { if (trip_index < thermal_info_list[matched_thermal_info_index].zones[zone_index].trip_pts.size()) return &thermal_info_list[matched_thermal_info_index].zones[zone_index].trip_pts[trip_index]; return NULL; } else return NULL; } cooling_dev_t* cthd_parse::get_cool_dev_index(unsigned int cdev_index) { if (cdev_index < thermal_info_list[matched_thermal_info_index].cooling_devs.size()) return &thermal_info_list[matched_thermal_info_index].cooling_devs[cdev_index]; else return NULL; } thermal_sensor_t* cthd_parse::get_sensor_dev_index(unsigned int sensor_index) { if (sensor_index < thermal_info_list[matched_thermal_info_index].sensors.size()) return &thermal_info_list[matched_thermal_info_index].sensors[sensor_index]; else return NULL; } thermal_zone_t *cthd_parse::get_zone_dev_index(unsigned int zone_index) { if (zone_index < thermal_info_list[matched_thermal_info_index].zones.size()) return &thermal_info_list[matched_thermal_info_index].zones[zone_index]; else return NULL; } bool cthd_parse::pid_status(int cdev_index) { return thermal_info_list[matched_thermal_info_index].cooling_devs[cdev_index].pid_enable; } bool cthd_parse::get_pid_values(int cdev_index, int *Kp, int *Ki, int *Kd) { if (thermal_info_list[matched_thermal_info_index].cooling_devs[cdev_index].pid_enable) { *Kp = thermal_info_list[matched_thermal_info_index].cooling_devs[cdev_index].pid.Kp; *Kd = thermal_info_list[matched_thermal_info_index].cooling_devs[cdev_index].pid.Kd; *Ki = thermal_info_list[matched_thermal_info_index].cooling_devs[cdev_index].pid.Ki; return true; } return false; } int cthd_parse::set_default_preference() { cthd_preference thd_pref; int ret; if (thermal_info_list[matched_thermal_info_index].default_prefernce == PREF_PERFORMANCE) ret = thd_pref.set_preference("PERFORMANCE"); else ret = thd_pref.set_preference("ENERGY_CONSERVE"); return ret; } thermald-1.5/src/thd_engine.h0000664000175000017500000001507012661205366014701 0ustar kingking/* * thd_engine.h: thermal engine class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_ENGINE_H_ #define THD_ENGINE_H_ #include #include #include #include "thd_common.h" #include "thd_sys_fs.h" #include "thd_preference.h" #include "thd_sensor.h" #include "thd_sensor_virtual.h" #include "thd_zone.h" #include "thd_cdev.h" #include "thd_parse.h" #include "thd_kobj_uevent.h" #include "thd_rapl_power_meter.h" #define MAX_MSG_SIZE 512 #define THD_NUM_OF_POLL_FDS 10 typedef enum { WAKEUP, TERMINATE, PREF_CHANGED, THERMAL_ZONE_NOTIFY, RELOAD_ZONES, POLL_ENABLE, POLL_DISABLE, } message_name_t; // This defines whether the thermal control is entirey done by // this daemon or it just complements, what is done in kernel typedef enum { COMPLEMENTRY, EXCLUSIVE, } control_mode_t; typedef struct { message_name_t msg_id; int msg_size; unsigned long msg[MAX_MSG_SIZE]; } message_capsul_t; typedef struct { unsigned int family; unsigned int model; } supported_ids_t; class cthd_engine { protected: std::vector zones; std::vector sensors; std::vector cdevs; int current_cdev_index; int current_zone_index; int current_sensor_index; bool parse_thermal_zone_success; bool parse_thermal_cdev_success; private: int poll_timeout_msec; int wakeup_fd; int uevent_fd; control_mode_t control_mode; int write_pipe_fd; int preference; bool status; time_t thz_last_uevent_time; time_t thz_last_temp_ind_time; bool terminate; int genuine_intel; int has_invariant_tsc; int has_aperf; bool proc_list_matched; int poll_interval_sec; cthd_preference thd_pref; unsigned int poll_sensor_mask; std::string config_file; pthread_t thd_engine; pthread_attr_t thd_attr; pthread_mutex_t thd_engine_mutex; std::vector zone_preferences; static const int thz_notify_debounce_interval = 3; struct pollfd poll_fds[THD_NUM_OF_POLL_FDS]; int poll_fd_cnt; bool rt_kernel; cthd_kobj_uevent kobj_uevent; bool parser_init_done; int proc_message(message_capsul_t *msg); void process_pref_change(); void thermal_zone_change(message_capsul_t *msg); void process_terminate(); void check_for_rt_kernel(); public: static const int max_thermal_zones = 10; static const int max_cool_devs = 50; static const int def_poll_interval = 4000; static const int soft_cdev_start_index = 100; cthd_parse parser; cthd_rapl_power_meter rapl_power_meter; cthd_engine(); virtual ~cthd_engine(); void set_control_mode(control_mode_t mode) { control_mode = mode; } control_mode_t get_control_mode() { return control_mode; } void thd_engine_thread(); int thd_engine_start(bool ignore_cpuid_check); int thd_engine_stop(); int check_cpu_id(); bool set_preference(const int pref); void thd_engine_terminate(); void thd_engine_calibrate(); int thd_engine_set_user_max_temp(const char *zone_type, const char *user_set_point); int thd_engine_set_user_psv_temp(const char *zone_type, const char *user_set_point); void poll_enable_disable(bool status, message_capsul_t *msg); cthd_cdev *thd_get_cdev_at_index(int index); void send_message(message_name_t msg_id, int size, unsigned char *msg); void takeover_thermal_control(); void giveup_thermal_control(); void thd_engine_poll_enable(int sensor_id); void thd_engine_poll_disable(int sensor_id); void thd_read_default_thermal_sensors(); void thd_read_default_thermal_zones(); void thd_read_default_cooling_devices(); virtual int read_thermal_sensors() { return 0; } ; virtual int read_thermal_zones() { return 0; } ; virtual int read_cooling_devices() { return 0; } ; int use_custom_zones() { return parse_thermal_zone_success; } int use_custom_cdevs() { return parse_thermal_cdev_success; } static const int max_cpu_count = 64; time_t last_cpu_update[max_cpu_count]; virtual bool apply_cpu_operation(int cpu) { return false; } int get_poll_timeout_ms() { return poll_timeout_msec; } int get_poll_timeout_sec() { return poll_timeout_msec / 1000; } void thd_engine_reload_zones(); bool processor_id_match() { return proc_list_matched; } void set_poll_interval(int val) { poll_interval_sec = val; } int get_preference() { return preference; } void set_config_file(std::string conf_file) { config_file = conf_file; } std::string get_config_file() { return config_file; } cthd_zone *search_zone(std::string name); cthd_cdev *search_cdev(std::string name); cthd_sensor *search_sensor(std::string name); cthd_sensor *get_sensor(int index); cthd_zone *get_zone(int index); cthd_zone *get_zone(std::string type); int get_sensor_temperature(int index, unsigned int *temperature); unsigned int get_sensor_count() { return sensors.size(); } unsigned int get_zone_count() { return zones.size(); } unsigned int get_cdev_count() { return cdevs.size(); } void add_zone(cthd_zone *zone) { zones.push_back(zone); } bool rt_kernel_status() { return rt_kernel; } // User/External messages int user_add_sensor(std::string name, std::string path); cthd_sensor *user_get_sensor(unsigned int index); cthd_zone *user_get_zone(unsigned int index); int user_add_virtual_sensor(std::string name, std::string dep_sensor, double slope, double intercept); int user_set_psv_temp(std::string name, unsigned int temp); int user_set_max_temp(std::string name, unsigned int temp); int user_add_zone(std::string zone_name, unsigned int trip_temp, std::string sensor_name, std::string cdev_name); int user_set_zone_status(std::string name, int status); int user_get_zone_status(std::string name, int *status); int user_delete_zone(std::string name); int user_add_cdev(std::string cdev_name, std::string cdev_path, int min_state, int max_state, int step); cthd_cdev *user_get_cdev(unsigned int index); int parser_init(); void parser_deinit(); }; #endif /* THD_ENGINE_H_ */ thermald-1.5/src/thd_common.h0000664000175000017500000000166112661205366014725 0ustar kingking/* thd_msr.cpp: thermal engine common definitions * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_COMMON_H_ #define THD_COMMON_H_ #include "thermald.h" #endif /* THD_COMMON_H_ */ thermald-1.5/src/thd_cdev_backlight.h0000664000175000017500000000231212661205366016360 0ustar kingking/* * thd_cdev_backlight.h: thermal backlight cooling interface * * Copyright (C) 2015 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef SRC_THD_CDEV_BACKLIGHT_H_ #define SRC_THD_CDEV_BACKLIGHT_H_ #include "thd_cdev.h" class cthd_cdev_backlight: public cthd_cdev { private: static const std::string backlight_devices[]; public: cthd_cdev_backlight(unsigned int _index, int _cpu_index); void set_curr_state(int state, int arg); int update(); }; #endif /* SRC_THD_CDEV_BACKLIGHT_H_ */ thermald-1.5/src/thd_parse.h0000664000175000017500000001260612661205366014550 0ustar kingking/* * thd_engine.cpp: thermal engine class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_PARSE_H #define THD_PARSE_H #include #include #include #include #include "thermald.h" #include "thd_trip_point.h" #define CDEV_DEF_BIT_MIN_STATE 0x0001 #define CDEV_DEF_BIT_MAX_STATE 0x0002 #define CDEV_DEF_BIT_STEP 0x0004 #define CDEV_DEF_BIT_READ_BACK 0x0008 #define CDEV_DEF_BIT_AUTO_DOWN 0x0010 #define CDEV_DEF_BIT_PATH 0x0020 #define CDEV_DEF_BIT_STATUS 0x0040 #define CDEV_DEF_BIT_UNIT_VAL 0x0080 #define CDEV_DEF_BIT_DEBOUNCE_VAL 0x0100 #define CDEV_DEF_BIT_PID_PARAMS 0x0200 #define SENSOR_DEF_BIT_PATH 0x0001 #define SENSOR_DEF_BIT_ASYNC_CAPABLE 0x0002 typedef struct { double Kp; double Ki; double Kd; } pid_control_t; typedef struct { std::string name; double multiplier; double offset; } thermal_sensor_link_t; typedef struct { unsigned int mask; std::string name; std::string path; bool async_capable; bool virtual_sensor; thermal_sensor_link_t sensor_link; } thermal_sensor_t; typedef struct { std::string type; int influence; int sampling_period; int target_state; } trip_cdev_t; typedef struct { int temperature; int hyst; trip_point_type_t trip_pt_type; trip_control_type_t control_type; int influence; std::string sensor_type; std::vector cdev_trips; } trip_point_t; typedef struct { std::string type; std::vector trip_pts; } thermal_zone_t; typedef enum { ABSOULUTE_VALUE, RELATIVE_PERCENTAGES } unit_value_t; typedef struct { bool status; unsigned int mask; // Fields which are present in config int index; unit_value_t unit_val; int min_state; int max_state; int inc_dec_step; bool read_back; // For some device read back current state is not possible bool auto_down_control; std::string type_string; std::string path_str; int debounce_interval; bool pid_enable; pid_control_t pid; } cooling_dev_t; typedef struct { std::string name; std::string uuid; std::string product_name; int default_prefernce; std::vector sensors; std::vector zones; std::vector cooling_devs; } thermal_info_t; class cthd_parse { private: std::string filename; std::string filename_auto; std::vector thermal_info_list; int matched_thermal_info_index; xmlDoc *doc; xmlNode *root_element; int parse(xmlNode * a_node, xmlDoc *doc); int parse_pid_values(xmlNode * a_node, xmlDoc *doc, pid_control_t *pid_ptr); int parse_new_trip_cdev(xmlNode * a_node, xmlDoc *doc, trip_cdev_t *trip_cdev); int parse_new_thermal_conf(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info); int parse_new_platform_info(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info); int parse_new_zone(xmlNode * a_node, xmlDoc *doc, thermal_zone_t *info_ptr); int parse_new_cooling_dev(xmlNode * a_node, xmlDoc *doc, cooling_dev_t *info_ptr); int parse_new_trip_point(xmlNode * a_node, xmlDoc *doc, trip_point_t *trip_pt); int parse_thermal_zones(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr); int parse_new_sensor(xmlNode * a_node, xmlDoc *doc, thermal_sensor_t *info_ptr); int parse_new_sensor_link(xmlNode * a_node, xmlDoc *doc, thermal_sensor_link_t *info_ptr); int parse_thermal_sensors(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr); int parse_cooling_devs(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info_ptr); int parse_trip_points(xmlNode * a_node, xmlDoc *doc, thermal_zone_t *info_ptr); int parse_new_platform(xmlNode * a_node, xmlDoc *doc, thermal_info_t *info); void string_trim(std::string &str); char *char_trim(char *trim); public: cthd_parse(); int parser_init(std::string config_file); void parser_deinit(); int start_parse(); void dump_thermal_conf(); bool platform_matched(); int zone_count() { return thermal_info_list[matched_thermal_info_index].zones.size(); } int cdev_count() { return thermal_info_list[matched_thermal_info_index].cooling_devs.size(); } int sensor_count() { return thermal_info_list[matched_thermal_info_index].sensors.size(); } int set_default_preference(); int trip_count(unsigned int zone_index); bool pid_status(int cdev_index); bool get_pid_values(int cdev_index, int *Kp, int *Ki, int *Kd); trip_point_t *get_trip_point(unsigned int zone_index, unsigned int trip_index); cooling_dev_t *get_cool_dev_index(unsigned int cdev_index); thermal_sensor_t *get_sensor_dev_index(unsigned int sensor_index); thermal_zone_t *get_zone_dev_index(unsigned int zone_index); // std::string get_sensor_path(int zone_index) { // return thermal_info_list[matched_thermal_info_index].zones[zone_index].path; // } }; #endif thermald-1.5/src/thd_pid.cpp0000664000175000017500000000337612661205366014551 0ustar kingking/* * thd_pid.cpp: pid implementation * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_pid.h" cthd_pid::cthd_pid() { kp = 0.0005; ki = kd = 0.0001; last_time = 0; err_sum = 0.0; last_err = 0.0; target_temp = 0; } int cthd_pid::pid_output(unsigned int curr_temp) { double output; double d_err = 0; time_t now; time(&now); if (last_time == 0) last_time = now; time_t timeChange = (now - last_time); int error = curr_temp - target_temp; thd_log_debug("pid_output error %d %g:%g\n", error, kp, kp * error); err_sum += (error * timeChange); if (timeChange) d_err = (error - last_err) / timeChange; else d_err = 0.0; /*Compute PID Output*/ output = kp * error + ki * err_sum + kd * d_err; thd_log_debug("pid %d:%d:%d:%d\n", (int) output, (int) (kp * error), (int) (ki * err_sum), (int) (kd * d_err)); /*Remember some variables for next time*/ last_err = error; last_time = now; thd_log_debug("pid_output %d:%d %g:%d\n", curr_temp, target_temp, output, (int) output); return (int) output; } thermald-1.5/src/thd_cdev_order_parser.cpp0000664000175000017500000000510112661205366017451 0ustar kingking/* * thd_cdev_order_parser.cpp: Specify cdev order * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_cdev_order_parser.h" #include "thd_sys_fs.h" cthd_cdev_order_parse::cthd_cdev_order_parse() : doc(NULL), root_element(NULL) { std::string name = TDCONFDIR; filename = name + "/" "thermal-cpu-cdev-order.xml"; } int cthd_cdev_order_parse::parser_init() { doc = xmlReadFile(filename.c_str(), NULL, 0); if (doc == NULL) { thd_log_warn("error: could not parse file %s\n", filename.c_str()); return THD_ERROR; } root_element = xmlDocGetRootElement(doc); if (root_element == NULL) { thd_log_warn("error: could not get root element \n"); return THD_ERROR; } return THD_SUCCESS; } int cthd_cdev_order_parse::start_parse() { parse(root_element, doc); return THD_SUCCESS; } void cthd_cdev_order_parse::parser_deinit() { xmlFreeDoc(doc); } int cthd_cdev_order_parse::parse_new_cdev(xmlNode * a_node, xmlDoc *doc) { xmlNode *cur_node = NULL; char *tmp_value; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { tmp_value = (char *) xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1); if (tmp_value) { thd_log_info("node type: Element, name: %s value: %s\n", cur_node->name, tmp_value); cdev_order_list.push_back(tmp_value); xmlFree(tmp_value); } } } return THD_SUCCESS; } int cthd_cdev_order_parse::parse(xmlNode * a_node, xmlDoc *doc) { xmlNode *cur_node = NULL; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { if (!strcmp((const char*) cur_node->name, "CoolingDeviceOrder")) { parse_new_cdev(cur_node->children, doc); } } } return THD_SUCCESS; } int cthd_cdev_order_parse::get_order_list(std::vector &list) { list = cdev_order_list; return 0; } thermald-1.5/src/thd_zone_cpu.h0000664000175000017500000000340612661205366015256 0ustar kingking/* * thd_zone_dts.h: thermal engine DTS class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * * This interface allows to overide per zone read data from sysfs for buggy BIOS. */ #ifndef THD_ZONE_DTS_H #define THD_ZONE_DTS_H #include "thd_zone.h" #include class cthd_zone_cpu: public cthd_zone { protected: csys_fs dts_sysfs; int critical_temp; int max_temp; int set_point; int prev_set_point; int trip_point_cnt; unsigned int sensor_mask; int phy_package_id; std::vector sensor_sysfs; int init(); int parse_cdev_order(); int pkg_thres_th_zone; bool pkg_temp_poll_enable; public: static const int max_dts_sensors = 16; static const int def_hystersis = 0; static const int def_offset_from_critical = 10000; static const int def_critical_temp = 100000; cthd_zone_cpu(int count, std::string path, int package_id); int load_cdev_xml(cthd_trip_point &trip_pt, std::vector &list); virtual int read_trip_points(); int read_cdev_trip_points(); int zone_bind_sensors(); }; #endif thermald-1.5/src/thd_cdev_gen_sysfs.h0000664000175000017500000000235412661205366016436 0ustar kingking/* * cthd_sysfs_gen_sysfs.h: thermal cooling class interface * for non thermal cdev sysfs * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_GEN_SYSFS_H_ #define THD_CDEV_GEN_SYSFS_H_ #include "thd_cdev.h" class cthd_gen_sysfs_cdev: public cthd_cdev { protected: public: cthd_gen_sysfs_cdev(unsigned int _index, std::string control_path) : cthd_cdev(_index, control_path) { } virtual void set_curr_state(int state, int arg); virtual int update(); }; #endif /* THD_CDEV_GEN_SYSFS_H_ */ thermald-1.5/src/thd_cdev_backlight.cpp0000664000175000017500000000411412661205366016715 0ustar kingking/* * thd_cdev_backlight.cpp: thermal backlight cooling implementation * * Copyright (C) 2015 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_cdev_backlight.h" #define MAX_BACKLIGHT_DEV 4 const std::string cthd_cdev_backlight::backlight_devices[MAX_BACKLIGHT_DEV] = { "/sys/class/backlight/intel_backlight", "/sys/class/backlight/acpi_video0", "/sys/class/leds/lcd-backlight", "/sys/class/backlight/lcd-backlight" }; cthd_cdev_backlight::cthd_cdev_backlight(unsigned int _index, int _cpu_index): cthd_cdev(_index, backlight_devices[0]) { int active_device = 0; do { cdev_sysfs.update_path(backlight_devices[active_device]); if (update() == THD_SUCCESS) break; active_device++; }while (active_device < MAX_BACKLIGHT_DEV); } int cthd_cdev_backlight::update() { int ret; if (cdev_sysfs.exists()) { std::string temp_str; ret = cdev_sysfs.read("max_brightness", temp_str); if (ret < 0) return ret; std::istringstream(temp_str) >> max_state; } if (max_state <= 0) return THD_ERROR; set_inc_dec_value(max_state * (float) 10 / 100); return THD_SUCCESS; } void cthd_cdev_backlight::set_curr_state(int state, int arg) { int ret; ret = cdev_sysfs.write("brightness", max_state - state); if (ret < 0) { thd_log_warn("Failed to write brightness\n"); return; } curr_state = state; } thermald-1.5/src/thd_preference.cpp0000664000175000017500000000737612661205366016117 0ustar kingking/* * thd_preference.cpp: Thermal preference class implementation * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_preference.h" cthd_preference::cthd_preference() : old_preference(0) { std::stringstream filename; filename << TDRUNDIR << "/" << "thd_preference.conf"; std::ifstream ifs(filename.str().c_str(), std::ifstream::in); if (!ifs.good()) { preference = PREF_ENERGY_CONSERVE; } else { ifs >> preference; } ifs.close(); } std::string cthd_preference::int_pref_to_string(int pref) { std::string perf_str; switch (preference) { case PREF_PERFORMANCE: perf_str = "PERFORMANCE"; break; case PREF_ENERGY_CONSERVE: perf_str = "ENERGY_CONSERVE"; break; case PREF_DISABLED: perf_str = "DISABLE"; break; default: perf_str = "INVALID"; break; } return perf_str; } int cthd_preference::string_pref_to_int(std::string &pref_str) { int pref; if (pref_str == "PERFORMANCE") pref = PREF_PERFORMANCE; else if (pref_str == "ENERGY_CONSERVE") pref = PREF_ENERGY_CONSERVE; else if (pref_str == "DISABLE") pref = PREF_DISABLED; else pref = PREF_PERFORMANCE; return pref; } std::string cthd_preference::get_preference_str() { return int_pref_to_string(preference); } const char *cthd_preference::get_preference_cstr() { return strdup(int_pref_to_string(preference).c_str()); } int cthd_preference::get_preference() { return preference; } void cthd_preference::refresh() { std::stringstream filename; filename << TDRUNDIR << "/" << "thd_preference.conf"; std::ifstream ifs(filename.str().c_str(), std::ifstream::in); if (!ifs.good()) { preference = PREF_ENERGY_CONSERVE; } else { ifs >> preference; } ifs.close(); } bool cthd_preference::set_preference(const char *pref_str) { std::string str(pref_str); int pref = string_pref_to_int(str); std::stringstream filename; filename << TDRUNDIR << "/" << "thd_preference.conf"; std::ofstream fout(filename.str().c_str()); if (!fout.good()) { return false; } fout << pref; fout.close(); // Save the old preference old_preference = preference; std::stringstream filename_save; filename_save << TDRUNDIR << "/" << "thd_preference.conf.save"; std::ofstream fout_save(filename_save.str().c_str()); if (!fout_save.good()) { return false; } fout_save << old_preference; fout_save.close(); std::ifstream ifs(filename.str().c_str(), std::ifstream::in); if (!ifs.good()) { preference = PREF_PERFORMANCE; } else { //ifs.read(reinterpret_cast < char * > (&preference), sizeof(preference)); ifs >> preference; } ifs.close(); thd_log_debug("old_preference %d new preference %d\n", old_preference, preference); return true; } int cthd_preference::get_old_preference() { std::stringstream filename; filename << TDRUNDIR << "/" << "thd_preference.conf.save"; std::ifstream ifs(filename.str().c_str(), std::ifstream::in); if (!ifs.good()) { old_preference = PREF_PERFORMANCE; } else { //ifs.read(reinterpret_cast < char * > (&preference), sizeof(preference)); ifs >> old_preference; } ifs.close(); return old_preference; } thermald-1.5/src/thd_preference.h0000664000175000017500000000271212661205366015551 0ustar kingking/* * thd_preference.h: Thermal preference class interface file * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_PREFERENCE_H #define THD_PREFERENCE_H #include "thd_common.h" #include #include #include #include #include enum { PREF_ENERGY_CONSERVE, PREF_PERFORMANCE, PREF_DISABLED }; class cthd_preference { private: int preference; int old_preference; int string_pref_to_int(std::string &pref_str); std::string int_pref_to_string(int pref); public: cthd_preference(); bool set_preference(const char *pref); std::string get_preference_str(); const char *get_preference_cstr(); int get_preference(); int get_old_preference(); void refresh(); }; #endif thermald-1.5/src/thd_kobj_uevent.cpp0000664000175000017500000000377712661205366016315 0ustar kingking/* * thd_kobj_uevent.cpp: Get notification from kobj uevent * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include "thd_kobj_uevent.h" #include "thd_common.h" int cthd_kobj_uevent::kobj_uevent_open() { memset(&nls, 0, sizeof(struct sockaddr_nl)); nls.nl_family = AF_NETLINK; nls.nl_pid = getpid(); nls.nl_groups = -1; fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT); if (fd < 0) return fd; if (bind(fd, (struct sockaddr*) &nls, sizeof(struct sockaddr_nl))) { thd_log_warn("kob_uevent bin failed \n"); close(fd); return -1; } return fd; } void cthd_kobj_uevent::kobj_uevent_close() { close(fd); } bool cthd_kobj_uevent::check_for_event() { int i = 0; int len; const char *dev_path = "DEVPATH="; unsigned int dev_path_len = strlen(dev_path); char buffer[max_buffer_size]; len = recv(fd, buffer, sizeof(buffer), MSG_DONTWAIT); while (i < len) { if (strlen(buffer + i) > dev_path_len && !strncmp(buffer + i, dev_path, dev_path_len)) { if (!strncmp(buffer + i + dev_path_len, device_path, strlen(device_path))) { return true; } } i += strlen(buffer + i) + 1; } return false; } void cthd_kobj_uevent::register_dev_path(char *path) { strncpy(device_path, path, max_buffer_size); device_path[max_buffer_size - 1] = '\0'; } thermald-1.5/src/thd_cdev_rapl_dram.cpp0000664000175000017500000000457412661205366016740 0ustar kingking/* * cthd_cdev_rapl_dram.cpp: thermal cooling class implementation * using RAPL DRAM * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #include #include "thd_cdev_rapl_dram.h" #include "thd_engine.h" int cthd_sysfs_cdev_rapl_dram::update() { DIR *dir; struct dirent *entry; std::string base = "/sys/devices/virtual/powercap/intel-rapl/intel-rapl:0/"; bool found = false; std::string path_name; dir = opendir(base.c_str()); if (!dir) return THD_ERROR; while ((entry = readdir(dir)) != NULL) { std::string temp_str; temp_str = base + entry->d_name + "/" + "name"; csys_fs name_sysfs(temp_str.c_str()); if (!name_sysfs.exists()) { continue; } std::string name; if (name_sysfs.read("", name) < 0) { continue; } thd_log_info("name = %s\n", name.c_str()); if (name == "dram") { found = true; path_name = base + entry->d_name + "/"; break; } } closedir(dir); if (!found) return THD_ERROR; cdev_sysfs.update_path(path_name); return cthd_sysfs_cdev_rapl::update(); } bool cthd_sysfs_cdev_rapl_dram::calculate_phy_max() { if (dynamic_phy_max_enable) { unsigned int curr_max_phy; curr_max_phy = thd_engine->rapl_power_meter.rapl_action_get_power(DRAM); thd_log_info("curr_phy_max = %u \n", curr_max_phy); if (curr_max_phy < rapl_min_default_step) return false; if (phy_max < curr_max_phy) { phy_max = curr_max_phy; set_inc_dec_value(phy_max * (float) rapl_power_dec_percent / 100); max_state = phy_max; max_state -= (float) max_state * rapl_low_limit_percent / 100; thd_log_info("DRAM PHY_MAX %lu, step %d, max_state %d\n", phy_max, inc_dec_val, max_state); } } return true; } thermald-1.5/src/thd_cdev_cpufreq.h0000664000175000017500000000313012661205366016074 0ustar kingking/* * thd_cdev_pstates.h: thermal cooling class interface * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_CDEV_PSTATES_H_ #define THD_CDEV_PSTATES_H_ #include #include #include "thd_cdev.h" class cthd_cdev_cpufreq: public cthd_cdev { private: int cpu_start_index; int cpu_end_index; std::vector cpufreqs; int pstate_active_freq_index; int turbo_state; std::string last_governor; int cpu_index; void add_frequency(unsigned int freq_int); public: cthd_cdev_cpufreq(unsigned int _index, int _cpu_index) : cthd_cdev(_index, "/sys/devices/system/cpu/"), cpu_start_index(0), cpu_end_index( 0), pstate_active_freq_index(0), turbo_state(0), last_governor( ""), cpu_index(_cpu_index) { } int init(); void set_curr_state(int state, int arg); int get_max_state(); int update(); }; #endif /* THD_CDEV_PSTATES_H_ */ thermald-1.5/src/thd_zone_dynamic.h0000664000175000017500000000121012661205366016102 0ustar kingking/* * thd_zone_dynamic.h * * Created on: Sep 19, 2014 * Author: spandruvada */ #ifndef THD_ZONE_DYNAMIC_H_ #define THD_ZONE_DYNAMIC_H_ #include "thd_zone.h" class cthd_zone_dynamic: public cthd_zone { private: std::string name; unsigned int trip_temp; trip_point_type_t trip_type; std::string sensor_name; std::string cdev_name; public: cthd_zone_dynamic(int index, std::string _name, unsigned int _trip_temp, trip_point_type_t _trip_type, std::string _sensor, std::string _cdev); virtual int read_trip_points(); virtual int read_cdev_trip_points(); virtual int zone_bind_sensors(); }; #endif /* THD_ZONE_DYNAMIC_H_ */ thermald-1.5/src/thd_cpu_default_binding.cpp0000664000175000017500000002327612661205366017763 0ustar kingking/* * thd_default_binding.cpp: Default binding of thermal zones * implementation file * Copyright (C) 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * Author Name * */ /* * It will search for unbounded zones (There is valid passive trips and temp * reading is available but there is no cooling driver attached to it via XML * config or default hardcoded config. * In this case if CPU is causing this temp to go up then it will use RAPL and * power clamp to cool. If it fails for three times then this zone is added * to black list, so that this method will never be tried again, * The way this file implements using existing mechanism via a two pseudo * cooling devices "gates" called start and exit. The start gate checks the * current cpu load, if yes then it opens gate by changing it to max state. * Similarly if end gate state is reached means that the RAPL and power clamp * failed to control temperature of this zone. */ #include "thd_zone_therm_sys_fs.h" #include "thd_cpu_default_binding.h" class cthd_gating_cdev: public cthd_cdev { private: class cthd_cpu_default_binding *def_bind_ref; cpu_zone_binding_t *bind_zone; int id; bool start; public: static const int max_state = 0x01; cthd_gating_cdev(int _id, cthd_cpu_default_binding *_def_bind_ref, cpu_zone_binding_t *_bind_zone, bool _start) : cthd_cdev(_id, ""), def_bind_ref(_def_bind_ref), bind_zone( _bind_zone), id(_id), start(_start) { } void set_curr_state(int state, int arg); int get_max_state(); int update(); int get_curr_state(); }; int cthd_gating_cdev::get_curr_state() { return curr_state; } void cthd_gating_cdev::set_curr_state(int state, int arg) { if (!start && state) { if (!bind_zone->zone) return; thd_log_info("CPU def binding exit for %s\n", bind_zone->zone->get_zone_type().c_str()); bind_zone->zone->zone_reset(); cpu_zone_stat_t stats; if (def_bind_ref->read_zone_stat(bind_zone->zone->get_zone_type(), &stats) == THD_SUCCESS) { ++stats.failures; def_bind_ref->update_zone_stat(bind_zone->zone->get_zone_type(), stats.failures); if (stats.failures > 3) { // This zone can't be controlled by this binding thd_log_info("CPU def binding is set to inactive for %s\n", bind_zone->zone->get_zone_type().c_str()); bind_zone->zone->set_zone_inactive(); } } else { def_bind_ref->update_zone_stat(bind_zone->zone->get_zone_type(), 0); } } else if (start && state) { if (def_bind_ref->check_cpu_load()) { thd_log_info("Turn on the gate \n"); curr_state = max_state; } else { thd_log_info("Not CPU specific increase \n"); curr_state = 0; } } else { curr_state = 0; } thd_log_info( "cthd_gating_cdev::set_curr_state[start:%d state:%d. curr_state:%d\n", start, state, curr_state); } int cthd_gating_cdev::get_max_state() { return max_state; } int cthd_gating_cdev::update() { thd_log_info("cthd_gating_cdev::update\n"); return 0; } int cthd_cpu_default_binding::read_zone_stat(std::string zone_name, cpu_zone_stat_t *stat) { std::ifstream filein; std::stringstream filename; filename << TDRUNDIR << "/" << "cpu_def_zone_bind.out"; filein.open(filename.str().c_str(), std::ios::in | std::ios::binary); if (!filein) return THD_ERROR; while (filein) { filein.read((char *) stat, sizeof(*stat)); thd_log_info("read_zone_stat name:%s f:%d\n", stat->zone_name, stat->failures); if (filein && zone_name == stat->zone_name) return THD_SUCCESS; } filein.close(); return THD_ERROR; } void cthd_cpu_default_binding::update_zone_stat(std::string zone_name, int fail_cnt) { std::ifstream filein; std::streampos current = 0; cpu_zone_stat_t obj; bool found = false; std::stringstream filename; filename << TDRUNDIR << "/" << "cpu_def_zone_bind.out"; filein.open(filename.str().c_str(), std::ios::in | std::ios::binary); if (filein.is_open()) { while (!filein.eof()) { current = filein.tellg(); filein.read((char *) &obj, sizeof(obj)); if (filein && zone_name == obj.zone_name) { found = true; break; } } } filein.close(); std::fstream fileout(filename.str().c_str(), std::ios::out | std::ios::in | std::ios::binary); if (!fileout.is_open()) { std::ofstream file; file.open(filename.str().c_str()); if (file.is_open()) { file.close(); fileout.open(filename.str().c_str(), std::ios::in | std::ios::out | std::ios::binary); } else { thd_log_info("Can't create cpu_def_zone_bind.out\n"); } } if (found) { fileout.seekp(current); } else fileout.seekp(0, std::ios::end); strncpy(obj.zone_name, zone_name.c_str(), 50); obj.failures = fail_cnt; fileout.write((char *) &obj, sizeof(obj)); fileout.close(); } bool cthd_cpu_default_binding::check_cpu_load() { unsigned int max_power; unsigned int min_power; unsigned int power; power = thd_engine->rapl_power_meter.rapl_action_get_power(PACKAGE, &max_power, &min_power); if (cpu_package_max_power != 0) max_power = cpu_package_max_power; thd_log_info("cthd_gating_cdev power :%u %u %u\n", power, min_power, max_power); if ((max_power - min_power) < def_starting_power_differential) { return false; } if (power > (max_power * 60 / 100)) { thd_log_info("Significant cpu load \n"); return true; } return false; } bool cthd_cpu_default_binding::blacklist_match(std::string name) { int i = 0; const char *blacklist_zones[] = { "cpu", "acpitz", "Surface", "pkg-temp-0", "x86_pkg_temp", "soc_dts0", "soc_dts1", "B0D4", "B0DB", "" }; while (blacklist_zones[i][0] != '\0') { if (name == blacklist_zones[i]) return true; ++i; } cpu_zone_stat_t stats; if (read_zone_stat(name, &stats) == THD_SUCCESS) { if (stats.failures > 3) { // This zone can't be controlled by this binding thd_log_info(" zone %s in blacklist\n", name.c_str()); return true; } } return false; } void cthd_cpu_default_binding::do_default_binding( std::vector &cdevs) { int count = 0; int id = 0x1000; cthd_cdev *cdev_rapl; cthd_cdev *cdev_powerclamp; cdev_rapl = thd_engine->search_cdev("rapl_controller"); cdev_powerclamp = thd_engine->search_cdev("intel_powerclamp"); if (!cdev_rapl && !cdev_powerclamp) { thd_log_info( "cthd_cpu_default_binding::do_default_binding: No relavent cpu cdevs\n"); return; } for (unsigned int i = 0; i < thd_engine->get_zone_count(); ++i) { cthd_zone *zone = thd_engine->get_zone(i); if (blacklist_match(zone->get_zone_type())) { continue; } if (!zone->zone_cdev_binded()) { cpu_zone_binding_t *cdev_binding_info; cdev_binding_info = new cpu_zone_binding_t; cdev_binding_info->zone_name = zone->get_zone_type(); cdev_binding_info->zone = zone; cdev_binding_info->cdev_gate_entry = new cthd_gating_cdev(id++, this, cdev_binding_info, true); if (cdev_binding_info->cdev_gate_entry) { cdev_binding_info->cdev_gate_entry->set_cdev_type( cdev_binding_info->zone_name + "_" + "cpu_gate_entry"); } else { thd_log_info("do_default_binding failed \n"); cdev_binding_info->cdev_gate_entry = NULL; delete cdev_binding_info; continue; } cdev_binding_info->cdev_gate_exit = new cthd_gating_cdev(id++, this, cdev_binding_info, false); if (cdev_binding_info->cdev_gate_exit) { cdev_binding_info->cdev_gate_exit->set_cdev_type( cdev_binding_info->zone_name + "_" + "cpu_gate_exit"); } else { thd_log_info("do_default_binding failed \n"); delete cdev_binding_info->cdev_gate_entry; cdev_binding_info->cdev_gate_entry = NULL; delete cdev_binding_info; return; } thd_log_info("unbound zone %s\n", zone->get_zone_type().c_str()); int status = zone->bind_cooling_device(PASSIVE, 0, cdev_binding_info->cdev_gate_entry, 0, def_gating_cdev_sampling_period); if (status == THD_ERROR) { thd_log_info("unbound zone: Bind attempt failed\n"); delete cdev_binding_info->cdev_gate_exit; cdev_binding_info->cdev_gate_exit = NULL; delete cdev_binding_info->cdev_gate_entry; cdev_binding_info->cdev_gate_entry = NULL; delete cdev_binding_info; continue; } if (cdev_rapl) { zone->bind_cooling_device(PASSIVE, 0, cdev_rapl, 20); } if (cdev_powerclamp) { zone->bind_cooling_device(PASSIVE, 0, cdev_powerclamp, 20); } status = zone->bind_cooling_device(PASSIVE, 0, cdev_binding_info->cdev_gate_exit, 0, def_gating_cdev_sampling_period); if (status == THD_ERROR) { thd_log_info("unbound zone: Bind attempt failed\n"); delete cdev_binding_info->cdev_gate_exit; cdev_binding_info->cdev_gate_exit = NULL; delete cdev_binding_info->cdev_gate_entry; cdev_binding_info->cdev_gate_entry = NULL; delete cdev_binding_info; continue; } thd_log_info("unbound zone %s\n", zone->get_zone_type().c_str()); count++; zone->set_zone_active(); cdev_list.push_back(cdev_binding_info); } } if (count) { thd_engine->rapl_power_meter.rapl_start_measure_power(); cpu_package_max_power = thd_engine->rapl_power_meter.rapl_action_get_max_power(PACKAGE); thd_log_info("do_default_binding max power CPU package :%u\n", cpu_package_max_power); } } thermald-1.5/src/thd_sensor.h0000664000175000017500000000446712661205366014755 0ustar kingking/* * thd_sensor.h: thermal sensor class interface * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name * */ #ifndef THD_SENSOR_H_ #define THD_SENSOR_H_ #include #include "thd_common.h" #include "thd_sys_fs.h" #define SENSOR_TYPE_THERMAL_SYSFS 0 #define SENSOR_TYPE_RAW 1 class cthd_sensor { protected: int index; int type; csys_fs sensor_sysfs; bool sensor_active; std::string type_str; bool async_capable; bool virtual_sensor; private: std::vector thresholds; void enable_uevent(); public: cthd_sensor(int _index, std::string control_path, std::string _type_str, int _type = SENSOR_TYPE_THERMAL_SYSFS); virtual ~cthd_sensor() { } int sensor_update(); virtual std::string get_sensor_type() { return type_str; } virtual std::string get_sensor_path() { return sensor_sysfs.get_base_path(); } virtual unsigned int read_temperature(); int get_index() { return index; } int set_threshold(int index, int temp); ; void update_path(std::string str) { sensor_sysfs.update_path(str); } void set_async_capable(bool capable) { async_capable = capable; } bool check_async_capable() { return async_capable; } virtual void sensor_dump() { thd_log_info("sensor index:%d %s %s Async:%d \n", index, type_str.c_str(), sensor_sysfs.get_base_path(), async_capable); } // Even if sensors are capable of async, it is possible that it is not reliable enough // at critical monitoring point. Sensors can be forced to go to poll mode at that temp void sensor_poll_trip(bool status); bool is_virtual() { return virtual_sensor; } }; #endif /* THD_SENSOR_H_ */ thermald-1.5/Android.mk0000664000175000017500000000404112661205366013542 0ustar kingkingLOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) thermald_src_path := ./src thermald_src_files := \ $(thermald_src_path)/android_main.cpp \ $(thermald_src_path)/thd_engine.cpp \ $(thermald_src_path)/thd_cdev.cpp \ $(thermald_src_path)/thd_cdev_therm_sys_fs.cpp \ $(thermald_src_path)/thd_engine_default.cpp \ $(thermald_src_path)/thd_sys_fs.cpp \ $(thermald_src_path)/thd_trip_point.cpp \ $(thermald_src_path)/thd_zone.cpp \ $(thermald_src_path)/thd_zone_surface.cpp \ $(thermald_src_path)/thd_zone_cpu.cpp \ $(thermald_src_path)/thd_zone_therm_sys_fs.cpp \ $(thermald_src_path)/thd_preference.cpp \ $(thermald_src_path)/thd_model.cpp \ $(thermald_src_path)/thd_parse.cpp \ $(thermald_src_path)/thd_sensor.cpp \ $(thermald_src_path)/thd_sensor_virtual.cpp \ $(thermald_src_path)/thd_kobj_uevent.cpp \ $(thermald_src_path)/thd_cdev_order_parser.cpp \ $(thermald_src_path)/thd_cdev_gen_sysfs.cpp \ $(thermald_src_path)/thd_pid.cpp \ $(thermald_src_path)/thd_zone_generic.cpp \ $(thermald_src_path)/thd_cdev_cpufreq.cpp \ $(thermald_src_path)/thd_cdev_rapl.cpp \ $(thermald_src_path)/thd_cdev_intel_pstate_driver.cpp \ $(thermald_src_path)/thd_msr.cpp \ $(thermald_src_path)/thd_rapl_interface.cpp \ $(thermald_src_path)/thd_cdev_msr_rapl.cpp \ $(thermald_src_path)/thd_rapl_power_meter.cpp \ $(thermald_src_path)/thd_trt_art_reader.cpp \ $(thermald_src_path)/thd_cdev_rapl_dram.cpp \ $(thermald_src_path)/thd_cpu_default_binding.cpp \ $(thermald_src_path)/thd_cdev_backlight.cpp LOCAL_C_INCLUDES += $(LOCAL_PATH) $(thermald_src_path) \ external/icu4c/common \ external/libxml2/include \ system/core/include/ LOCAL_MODULE_TAGS := optional LOCAL_CFLAGS := -fpermissive -DTDRUNDIR='"/data/thermal-daemon"' -DTDCONFDIR='"/system/etc/thermal-daemon"' LOCAL_STATIC_LIBRARIES := libxml2 LOCAL_SHARED_LIBRARIES := liblog libcutils libdl libc++ libicuuc libicui18n libbinder libutils LOCAL_PRELINK_MODULE := false LOCAL_SRC_FILES := $(thermald_src_files) LOCAL_MODULE := thermal-daemon include $(BUILD_EXECUTABLE) thermald-1.5/tools/0000775000175000017500000000000012661205366012772 5ustar kingkingthermald-1.5/tools/thermald_set_pref.sh0000775000175000017500000001103112661205366017014 0ustar kingking#!/bin/sh echo "****thermald preference****" echo "0 : DEFAULT" echo "1 : PERFORMANCE" echo "2 : ENERGY_CONSERVE" echo "3 : DISABLED" echo "4 : CALIBRATE" echo "5 : SET USER DEFINED CPU MAX temp" echo "6 : SET USER DEFINED CPU PASSIVE temp" echo "7 : TERMINATE" echo "8 : REINIT" echo "A : Add sensor test" echo "B : Get Sensor Information" echo "C : Add zone test" echo "D : Set zone test" echo "E : Get zone test" echo "F : Delete zone test" echo "G : Add cdev test" echo "H : Get Sensor Count" echo "I : Get Zone Count" echo "J : Get Zone Information" echo "K : Get Zone Sensor Information" echo "L : Get Zone Trip Information" echo "M : Get cdev count" echo "N : Get cdev Information" arg="0" if [[ "$1" != "" ]]; then if [[ "$2" != "" ]]; then arg=$2 fi opt_no=$1 echo "Taking command line argument as choice!" else echo -n " Enter thermald preference [1..6]: " read opt_no fi case $opt_no in 0) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.SetCurrentPreference string:"FALLBACK" ;; 1) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.SetCurrentPreference string:"PERFORMANCE" ;; 2) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.SetCurrentPreference string:"ENERGY_CONSERVE" ;; 3) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.SetCurrentPreference string:"DISABLE" ;; 4) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.Calibrate ;; 5) echo -n " Enter valid max temp in mill degree celsius " read max_temp dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.SetUserMaxTemperature string:cpu uint32:$max_temp ;; 6) echo -n " Enter valid passive temp in mill degree celsius " read psv_temp dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.SetUserPassiveTemperature string:cpu uint32:$psv_temp ;; 7) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.Terminate ;; 8) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.Reinit ;; A) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.AddSensor string:"TEST_ADD_SENSOR" string:"/sys/class/thermal/thermal_zone0/temp" ;; B) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetSensorInformation uint32:0 ;; C) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.AddZonePassive string:"TEST_ADD_ZONE" uint32:90000 string:"hwmon" string:"intel_pstate" ;; D) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.SetZoneStatus string:"TEST_ADD_ZONE" int32:0 ;; E) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetZoneStatus string:"TEST_ADD_ZONE" ;; F) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.DeleteZone string:"TEST_ADD_ZONE" ;; G) dbus-send --system --dest=org.freedesktop.thermald /org/freedesktop/thermald org.freedesktop.thermald.AddCoolingDevice string:"TEST_CDEV" string:"/sys/class/thermal/cooling_device0/cur_state" int32:0 int32:1 int32:1 ;; H) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetSensorCount ;; I) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetZoneCount ;; J) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetZoneInformation uint32:0 ;; K) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetZoneSensorAtIndex uint32:0 uint32:$arg ;; L) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetZoneTripAtIndex uint32:0 uint32:$arg ;; M) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetCdevCount ;; N) dbus-send --system --dest=org.freedesktop.thermald --print-reply /org/freedesktop/thermald org.freedesktop.thermald.GetCdevInformation uint32:$arg ;; *) echo "Invalid option" esac thermald-1.5/tools/thermal_monitor/0000775000175000017500000000000012661205366016175 5ustar kingkingthermald-1.5/tools/thermal_monitor/sensorsdialog.cpp0000664000175000017500000001765312661205366021571 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #include "sensorsdialog.h" #include "ui_sensorsdialog.h" #include #include SensorsDialog::SensorsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SensorsDialog) { ui->setupUi(this); } SensorsDialog::~SensorsDialog() { delete ui; } void SensorsDialog::disableCheckbox(int index) { QCheckBox *cb = getCheckboxPtr(index); if (cb != NULL) { cb->setText(""); cb->setEnabled(false); cb->setVisible(false); } } void SensorsDialog::setupCheckbox(int index, QString name, bool checked) { QCheckBox *cb = getCheckboxPtr(index); if (cb != NULL) { cb->setText(name); cb->setChecked(checked); } } QCheckBox* SensorsDialog::getCheckboxPtr(int index) { if (index >= 0 && index < MAX_NUMBER_SENSOR_VISIBILITY_CHECKBOXES) { switch(index){ case 0: return ui->checkBox; break; case 1: return ui->checkBox_2; break; case 2: return ui->checkBox_3; break; case 3: return ui->checkBox_4; break; case 4: return ui->checkBox_5; break; case 5: return ui->checkBox_6; break; case 6: return ui->checkBox_7; break; case 7: return ui->checkBox_8; break; case 8: return ui->checkBox_9; break; case 9: return ui->checkBox_10; break; case 10: return ui->checkBox_11; break; case 11: return ui->checkBox_12; break; case 12: return ui->checkBox_13; break; case 13: return ui->checkBox_14; break; case 14: return ui->checkBox_15; break; case 15: return ui->checkBox_16; break; case 16: return ui->checkBox_17; break; case 17: return ui->checkBox_18; break; case 18: return ui->checkBox_19; break; case 19: return ui->checkBox_20; break; } } else { qDebug() << "index" << index << "out of range, SensorsDialog::getCheckboxPtr"; } return NULL; } void SensorsDialog::on_checkBox_toggled(bool checked) { if (checked) { emit setGraphVisibility(0, true); } else { emit setGraphVisibility(0, false); } } void SensorsDialog::on_checkBox_2_toggled(bool checked) { if (checked) { emit setGraphVisibility(1, true); } else { emit setGraphVisibility(1, false); } } void SensorsDialog::on_checkBox_3_toggled(bool checked) { if (checked) { emit setGraphVisibility(2, true); } else { emit setGraphVisibility(2, false); } } void SensorsDialog::on_checkBox_4_toggled(bool checked) { if (checked) { emit setGraphVisibility(3, true); } else { emit setGraphVisibility(3, false); } } void SensorsDialog::on_checkBox_5_toggled(bool checked) { if (checked) { emit setGraphVisibility(4, true); } else { emit setGraphVisibility(4, false); } } void SensorsDialog::on_checkBox_6_toggled(bool checked) { if (checked) { emit setGraphVisibility(5, true); } else { emit setGraphVisibility(5, false); } } void SensorsDialog::on_checkBox_7_toggled(bool checked) { if (checked) { emit setGraphVisibility(6, true); } else { emit setGraphVisibility(6, false); } } void SensorsDialog::on_checkBox_8_toggled(bool checked) { if (checked) { emit setGraphVisibility(7, true); } else { emit setGraphVisibility(7, false); } } void SensorsDialog::on_checkBox_9_toggled(bool checked) { if (checked) { emit setGraphVisibility(8, true); } else { emit setGraphVisibility(8, false); } } void SensorsDialog::on_checkBox_10_toggled(bool checked) { if (checked) { emit setGraphVisibility(9, true); } else { emit setGraphVisibility(9, false); } } void SensorsDialog::on_checkBox_11_toggled(bool checked) { if (checked) { emit setGraphVisibility(10, true); } else { emit setGraphVisibility(10, false); } } void SensorsDialog::on_checkBox_12_toggled(bool checked) { if (checked) { emit setGraphVisibility(11, true); } else { emit setGraphVisibility(11, false); } } void SensorsDialog::on_checkBox_13_toggled(bool checked) { if (checked) { emit setGraphVisibility(12, true); } else { emit setGraphVisibility(12, false); } } void SensorsDialog::on_checkBox_14_toggled(bool checked) { if (checked) { emit setGraphVisibility(13, true); } else { emit setGraphVisibility(13, false); } } void SensorsDialog::on_checkBox_15_toggled(bool checked) { if (checked) { emit setGraphVisibility(14, true); } else { emit setGraphVisibility(14, false); } } void SensorsDialog::on_checkBox_16_toggled(bool checked) { if (checked) { emit setGraphVisibility(15, true); } else { emit setGraphVisibility(15, false); } } void SensorsDialog::on_checkBox_17_toggled(bool checked) { if (checked) { emit setGraphVisibility(16, true); } else { emit setGraphVisibility(16, false); } } void SensorsDialog::on_checkBox_18_toggled(bool checked) { if (checked) { emit setGraphVisibility(17, true); } else { emit setGraphVisibility(17, false); } } void SensorsDialog::on_checkBox_19_toggled(bool checked) { if (checked) { emit setGraphVisibility(18, true); } else { emit setGraphVisibility(18, false); } } void SensorsDialog::on_checkBox_20_toggled(bool checked) { if (checked) { emit setGraphVisibility(19, true); } else { emit setGraphVisibility(19, false); } } void SensorsDialog::on_setAllButton_clicked() { ui->checkBox->setChecked(true); ui->checkBox_2->setChecked(true); ui->checkBox_3->setChecked(true); ui->checkBox_4->setChecked(true); ui->checkBox_5->setChecked(true); ui->checkBox_6->setChecked(true); ui->checkBox_7->setChecked(true); ui->checkBox_8->setChecked(true); ui->checkBox_9->setChecked(true); ui->checkBox_10->setChecked(true); ui->checkBox_11->setChecked(true); ui->checkBox_12->setChecked(true); ui->checkBox_13->setChecked(true); ui->checkBox_14->setChecked(true); ui->checkBox_15->setChecked(true); ui->checkBox_16->setChecked(true); ui->checkBox_17->setChecked(true); ui->checkBox_18->setChecked(true); ui->checkBox_19->setChecked(true); ui->checkBox_20->setChecked(true); } void SensorsDialog::on_clearAllButton_clicked() { ui->checkBox->setChecked(false); ui->checkBox_2->setChecked(false); ui->checkBox_3->setChecked(false); ui->checkBox_4->setChecked(false); ui->checkBox_5->setChecked(false); ui->checkBox_6->setChecked(false); ui->checkBox_7->setChecked(false); ui->checkBox_8->setChecked(false); ui->checkBox_9->setChecked(false); ui->checkBox_10->setChecked(false); ui->checkBox_11->setChecked(false); ui->checkBox_12->setChecked(false); ui->checkBox_13->setChecked(false); ui->checkBox_14->setChecked(false); ui->checkBox_15->setChecked(false); ui->checkBox_16->setChecked(false); ui->checkBox_17->setChecked(false); ui->checkBox_18->setChecked(false); ui->checkBox_19->setChecked(false); ui->checkBox_20->setChecked(false); } thermald-1.5/tools/thermal_monitor/mainwindow.ui0000664000175000017500000000542012661205366020711 0ustar kingking MainWindow 0 0 400 300 Thermal Monitor 0 35 530 341 0 0 400 26 &Settings TopToolBarArea false &Clear Settings and Exit Set &Polling Interval &Sensors &Log &About E&xit Ctrl+Q &Trips QCustomPlot QWidget
qcustomplot/qcustomplot.h
1
thermald-1.5/tools/thermal_monitor/mainwindow.cpp0000664000175000017500000004356512661205366021072 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "pollingdialog.h" #include "sensorsdialog.h" #include "logdialog.h" #include "tripsdialog.h" #define DEFAULT_SCREEN_POS_DIVISOR 4 #define DEFAULT_SCREEN_SIZE_DIVISOR 2 #define DEFAULT_SCREEN_ASPECT_RATIO_NUM 3 #define DEFAULT_SCREEN_ASPECT_RATIO_DEN 4 #define DEFAULT_TEMP_POLL_INTERVAL_MS 4000 #define SAMPLE_STORE_SIZE 100 #define DEFAULT_LOGFILE_NAME "log.txt" #define CUSTOMPLOT_YAXIS_RANGE 120 #define VERSION_NUMBER "1.1" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), temp_samples(SAMPLE_STORE_SIZE), currentTempsensorIndex(0), temp_poll_interval(DEFAULT_TEMP_POLL_INTERVAL_MS), logging_enabled(false), log_visible_only(false) { int ret; ret = thermaldInterface.initialize(); if (ret < 0) { sensor_visibility = NULL; sensor_temp = NULL; window = NULL; layout = NULL; QMessageBox msgBox; QString str; str = QString("Can't establish link with thermal daemon." " Make sure that thermal daemon started with --dbus-enable option.\n"); msgBox.setText(str); msgBox.setStandardButtons(QMessageBox::Abort); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Abort: // Abort was clicked abort(); break; default: // should never be reached qFatal("main: unexpected button result"); break; } delete ui; return; } // Build up a color vector for holding a good variety colors.append(Qt::red); colors.append(Qt::green); colors.append(Qt::blue); colors.append(Qt::cyan); colors.append(Qt::magenta); colors.append(Qt::yellow); colors.append(Qt::black); colors.append(QColor(200,200,00)); colors.append(QColor(220,20,60)); colors.append(QColor(255,20,147)); colors.append(QColor(145,44,238)); colors.append(QColor(0,255,127)); colors.append(QColor(127,255,0)); colors.append(QColor(255,215,0)); colors.append(QColor(255,193,37)); colors.append(QColor(255,153,18)); colors.append(QColor(255,69,0)); colors.append(Qt::gray); ui->setupUi(this); resoreSettings(); for (int i = 0; i < SAMPLE_STORE_SIZE; ++i) { temp_samples[i] = i; } displayTemperature(ui->customPlot); window = new QWidget; layout = new QVBoxLayout; layout->addWidget(ui->customPlot, 90); // 90% to this widget, 10% to tab widget window->setLayout(layout); setCentralWidget(window); } MainWindow::~MainWindow() { if (logging_enabled){ logging_file.close(); } delete[] sensor_visibility; delete[] sensor_temp; delete window; delete layout; delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { storeSettings(); event->accept(); } void MainWindow::displayTemperature(QCustomPlot *customPlot) { QPen pen; int temp; // give the axes some labels: customPlot->xAxis->setLabel("Samples"); customPlot->yAxis->setLabel("Temperature (°C)"); // set axes ranges, so we see all data: customPlot->xAxis->setRange(0, SAMPLE_STORE_SIZE); customPlot->yAxis->setRange(0, CUSTOMPLOT_YAXIS_RANGE); customPlot->legend->setVisible(true); pen.setWidth(1); currentTempsensorIndex = 0; for (uint zone = 0; zone < thermaldInterface.getZoneCount(); zone++) { zoneInformationType *zone_info = thermaldInterface.getZone(zone); if (!zone_info) continue; pen.setColor(colors[zone % colors.count()]); int sensor_cnt_per_zone = thermaldInterface.getSensorCountForZone(zone); if (sensor_cnt_per_zone <= 0) break; pen.setStyle(Qt::SolidLine); for (int cnt = 0; cnt < sensor_cnt_per_zone; cnt++) { QString sensor_type; QString sensor_name; sensorZoneInformationType sensor_info; if (thermaldInterface.getSensorTypeForZone(zone, cnt, sensor_type) < 0) continue; sensor_name.append(zone_info->name); sensor_name.append(":"); sensor_name.append(sensor_type); ui->customPlot->addGraph(); ui->customPlot->graph(currentTempsensorIndex)->setName(sensor_name); ui->customPlot->graph(currentTempsensorIndex)->setPen(pen); current_sample_index[currentTempsensorIndex] = 0; sensor_info.index = thermaldInterface.getSensorIndex(sensor_type); sensor_info.display_name = sensor_name; sensor_info.sensor_name = sensor_type; sensor_info.zone = zone; sensor_types.append(sensor_info); currentTempsensorIndex++; } pen.setStyle(Qt::DashLine); // Draw a dashed horz line for each min valid trip temperature QVector these_trips; uint trip_count = thermaldInterface.getTripCountForZone(zone); if (trip_count > 0) { for (uint trip = 0; trip < trip_count; trip++){ QCPItemLine *line = new QCPItemLine(customPlot); customPlot->addItem(line); temp = thermaldInterface.getTripTempForZone(zone, trip); line->start->setCoords(0, temp); line->end->setCoords(SAMPLE_STORE_SIZE - 1, temp); line->setPen(pen); if (temp == thermaldInterface.getLowestValidTripTempForZone(zone)) { line->setVisible(true); thermaldInterface.setTripVisibility(zone, trip, true); } else { line->setVisible(false); thermaldInterface.setTripVisibility(zone, trip, false); } these_trips.append(line); } trips.append(these_trips); } } // Now display sensors which are not part of any zone. Users can use this and assign to some zone for (uint i = 0; i < thermaldInterface.getSensorCount(); ++i) { sensorInformationType info; QString name; bool found = false; name = thermaldInterface.getSensorName(i); if (!name.isEmpty()){ // search if this is already registered as part of a zone sensor for (int j = 0; j < sensor_types.count(); ++j) { sensorZoneInformationType sensor_info = sensor_types[j]; if (name == sensor_info.sensor_name) { found = true; break; } } if (!found) { sensorZoneInformationType sensor_info; QString sensor_name; sensor_name.append("UKWN:"); sensor_name.append(name); ui->customPlot->addGraph(); ui->customPlot->graph(currentTempsensorIndex)->setName(sensor_name); ui->customPlot->graph(currentTempsensorIndex)->setPen(pen); current_sample_index[currentTempsensorIndex] = 0; sensor_info.index = thermaldInterface.getSensorIndex(name); sensor_info.display_name = sensor_name; sensor_info.sensor_name = name; sensor_info.zone = -1; sensor_types.append(sensor_info); currentTempsensorIndex++; } } } sensor_visibility = new bool[sensor_types.count()]; sensor_temp = new QLabel[sensor_types.count()]; connect(&tempUpdateTimer, SIGNAL(timeout()), this, SLOT(updateTemperatureDataSlot())); tempUpdateTimer.start(temp_poll_interval); } void MainWindow::updateTemperatureDataSlot() { for (int i = 0; i < sensor_types.count(); ++i) { int temperature = thermaldInterface.getSensorTemperature(sensor_types[i].index); sensor_temp[i].setNum(temperature/1000); addNewTemperatureTemperatureSample(i, (double)temperature/1000.0); } if(logging_enabled) { outStreamLogging << endl; } ui->customPlot->replot(); // Show any active cooling devices on the status bar QString str; for (uint i = 0; i < thermaldInterface.getCoolingDeviceCount(); i++) { int current = thermaldInterface.getCoolingDeviceCurrentState(i); int min = thermaldInterface.getCoolingDeviceMinState(i); if (current > min){ if (str.isEmpty()){ str += "Cooling: "; } else { str += ", "; } str += QString("%2%3 (%4/%5)") .arg(thermaldInterface.getCoolingDeviceName(i)) .arg(i) .arg(current) .arg(thermaldInterface.getCoolingDeviceMaxState(i)); } } ui->statusBar->showMessage(str); } int MainWindow::addNewTemperatureTemperatureSample(int index, double temperature) { if (temperature_samples[index].size() >= SAMPLE_STORE_SIZE) { int i; for (i = 0; i < temperature_samples[index].count() - 1; i++){ temperature_samples[index][i] = temperature_samples[index][i + 1]; } temperature_samples[index][i] = temperature; } else { temperature_samples[index].push_back(temperature); current_sample_index[index]++; } ui->customPlot->graph(index)->setData(temp_samples, temperature_samples[index]); if (logging_enabled) { if (ui->customPlot->graph(index)->visible() || !log_visible_only){ outStreamLogging << temperature << ", "; } } return 0; } void MainWindow::resoreSettings() { QSettings settings; // restore the previous window geometry, if available if (settings.contains("mainWindowGeometry/size")) { resize(settings.value("mainWindowGeometry/size").toSize()); move(settings.value("mainWindowGeometry/pos").toPoint()); } else { // otherwise start with the default geometry calculated from the desktop size QDesktopWidget desktop; QRect screen = desktop.screenGeometry(); int width, height, x, y; width = screen.width() / DEFAULT_SCREEN_SIZE_DIVISOR; height = ((screen.width() / DEFAULT_SCREEN_SIZE_DIVISOR) * DEFAULT_SCREEN_ASPECT_RATIO_NUM) / DEFAULT_SCREEN_ASPECT_RATIO_DEN; x = screen.width() / DEFAULT_SCREEN_POS_DIVISOR; y = screen.height() / DEFAULT_SCREEN_POS_DIVISOR; resize(width, height); move(x, y); } // restore the previous window state, if available if (settings.contains("mainWindowState")) { restoreState(settings.value("mainWindowState").toByteArray()); } // restore the polling interval, if available if (settings.contains("updateInterval")) { temp_poll_interval = settings.value("updateInterval").toUInt(); } else { // otherwise load the default temp_poll_interval = DEFAULT_TEMP_POLL_INTERVAL_MS; } // restore the log file name, if available if (settings.contains("logFilename") && !settings.value("logFilename").toString().isEmpty()) { log_filename = settings.value("logFilename").toString(); } else { // otherwise load the default log_filename = QString(DEFAULT_LOGFILE_NAME); } // restore the log visible only setting, if available if (settings.contains("logVisibleOnly")) { log_visible_only = settings.value("logVisibleOnly").toBool(); } else { // otherwise load the default log_visible_only = false; } // start out with logging disabled logging_enabled = false; } void MainWindow::storeSettings() { QSettings settings; settings.setValue("mainWindowGeometry/size", size()); settings.setValue("mainWindowGeometry/pos", pos()); settings.setValue("mainWindowState", saveState()); settings.setValue("updateInterval", temp_poll_interval); if (!log_filename.isEmpty()) { settings.setValue("logFilename", log_filename); } else { // restore default log file name from empty string name settings.setValue("logFilename", QString(DEFAULT_LOGFILE_NAME)); } settings.setValue("logVisibleOnly", log_visible_only); } void MainWindow::changePollIntervalSlot(uint new_val) { temp_poll_interval = new_val; tempUpdateTimer.start(temp_poll_interval); } void MainWindow::changeGraphVisibilitySlot(uint index, bool visible) { if (index < (uint) sensor_types.count()) { ui->customPlot->graph(index)->setVisible(visible); sensor_visibility[index] = visible; if (index < (uint)sensor_types.count()) { sensorZoneInformationType sensor_info = sensor_types[index]; if (sensor_info.zone >= 0) setTripVisibility(sensor_info.zone, 0, visible); } } } void MainWindow::changeLogVariables(bool log_enabled, bool log_vis_only, QString log_file_name) { if (log_enabled && log_file_name.isEmpty()) { QMessageBox msgBox(this); msgBox.setText("Please enter a valid filename.\r\rLogging not enabled"); msgBox.exec(); return; } /* if logging has just been turned on, open the file to write, * then output the sensor name header */ if (!logging_enabled && log_enabled) { // first set the file and output stream logging_file.setFileName(log_file_name); QTextStream out(&logging_file); if (!logging_file.open(QIODevice::WriteOnly | QIODevice::Text)) { qCritical() << "Cannot open file for writing: " << qPrintable(logging_file.errorString()) << endl; return; } outStreamLogging.setDevice(&logging_file); // now output the temperature sensor names as a header for(int i = 0; i < sensor_types.count(); i++) { if (!log_vis_only || ui->customPlot->graph(i)->visible()) { outStreamLogging << ui->customPlot->graph(i)->name() << ", "; } } outStreamLogging << endl; } // logging has been turned off, so close the file if (logging_enabled && !log_enabled){ logging_file.close(); } // copy the flags and filename to this logging_enabled = log_enabled; log_visible_only = log_vis_only; log_filename = log_file_name; } void MainWindow::currentChangedSlot(int index) { if (index) { ui->customPlot->setVisible(false); } else { ui->customPlot->setVisible(true); } } void MainWindow::setTripSetpoint(uint zone, uint trip, int temperature) { trips[zone][trip]->start->setCoords(0, temperature); trips[zone][trip]->end->setCoords(SAMPLE_STORE_SIZE - 1, temperature); thermaldInterface.setTripTempForZone(zone, trip, temperature); } void MainWindow::setTripVisibility(uint zone, uint trip, bool visibility) { thermaldInterface.setTripVisibility(zone, trip, visibility); trips[zone][trip]->setVisible(visibility); } void MainWindow::on_actionClear_triggered() { QSettings settings; settings.clear(); QCoreApplication::quit(); } void MainWindow::on_actionSet_Polling_Interval_triggered() { PollingDialog *p = new PollingDialog(this, temp_poll_interval); QObject::connect(p, SIGNAL(setPollInterval(uint)), this, SLOT(changePollIntervalSlot(uint))); p->show(); // non-modal } void MainWindow::on_actionSensors_triggered() { SensorsDialog *s = new SensorsDialog(this); QObject::connect(s, SIGNAL(setGraphVisibility(uint, bool)), this, SLOT(changeGraphVisibilitySlot(uint, bool))); // set the checkbox names to match the temperature sensor names for (int i = 0; i < MAX_NUMBER_SENSOR_VISIBILITY_CHECKBOXES; i++) { sensorZoneInformationType sensor_info; if (i < sensor_types.count()) { sensor_info = sensor_types[i]; s->setupCheckbox(i, sensor_info.display_name, sensor_visibility[i]); } else { s->disableCheckbox(i); } } // future project: create checkboxes via code, not .ui s->show(); } void MainWindow::on_actionLog_triggered() { LogDialog *l = new LogDialog(this); QObject::connect(l, SIGNAL(setLogVariable(bool, bool, QString)), this, SLOT(changeLogVariables(bool, bool, QString))); l->setLoggingState(logging_enabled, log_visible_only, log_filename); l->show(); } void MainWindow::on_action_About_triggered() { QMessageBox msgBox; QString str; str = QString("

Thermal Monitor

" "Version %1

" "GUI for Linux thermal daemon (thermald)

" "Copyright (c) 2015, Intel Corporation

") .arg(QString(VERSION_NUMBER)); msgBox.setText(str); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setWindowTitle(QString("About Thermal Monitor")); msgBox.exec(); } void MainWindow::on_actionE_xit_triggered() { close(); } void MainWindow::on_action_Trips_triggered() { tripsDialog *t = new tripsDialog(this, &thermaldInterface); QObject::connect(t, SIGNAL(setTripVis(uint, uint, bool)), this, SLOT(setTripVisibility(uint, uint, bool))); QObject::connect(t, SIGNAL(changeTripSetpoint(uint, uint, int)), this, SLOT(setTripSetpoint(uint, uint, int))); for(uint i = 0; i < thermaldInterface.getZoneCount(); i++) { t->addZone(thermaldInterface.getZone(i)); } t->show(); } thermald-1.5/tools/thermal_monitor/qcustomplot/0000775000175000017500000000000012661205366020567 5ustar kingkingthermald-1.5/tools/thermal_monitor/qcustomplot/qcustomplot.h0000664000175000017500000044336212661205366023346 0ustar kingking/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2015 Emanuel Eichhammer ** ** ** ** 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 http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 25.04.15 ** ** Version: 1.3.1 ** ****************************************************************************/ #ifndef QCUSTOMPLOT_H #define QCUSTOMPLOT_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) # include # include # include #else # include # include #endif class QCPPainter; class QCustomPlot; class QCPLayerable; class QCPLayoutElement; class QCPLayout; class QCPAxis; class QCPAxisRect; class QCPAxisPainterPrivate; class QCPAbstractPlottable; class QCPGraph; class QCPAbstractItem; class QCPItemPosition; class QCPLayer; class QCPPlotTitle; class QCPLegend; class QCPAbstractLegendItem; class QCPColorMap; class QCPColorScale; class QCPBars; /*! \file */ // decl definitions for shared library compilation/usage: #if defined(QCUSTOMPLOT_COMPILE_LIBRARY) # define QCP_LIB_DECL Q_DECL_EXPORT #elif defined(QCUSTOMPLOT_USE_LIBRARY) # define QCP_LIB_DECL Q_DECL_IMPORT #else # define QCP_LIB_DECL #endif /*! The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library */ namespace QCP { /*! Defines the sides of a rectangular entity to which margins can be applied. \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins */ enum MarginSide { msLeft = 0x01 ///< 0x01 left margin ,msRight = 0x02 ///< 0x02 right margin ,msTop = 0x04 ///< 0x04 top margin ,msBottom = 0x08 ///< 0x08 bottom margin ,msAll = 0xFF ///< 0xFF all margins ,msNone = 0x00 ///< 0x00 no margin }; Q_DECLARE_FLAGS(MarginSides, MarginSide) /*! Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective element how it is drawn. Typically it provides a \a setAntialiased function for this. \c AntialiasedElements is a flag of or-combined elements of this enum type. \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks ,aeGrid = 0x0002 ///< 0x0002 Grid lines ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines ,aeLegend = 0x0008 ///< 0x0008 Legend box ,aeLegendItems = 0x0010 ///< 0x0010 Legend items ,aePlottables = 0x0020 ///< 0x0020 Main lines of plottables (excluding error bars, see element \ref aeErrorBars) ,aeItems = 0x0040 ///< 0x0040 Main lines of items ,aeScatters = 0x0080 ///< 0x0080 Scatter symbols of plottables (excluding scatter symbols of type ssPixmap) ,aeErrorBars = 0x0100 ///< 0x0100 Error bars ,aeFills = 0x0200 ///< 0x0200 Borders of fills (e.g. under or between graphs) ,aeZeroLine = 0x0400 ///< 0x0400 Zero-lines, see \ref QCPGrid::setZeroLinePen ,aeAll = 0xFFFF ///< 0xFFFF All elements ,aeNone = 0x0000 ///< 0x0000 No elements }; Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) /*! Defines plotting hints that control various aspects of the quality and speed of plotting. \see QCustomPlot::setPlottingHints */ enum PlottingHint { phNone = 0x000 ///< 0x000 No hints are set ,phFastPolylines = 0x001 ///< 0x001 Graph/Curve lines are drawn with a faster method. This reduces the quality ///< especially of the line segment joins. (Only relevant for solid line pens.) ,phForceRepaint = 0x002 ///< 0x002 causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpHint. ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). ,phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as pixmaps, increasing replot performance. }; Q_DECLARE_FLAGS(PlottingHints, PlottingHint) /*! Defines the mouse interactions possible with QCustomPlot. \c Interactions is a flag of or-combined elements of this enum type. \see QCustomPlot::setInteractions */ enum Interaction { iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) ,iSelectAxes = 0x010 ///< 0x010 Axes are selectable (or parts of them, see QCPAxis::setSelectableParts) ,iSelectLegend = 0x020 ///< 0x020 Legends are selectable (or their child items, see QCPLegend::setSelectableParts) ,iSelectItems = 0x040 ///< 0x040 Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem) ,iSelectOther = 0x080 ///< 0x080 All other objects are selectable (e.g. your own derived layerables, the plot title,...) }; Q_DECLARE_FLAGS(Interactions, Interaction) /*! \internal Returns whether the specified \a value is considered an invalid data value for plottables (i.e. is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. */ inline bool isInvalidData(double value) { return qIsNaN(value) || qIsInf(value); } /*! \internal \overload Checks two arguments instead of one. */ inline bool isInvalidData(double value1, double value2) { return isInvalidData(value1) || isInvalidData(value2); } /*! \internal Sets the specified \a side of \a margins to \a value \see getMarginValue */ inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) { switch (side) { case QCP::msLeft: margins.setLeft(value); break; case QCP::msRight: margins.setRight(value); break; case QCP::msTop: margins.setTop(value); break; case QCP::msBottom: margins.setBottom(value); break; case QCP::msAll: margins = QMargins(value, value, value, value); break; default: break; } } /*! \internal Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or \ref QCP::msAll, returns 0. \see setMarginValue */ inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) { switch (side) { case QCP::msLeft: return margins.left(); case QCP::msRight: return margins.right(); case QCP::msTop: return margins.top(); case QCP::msBottom: return margins.bottom(); default: break; } return 0; } } // end of namespace QCP Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) class QCP_LIB_DECL QCPScatterStyle { Q_GADGET public: /*! Defines the shape used for scatter points. On plottables/items that draw scatters, the sizes of these visualizations (with exception of \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are drawn with the pen and brush specified with \ref setPen and \ref setBrush. */ Q_ENUMS(ScatterShape) enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) ,ssCross ///< \enumimage{ssCross.png} a cross ,ssPlus ///< \enumimage{ssPlus.png} a plus ,ssCircle ///< \enumimage{ssCircle.png} a circle ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) ,ssSquare ///< \enumimage{ssSquare.png} a square ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) }; QCPScatterStyle(); QCPScatterStyle(ScatterShape shape, double size=6); QCPScatterStyle(ScatterShape shape, const QColor &color, double size); QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); QCPScatterStyle(const QPixmap &pixmap); QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); // getters: double size() const { return mSize; } ScatterShape shape() const { return mShape; } QPen pen() const { return mPen; } QBrush brush() const { return mBrush; } QPixmap pixmap() const { return mPixmap; } QPainterPath customPath() const { return mCustomPath; } // setters: void setSize(double size); void setShape(ScatterShape shape); void setPen(const QPen &pen); void setBrush(const QBrush &brush); void setPixmap(const QPixmap &pixmap); void setCustomPath(const QPainterPath &customPath); // non-property methods: bool isNone() const { return mShape == ssNone; } bool isPenDefined() const { return mPenDefined; } void applyTo(QCPPainter *painter, const QPen &defaultPen) const; void drawShape(QCPPainter *painter, QPointF pos) const; void drawShape(QCPPainter *painter, double x, double y) const; protected: // property members: double mSize; ScatterShape mShape; QPen mPen; QBrush mBrush; QPixmap mPixmap; QPainterPath mCustomPath; // non-property members: bool mPenDefined; }; Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); class QCP_LIB_DECL QCPPainter : public QPainter { Q_GADGET public: /*! Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, depending on whether they are wanted on the respective output device. */ enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. ,pmNoCaching = 0x02 ///< 0x02 Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels ,pmNonCosmetic = 0x04 ///< 0x04 Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.) }; Q_FLAGS(PainterMode PainterModes) Q_DECLARE_FLAGS(PainterModes, PainterMode) QCPPainter(); QCPPainter(QPaintDevice *device); ~QCPPainter(); // getters: bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } PainterModes modes() const { return mModes; } // setters: void setAntialiasing(bool enabled); void setMode(PainterMode mode, bool enabled=true); void setModes(PainterModes modes); // methods hiding non-virtual base class functions (QPainter bug workarounds): bool begin(QPaintDevice *device); void setPen(const QPen &pen); void setPen(const QColor &color); void setPen(Qt::PenStyle penStyle); void drawLine(const QLineF &line); void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} void save(); void restore(); // non-virtual methods: void makeNonCosmetic(); protected: // property members: PainterModes mModes; bool mIsAntialiasing; // non-property members: QStack mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) class QCP_LIB_DECL QCPLayer : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) Q_PROPERTY(QString name READ name) Q_PROPERTY(int index READ index) Q_PROPERTY(QList children READ children) Q_PROPERTY(bool visible READ visible WRITE setVisible) /// \endcond public: QCPLayer(QCustomPlot* parentPlot, const QString &layerName); ~QCPLayer(); // getters: QCustomPlot *parentPlot() const { return mParentPlot; } QString name() const { return mName; } int index() const { return mIndex; } QList children() const { return mChildren; } bool visible() const { return mVisible; } // setters: void setVisible(bool visible); protected: // property members: QCustomPlot *mParentPlot; QString mName; int mIndex; QList mChildren; bool mVisible; // non-virtual methods: void addChild(QCPLayerable *layerable, bool prepend); void removeChild(QCPLayerable *layerable); private: Q_DISABLE_COPY(QCPLayer) friend class QCustomPlot; friend class QCPLayerable; }; class QCP_LIB_DECL QCPLayerable : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool visible READ visible WRITE setVisible) Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) /// \endcond public: QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=0); ~QCPLayerable(); // getters: bool visible() const { return mVisible; } QCustomPlot *parentPlot() const { return mParentPlot; } QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } QCPLayer *layer() const { return mLayer; } bool antialiased() const { return mAntialiased; } // setters: void setVisible(bool on); Q_SLOT bool setLayer(QCPLayer *layer); bool setLayer(const QString &layerName); void setAntialiased(bool enabled); // introduced virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-property methods: bool realVisibility() const; signals: void layerChanged(QCPLayer *newLayer); protected: // property members: bool mVisible; QCustomPlot *mParentPlot; QPointer mParentLayerable; QCPLayer *mLayer; bool mAntialiased; // introduced virtual methods: virtual void parentPlotInitialized(QCustomPlot *parentPlot); virtual QCP::Interaction selectionCategory() const; virtual QRect clipRect() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-property methods: void initializeParentPlot(QCustomPlot *parentPlot); void setParentLayerable(QCPLayerable* parentLayerable); bool moveToLayer(QCPLayer *layer, bool prepend); void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; private: Q_DISABLE_COPY(QCPLayerable) friend class QCustomPlot; friend class QCPAxisRect; }; class QCP_LIB_DECL QCPRange { public: double lower, upper; QCPRange(); QCPRange(double lower, double upper); bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } bool operator!=(const QCPRange& other) const { return !(*this == other); } QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } friend inline const QCPRange operator+(const QCPRange&, double); friend inline const QCPRange operator+(double, const QCPRange&); friend inline const QCPRange operator-(const QCPRange& range, double value); friend inline const QCPRange operator*(const QCPRange& range, double value); friend inline const QCPRange operator*(double value, const QCPRange& range); friend inline const QCPRange operator/(const QCPRange& range, double value); double size() const; double center() const; void normalize(); void expand(const QCPRange &otherRange); QCPRange expanded(const QCPRange &otherRange) const; QCPRange sanitizedForLogScale() const; QCPRange sanitizedForLinScale() const; bool contains(double value) const; static bool validRange(double lower, double upper); static bool validRange(const QCPRange &range); static const double minRange; //1e-280; static const double maxRange; //1e280; }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); /* documentation of inline functions */ /*! \fn QCPRange &QCPRange::operator+=(const double& value) Adds \a value to both boundaries of the range. */ /*! \fn QCPRange &QCPRange::operator-=(const double& value) Subtracts \a value from both boundaries of the range. */ /*! \fn QCPRange &QCPRange::operator*=(const double& value) Multiplies both boundaries of the range by \a value. */ /*! \fn QCPRange &QCPRange::operator/=(const double& value) Divides both boundaries of the range by \a value. */ /* end documentation of inline functions */ /*! Adds \a value to both boundaries of the range. */ inline const QCPRange operator+(const QCPRange& range, double value) { QCPRange result(range); result += value; return result; } /*! Adds \a value to both boundaries of the range. */ inline const QCPRange operator+(double value, const QCPRange& range) { QCPRange result(range); result += value; return result; } /*! Subtracts \a value from both boundaries of the range. */ inline const QCPRange operator-(const QCPRange& range, double value) { QCPRange result(range); result -= value; return result; } /*! Multiplies both boundaries of the range by \a value. */ inline const QCPRange operator*(const QCPRange& range, double value) { QCPRange result(range); result *= value; return result; } /*! Multiplies both boundaries of the range by \a value. */ inline const QCPRange operator*(double value, const QCPRange& range) { QCPRange result(range); result *= value; return result; } /*! Divides both boundaries of the range by \a value. */ inline const QCPRange operator/(const QCPRange& range, double value) { QCPRange result(range); result /= value; return result; } class QCP_LIB_DECL QCPMarginGroup : public QObject { Q_OBJECT public: QCPMarginGroup(QCustomPlot *parentPlot); ~QCPMarginGroup(); // non-virtual methods: QList elements(QCP::MarginSide side) const { return mChildren.value(side); } bool isEmpty() const; void clear(); protected: // non-property members: QCustomPlot *mParentPlot; QHash > mChildren; // non-virtual methods: int commonMargin(QCP::MarginSide side) const; void addChild(QCP::MarginSide side, QCPLayoutElement *element); void removeChild(QCP::MarginSide side, QCPLayoutElement *element); private: Q_DISABLE_COPY(QCPMarginGroup) friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLayout* layout READ layout) Q_PROPERTY(QRect rect READ rect) Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) Q_PROPERTY(QMargins margins READ margins WRITE setMargins) Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) /// \endcond public: /*! Defines the phases of the update process, that happens just before a replot. At each phase, \ref update is called with the according UpdatePhase value. */ enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout ,upMargins ///< Phase in which the margins are calculated and set ,upLayout ///< Final phase in which the layout system places the rects of the elements }; Q_ENUMS(UpdatePhase) explicit QCPLayoutElement(QCustomPlot *parentPlot=0); virtual ~QCPLayoutElement(); // getters: QCPLayout *layout() const { return mParentLayout; } QRect rect() const { return mRect; } QRect outerRect() const { return mOuterRect; } QMargins margins() const { return mMargins; } QMargins minimumMargins() const { return mMinimumMargins; } QCP::MarginSides autoMargins() const { return mAutoMargins; } QSize minimumSize() const { return mMinimumSize; } QSize maximumSize() const { return mMaximumSize; } QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); } QHash marginGroups() const { return mMarginGroups; } // setters: void setOuterRect(const QRect &rect); void setMargins(const QMargins &margins); void setMinimumMargins(const QMargins &margins); void setAutoMargins(QCP::MarginSides sides); void setMinimumSize(const QSize &size); void setMinimumSize(int width, int height); void setMaximumSize(const QSize &size); void setMaximumSize(int width, int height); void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); // introduced virtual methods: virtual void update(UpdatePhase phase); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; virtual QList elements(bool recursive) const; // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPLayout *mParentLayout; QSize mMinimumSize, mMaximumSize; QRect mRect, mOuterRect; QMargins mMargins, mMinimumMargins; QCP::MarginSides mAutoMargins; QHash mMarginGroups; // introduced virtual methods: virtual int calculateAutoMargin(QCP::MarginSide side); // events: virtual void mousePressEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseMoveEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseReleaseEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseDoubleClickEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void wheelEvent(QWheelEvent *event) {Q_UNUSED(event)} // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const { Q_UNUSED(painter) } virtual void draw(QCPPainter *painter) { Q_UNUSED(painter) } virtual void parentPlotInitialized(QCustomPlot *parentPlot); private: Q_DISABLE_COPY(QCPLayoutElement) friend class QCustomPlot; friend class QCPLayout; friend class QCPMarginGroup; }; class QCP_LIB_DECL QCPLayout : public QCPLayoutElement { Q_OBJECT public: explicit QCPLayout(); // reimplemented virtual methods: virtual void update(UpdatePhase phase); virtual QList elements(bool recursive) const; // introduced virtual methods: virtual int elementCount() const = 0; virtual QCPLayoutElement* elementAt(int index) const = 0; virtual QCPLayoutElement* takeAt(int index) = 0; virtual bool take(QCPLayoutElement* element) = 0; virtual void simplify(); // non-virtual methods: bool removeAt(int index); bool remove(QCPLayoutElement* element); void clear(); protected: // introduced virtual methods: virtual void updateLayout(); // non-virtual methods: void sizeConstraintsChanged() const; void adoptElement(QCPLayoutElement *el); void releaseElement(QCPLayoutElement *el); QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; private: Q_DISABLE_COPY(QCPLayout) friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(int rowCount READ rowCount) Q_PROPERTY(int columnCount READ columnCount) Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) /// \endcond public: explicit QCPLayoutGrid(); virtual ~QCPLayoutGrid(); // getters: int rowCount() const; int columnCount() const; QList columnStretchFactors() const { return mColumnStretchFactors; } QList rowStretchFactors() const { return mRowStretchFactors; } int columnSpacing() const { return mColumnSpacing; } int rowSpacing() const { return mRowSpacing; } // setters: void setColumnStretchFactor(int column, double factor); void setColumnStretchFactors(const QList &factors); void setRowStretchFactor(int row, double factor); void setRowStretchFactors(const QList &factors); void setColumnSpacing(int pixels); void setRowSpacing(int pixels); // reimplemented virtual methods: virtual void updateLayout(); virtual int elementCount() const; virtual QCPLayoutElement* elementAt(int index) const; virtual QCPLayoutElement* takeAt(int index); virtual bool take(QCPLayoutElement* element); virtual QList elements(bool recursive) const; virtual void simplify(); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; // non-virtual methods: QCPLayoutElement *element(int row, int column) const; bool addElement(int row, int column, QCPLayoutElement *element); bool hasElement(int row, int column); void expandTo(int newRowCount, int newColumnCount); void insertRow(int newIndex); void insertColumn(int newIndex); protected: // property members: QList > mElements; QList mColumnStretchFactors; QList mRowStretchFactors; int mColumnSpacing, mRowSpacing; // non-virtual methods: void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; private: Q_DISABLE_COPY(QCPLayoutGrid) }; class QCP_LIB_DECL QCPLayoutInset : public QCPLayout { Q_OBJECT public: /*! Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. */ enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect ,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment }; explicit QCPLayoutInset(); virtual ~QCPLayoutInset(); // getters: InsetPlacement insetPlacement(int index) const; Qt::Alignment insetAlignment(int index) const; QRectF insetRect(int index) const; // setters: void setInsetPlacement(int index, InsetPlacement placement); void setInsetAlignment(int index, Qt::Alignment alignment); void setInsetRect(int index, const QRectF &rect); // reimplemented virtual methods: virtual void updateLayout(); virtual int elementCount() const; virtual QCPLayoutElement* elementAt(int index) const; virtual QCPLayoutElement* takeAt(int index); virtual bool take(QCPLayoutElement* element); virtual void simplify() {} virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: void addElement(QCPLayoutElement *element, Qt::Alignment alignment); void addElement(QCPLayoutElement *element, const QRectF &rect); protected: // property members: QList mElements; QList mInsetPlacement; QList mInsetAlignment; QList mInsetRect; private: Q_DISABLE_COPY(QCPLayoutInset) }; class QCP_LIB_DECL QCPLineEnding { Q_GADGET public: /*! Defines the type of ending decoration for line-like items, e.g. an arrow. \image html QCPLineEnding.png The width and length of these decorations can be controlled with the functions \ref setWidth and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only support a width, the length property is ignored. \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding */ Q_ENUMS(EndingStyle) enum EndingStyle { esNone ///< No ending decoration ,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle) ,esSpikeArrow ///< A filled arrow head with an indented back ,esLineArrow ///< A non-filled arrow head with open back ,esDisc ///< A filled circle ,esSquare ///< A filled square ,esDiamond ///< A filled diamond (45° rotated square) ,esBar ///< A bar perpendicular to the line ,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted) ,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength) }; QCPLineEnding(); QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); // getters: EndingStyle style() const { return mStyle; } double width() const { return mWidth; } double length() const { return mLength; } bool inverted() const { return mInverted; } // setters: void setStyle(EndingStyle style); void setWidth(double width); void setLength(double length); void setInverted(bool inverted); // non-property methods: double boundingDistance() const; double realLength() const; void draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const; void draw(QCPPainter *painter, const QVector2D &pos, double angle) const; protected: // property members: EndingStyle mStyle; double mWidth, mLength; bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); class QCP_LIB_DECL QCPGrid :public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) /// \endcond public: QCPGrid(QCPAxis *parentAxis); // getters: bool subGridVisible() const { return mSubGridVisible; } bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } QPen pen() const { return mPen; } QPen subGridPen() const { return mSubGridPen; } QPen zeroLinePen() const { return mZeroLinePen; } // setters: void setSubGridVisible(bool visible); void setAntialiasedSubGrid(bool enabled); void setAntialiasedZeroLine(bool enabled); void setPen(const QPen &pen); void setSubGridPen(const QPen &pen); void setZeroLinePen(const QPen &pen); protected: // property members: bool mSubGridVisible; bool mAntialiasedSubGrid, mAntialiasedZeroLine; QPen mPen, mSubGridPen, mZeroLinePen; // non-property members: QCPAxis *mParentAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); // non-virtual methods: void drawGridLines(QCPPainter *painter) const; void drawSubGridLines(QCPPainter *painter) const; friend class QCPAxis; }; class QCP_LIB_DECL QCPAxis : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(AxisType axisType READ axisType) Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) Q_PROPERTY(double scaleLogBase READ scaleLogBase WRITE setScaleLogBase) Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) Q_PROPERTY(bool autoTicks READ autoTicks WRITE setAutoTicks) Q_PROPERTY(int autoTickCount READ autoTickCount WRITE setAutoTickCount) Q_PROPERTY(bool autoTickLabels READ autoTickLabels WRITE setAutoTickLabels) Q_PROPERTY(bool autoTickStep READ autoTickStep WRITE setAutoTickStep) Q_PROPERTY(bool autoSubTicks READ autoSubTicks WRITE setAutoSubTicks) Q_PROPERTY(bool ticks READ ticks WRITE setTicks) Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels) Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding) Q_PROPERTY(LabelType tickLabelType READ tickLabelType WRITE setTickLabelType) Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont) Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor) Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation) Q_PROPERTY(LabelSide tickLabelSide READ tickLabelSide WRITE setTickLabelSide) Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat) Q_PROPERTY(Qt::TimeSpec dateTimeSpec READ dateTimeSpec WRITE setDateTimeSpec) Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat) Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) Q_PROPERTY(double tickStep READ tickStep WRITE setTickStep) Q_PROPERTY(QVector tickVector READ tickVector WRITE setTickVector) Q_PROPERTY(QVector tickVectorLabels READ tickVectorLabels WRITE setTickVectorLabels) Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) Q_PROPERTY(QString label READ label WRITE setLabel) Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) Q_PROPERTY(int padding READ padding WRITE setPadding) Q_PROPERTY(int offset READ offset WRITE setOffset) Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) Q_PROPERTY(QCPGrid* grid READ grid) /// \endcond public: /*! Defines at which side of the axis rect the axis will appear. This also affects how the tick marks are drawn, on which side the labels are placed etc. */ enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect ,atTop = 0x04 ///< 0x04 Axis is horizontal and on the top side of the axis rect ,atBottom = 0x08 ///< 0x08 Axis is horizontal and on the bottom side of the axis rect }; Q_FLAGS(AxisType AxisTypes) Q_DECLARE_FLAGS(AxisTypes, AxisType) /*! When automatic tick label generation is enabled (\ref setAutoTickLabels), defines how the coordinate of the tick is interpreted, i.e. translated into a string. \see setTickLabelType */ enum LabelType { ltNumber ///< Tick coordinate is regarded as normal number and will be displayed as such. (see \ref setNumberFormat) ,ltDateTime ///< Tick coordinate is regarded as a date/time (seconds since 1970-01-01T00:00:00 UTC) and will be displayed and formatted as such. (for details, see \ref setDateTimeFormat) }; Q_ENUMS(LabelType) /*! Defines on which side of the axis the tick labels (numbers) shall appear. \see setTickLabelSide */ enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect ,lsOutside ///< Tick labels will be displayed outside the axis rect }; Q_ENUMS(LabelSide) /*! Defines the scale of an axis. \see setScaleType */ enum ScaleType { stLinear ///< Linear scaling ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base power (see \ref setScaleLogBase). }; Q_ENUMS(ScaleType) /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts */ enum SelectablePart { spNone = 0 ///< None of the selectable parts ,spAxis = 0x001 ///< The axis backbone and tick marks ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) ,spAxisLabel = 0x004 ///< The axis label }; Q_FLAGS(SelectablePart SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPAxis(QCPAxisRect *parent, AxisType type); virtual ~QCPAxis(); // getters: AxisType axisType() const { return mAxisType; } QCPAxisRect *axisRect() const { return mAxisRect; } ScaleType scaleType() const { return mScaleType; } double scaleLogBase() const { return mScaleLogBase; } const QCPRange range() const { return mRange; } bool rangeReversed() const { return mRangeReversed; } bool autoTicks() const { return mAutoTicks; } int autoTickCount() const { return mAutoTickCount; } bool autoTickLabels() const { return mAutoTickLabels; } bool autoTickStep() const { return mAutoTickStep; } bool autoSubTicks() const { return mAutoSubTicks; } bool ticks() const { return mTicks; } bool tickLabels() const { return mTickLabels; } int tickLabelPadding() const; LabelType tickLabelType() const { return mTickLabelType; } QFont tickLabelFont() const { return mTickLabelFont; } QColor tickLabelColor() const { return mTickLabelColor; } double tickLabelRotation() const; LabelSide tickLabelSide() const; QString dateTimeFormat() const { return mDateTimeFormat; } Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } QString numberFormat() const; int numberPrecision() const { return mNumberPrecision; } double tickStep() const { return mTickStep; } QVector tickVector() const { return mTickVector; } QVector tickVectorLabels() const { return mTickVectorLabels; } int tickLengthIn() const; int tickLengthOut() const; int subTickCount() const { return mSubTickCount; } int subTickLengthIn() const; int subTickLengthOut() const; QPen basePen() const { return mBasePen; } QPen tickPen() const { return mTickPen; } QPen subTickPen() const { return mSubTickPen; } QFont labelFont() const { return mLabelFont; } QColor labelColor() const { return mLabelColor; } QString label() const { return mLabel; } int labelPadding() const; int padding() const { return mPadding; } int offset() const; SelectableParts selectedParts() const { return mSelectedParts; } SelectableParts selectableParts() const { return mSelectableParts; } QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } QFont selectedLabelFont() const { return mSelectedLabelFont; } QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } QColor selectedLabelColor() const { return mSelectedLabelColor; } QPen selectedBasePen() const { return mSelectedBasePen; } QPen selectedTickPen() const { return mSelectedTickPen; } QPen selectedSubTickPen() const { return mSelectedSubTickPen; } QCPLineEnding lowerEnding() const; QCPLineEnding upperEnding() const; QCPGrid *grid() const { return mGrid; } // setters: Q_SLOT void setScaleType(QCPAxis::ScaleType type); void setScaleLogBase(double base); Q_SLOT void setRange(const QCPRange &range); void setRange(double lower, double upper); void setRange(double position, double size, Qt::AlignmentFlag alignment); void setRangeLower(double lower); void setRangeUpper(double upper); void setRangeReversed(bool reversed); void setAutoTicks(bool on); void setAutoTickCount(int approximateCount); void setAutoTickLabels(bool on); void setAutoTickStep(bool on); void setAutoSubTicks(bool on); void setTicks(bool show); void setTickLabels(bool show); void setTickLabelPadding(int padding); void setTickLabelType(LabelType type); void setTickLabelFont(const QFont &font); void setTickLabelColor(const QColor &color); void setTickLabelRotation(double degrees); void setTickLabelSide(LabelSide side); void setDateTimeFormat(const QString &format); void setDateTimeSpec(const Qt::TimeSpec &timeSpec); void setNumberFormat(const QString &formatCode); void setNumberPrecision(int precision); void setTickStep(double step); void setTickVector(const QVector &vec); void setTickVectorLabels(const QVector &vec); void setTickLength(int inside, int outside=0); void setTickLengthIn(int inside); void setTickLengthOut(int outside); void setSubTickCount(int count); void setSubTickLength(int inside, int outside=0); void setSubTickLengthIn(int inside); void setSubTickLengthOut(int outside); void setBasePen(const QPen &pen); void setTickPen(const QPen &pen); void setSubTickPen(const QPen &pen); void setLabelFont(const QFont &font); void setLabelColor(const QColor &color); void setLabel(const QString &str); void setLabelPadding(int padding); void setPadding(int padding); void setOffset(int offset); void setSelectedTickLabelFont(const QFont &font); void setSelectedLabelFont(const QFont &font); void setSelectedTickLabelColor(const QColor &color); void setSelectedLabelColor(const QColor &color); void setSelectedBasePen(const QPen &pen); void setSelectedTickPen(const QPen &pen); void setSelectedSubTickPen(const QPen &pen); Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); void setLowerEnding(const QCPLineEnding &ending); void setUpperEnding(const QCPLineEnding &ending); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-property methods: Qt::Orientation orientation() const { return mOrientation; } void moveRange(double diff); void scaleRange(double factor, double center); void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); void rescale(bool onlyVisiblePlottables=false); double pixelToCoord(double value) const; double coordToPixel(double value) const; SelectablePart getPartAt(const QPointF &pos) const; QList plottables() const; QList graphs() const; QList items() const; static AxisType marginSideToAxisType(QCP::MarginSide side); static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; } static AxisType opposite(AxisType type); signals: void ticksRequest(); void rangeChanged(const QCPRange &newRange); void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); void scaleTypeChanged(QCPAxis::ScaleType scaleType); void selectionChanged(const QCPAxis::SelectableParts &parts); void selectableChanged(const QCPAxis::SelectableParts &parts); protected: // property members: // axis base: AxisType mAxisType; QCPAxisRect *mAxisRect; //int mOffset; // in QCPAxisPainter int mPadding; Qt::Orientation mOrientation; SelectableParts mSelectableParts, mSelectedParts; QPen mBasePen, mSelectedBasePen; //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter // axis label: //int mLabelPadding; // in QCPAxisPainter QString mLabel; QFont mLabelFont, mSelectedLabelFont; QColor mLabelColor, mSelectedLabelColor; // tick labels: //int mTickLabelPadding; // in QCPAxisPainter bool mTickLabels, mAutoTickLabels; //double mTickLabelRotation; // in QCPAxisPainter LabelType mTickLabelType; QFont mTickLabelFont, mSelectedTickLabelFont; QColor mTickLabelColor, mSelectedTickLabelColor; QString mDateTimeFormat; Qt::TimeSpec mDateTimeSpec; int mNumberPrecision; QLatin1Char mNumberFormatChar; bool mNumberBeautifulPowers; //bool mNumberMultiplyCross; // QCPAxisPainter // ticks and subticks: bool mTicks; double mTickStep; int mSubTickCount, mAutoTickCount; bool mAutoTicks, mAutoTickStep, mAutoSubTicks; //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; // scale and range: QCPRange mRange; bool mRangeReversed; ScaleType mScaleType; double mScaleLogBase, mScaleLogBaseLogInv; // non-property members: QCPGrid *mGrid; QCPAxisPainterPrivate *mAxisPainter; int mLowestVisibleTick, mHighestVisibleTick; QVector mTickVector; QVector mTickVectorLabels; QVector mSubTickVector; bool mCachedMarginValid; int mCachedMargin; // introduced virtual methods: virtual void setupTickVectors(); virtual void generateAutoTicks(); virtual int calculateAutoSubTickCount(double tickStep) const; virtual int calculateMargin(); // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual QCP::Interaction selectionCategory() const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: void visibleTickBounds(int &lowIndex, int &highIndex) const; double baseLog(double value) const; double basePow(double value) const; QPen getBasePen() const; QPen getTickPen() const; QPen getSubTickPen() const; QFont getTickLabelFont() const; QFont getLabelFont() const; QColor getTickLabelColor() const; QColor getLabelColor() const; private: Q_DISABLE_COPY(QCPAxis) friend class QCustomPlot; friend class QCPGrid; friend class QCPAxisRect; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) Q_DECLARE_METATYPE(QCPAxis::SelectablePart) class QCPAxisPainterPrivate { public: explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); virtual ~QCPAxisPainterPrivate(); virtual void draw(QCPPainter *painter); virtual int size() const; void clearCache(); QRect axisSelectionBox() const { return mAxisSelectionBox; } QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } QRect labelSelectionBox() const { return mLabelSelectionBox; } // public property members: QCPAxis::AxisType type; QPen basePen; QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters int labelPadding; // directly accessed by QCPAxis setters/getters QFont labelFont; QColor labelColor; QString label; int tickLabelPadding; // directly accessed by QCPAxis setters/getters double tickLabelRotation; // directly accessed by QCPAxis setters/getters QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters bool substituteExponent; bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters QPen tickPen, subTickPen; QFont tickLabelFont; QColor tickLabelColor; QRect axisRect, viewportRect; double offset; // directly accessed by QCPAxis setters/getters bool abbreviateDecimalPowers; bool reversedEndings; QVector subTickPositions; QVector tickPositions; QVector tickLabels; protected: struct CachedLabel { QPointF offset; QPixmap pixmap; }; struct TickLabelData { QString basePart, expPart; QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; QFont baseFont, expFont; }; QCustomPlot *mParentPlot; QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters QCache mLabelCache; QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; virtual QByteArray generateLabelParameterHash() const; virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill) Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters) Q_PROPERTY(bool antialiasedErrorBars READ antialiasedErrorBars WRITE setAntialiasedErrorBars) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); // getters: QString name() const { return mName; } bool antialiasedFill() const { return mAntialiasedFill; } bool antialiasedScatters() const { return mAntialiasedScatters; } bool antialiasedErrorBars() const { return mAntialiasedErrorBars; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setName(const QString &name); void setAntialiasedFill(bool enabled); void setAntialiasedScatters(bool enabled); void setAntialiasedErrorBars(bool enabled); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setKeyAxis(QCPAxis *axis); void setValueAxis(QCPAxis *axis); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // introduced virtual methods: virtual void clearData() = 0; virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; virtual bool addToLegend(); virtual bool removeFromLegend() const; // non-property methods: void rescaleAxes(bool onlyEnlarge=false) const; void rescaleKeyAxis(bool onlyEnlarge=false) const; void rescaleValueAxis(bool onlyEnlarge=false) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: /*! Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange. */ enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero ,sdBoth ///< Both sign domains, including zero, i.e. all (rational) numbers ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero }; // property members: QString mName; bool mAntialiasedFill, mAntialiasedScatters, mAntialiasedErrorBars; QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; QPointer mKeyAxis, mValueAxis; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QRect clipRect() const; virtual void draw(QCPPainter *painter) = 0; virtual QCP::Interaction selectionCategory() const; void applyDefaultAntialiasingHint(QCPPainter *painter) const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // introduced virtual methods: virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; // non-virtual methods: void coordsToPixels(double key, double value, double &x, double &y) const; const QPointF coordsToPixels(double key, double value) const; void pixelsToCoords(double x, double y, double &key, double &value) const; void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; QPen mainPen() const; QBrush mainBrush() const; void applyFillAntialiasingHint(QCPPainter *painter) const; void applyScattersAntialiasingHint(QCPPainter *painter) const; void applyErrorBarsAntialiasingHint(QCPPainter *painter) const; double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; private: Q_DISABLE_COPY(QCPAbstractPlottable) friend class QCustomPlot; friend class QCPAxis; friend class QCPPlottableLegendItem; }; class QCP_LIB_DECL QCPItemAnchor { public: QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1); virtual ~QCPItemAnchor(); // getters: QString name() const { return mName; } virtual QPointF pixelPoint() const; protected: // property members: QString mName; // non-property members: QCustomPlot *mParentPlot; QCPAbstractItem *mParentItem; int mAnchorId; QSet mChildrenX, mChildrenY; // introduced virtual methods: virtual QCPItemPosition *toQCPItemPosition() { return 0; } // non-virtual methods: void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted private: Q_DISABLE_COPY(QCPItemAnchor) friend class QCPItemPosition; }; class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { public: /*! Defines the ways an item position can be specified. Thus it defines what the numbers passed to \ref setCoords actually mean. \see setType */ enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and ///< vertically at the top of the viewport/widget, etc. ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and ///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1. ,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes). }; QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); virtual ~QCPItemPosition(); // getters: PositionType type() const { return typeX(); } PositionType typeX() const { return mPositionTypeX; } PositionType typeY() const { return mPositionTypeY; } QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } double key() const { return mKey; } double value() const { return mValue; } QPointF coords() const { return QPointF(mKey, mValue); } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } QCPAxisRect *axisRect() const; virtual QPointF pixelPoint() const; // setters: void setType(PositionType type); void setTypeX(PositionType type); void setTypeY(PositionType type); bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); void setCoords(double key, double value); void setCoords(const QPointF &coords); void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); void setAxisRect(QCPAxisRect *axisRect); void setPixelPoint(const QPointF &pixelPoint); protected: // property members: PositionType mPositionTypeX, mPositionTypeY; QPointer mKeyAxis, mValueAxis; QPointer mAxisRect; double mKey, mValue; QCPItemAnchor *mParentAnchorX, *mParentAnchorY; // reimplemented virtual methods: virtual QCPItemPosition *toQCPItemPosition() { return this; } private: Q_DISABLE_COPY(QCPItemPosition) }; class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: QCPAbstractItem(QCustomPlot *parentPlot); virtual ~QCPAbstractItem(); // getters: bool clipToAxisRect() const { return mClipToAxisRect; } QCPAxisRect *clipAxisRect() const; bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setClipToAxisRect(bool clip); void setClipAxisRect(QCPAxisRect *rect); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; // non-virtual methods: QList positions() const { return mPositions; } QList anchors() const { return mAnchors; } QCPItemPosition *position(const QString &name) const; QCPItemAnchor *anchor(const QString &name) const; bool hasAnchor(const QString &name) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: bool mClipToAxisRect; QPointer mClipAxisRect; QList mPositions; QList mAnchors; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QCP::Interaction selectionCategory() const; virtual QRect clipRect() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // introduced virtual methods: virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; double rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const; QCPItemPosition *createPosition(const QString &name); QCPItemAnchor *createAnchor(const QString &name, int anchorId); private: Q_DISABLE_COPY(QCPAbstractItem) friend class QCustomPlot; friend class QCPItemAnchor; }; class QCP_LIB_DECL QCustomPlot : public QWidget { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance) Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag) Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier) /// \endcond public: /*! Defines how a layer should be inserted relative to an other layer. \see addLayer, moveLayer */ enum LayerInsertMode { limBelow ///< Layer is inserted below other layer ,limAbove ///< Layer is inserted above other layer }; Q_ENUMS(LayerInsertMode) /*! Defines with what timing the QCustomPlot surface is refreshed after a replot. \see replot */ enum RefreshPriority { rpImmediate ///< The QCustomPlot surface is immediately refreshed, by calling QWidget::repaint() after the replot ,rpQueued ///< Queues the refresh such that it is performed at a slightly delayed point in time after the replot, by calling QWidget::update() after the replot ,rpHint ///< Whether to use immediate repaint or queued update depends on whether the plotting hint \ref QCP::phForceRepaint is set, see \ref setPlottingHints. }; explicit QCustomPlot(QWidget *parent = 0); virtual ~QCustomPlot(); // getters: QRect viewport() const { return mViewport; } QPixmap background() const { return mBackgroundPixmap; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } QCPLayoutGrid *plotLayout() const { return mPlotLayout; } QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } const QCP::Interactions interactions() const { return mInteractions; } int selectionTolerance() const { return mSelectionTolerance; } bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } QCP::PlottingHints plottingHints() const { return mPlottingHints; } Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } // setters: void setViewport(const QRect &rect); void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); void setAutoAddPlottableToLegend(bool on); void setInteractions(const QCP::Interactions &interactions); void setInteraction(const QCP::Interaction &interaction, bool enabled=true); void setSelectionTolerance(int pixels); void setNoAntialiasingOnDrag(bool enabled); void setPlottingHints(const QCP::PlottingHints &hints); void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); void setMultiSelectModifier(Qt::KeyboardModifier modifier); // non-property methods: // plottable interface: QCPAbstractPlottable *plottable(int index); QCPAbstractPlottable *plottable(); bool addPlottable(QCPAbstractPlottable *plottable); bool removePlottable(QCPAbstractPlottable *plottable); bool removePlottable(int index); int clearPlottables(); int plottableCount() const; QList selectedPlottables() const; QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const; bool hasPlottable(QCPAbstractPlottable *plottable) const; // specialized interface for QCPGraph: QCPGraph *graph(int index) const; QCPGraph *graph() const; QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0); bool removeGraph(QCPGraph *graph); bool removeGraph(int index); int clearGraphs(); int graphCount() const; QList selectedGraphs() const; // item interface: QCPAbstractItem *item(int index) const; QCPAbstractItem *item() const; bool addItem(QCPAbstractItem* item); bool removeItem(QCPAbstractItem *item); bool removeItem(int index); int clearItems(); int itemCount() const; QList selectedItems() const; QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; bool hasItem(QCPAbstractItem *item) const; // layer interface: QCPLayer *layer(const QString &name) const; QCPLayer *layer(int index) const; QCPLayer *currentLayer() const; bool setCurrentLayer(const QString &name); bool setCurrentLayer(QCPLayer *layer); int layerCount() const; bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove); bool removeLayer(QCPLayer *layer); bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); // axis rect/layout interface: int axisRectCount() const; QCPAxisRect* axisRect(int index=0) const; QList axisRects() const; QCPLayoutElement* layoutElementAt(const QPointF &pos) const; Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); QList selectedAxes() const; QList selectedLegends() const; Q_SLOT void deselectAll(); bool savePdf(const QString &fileName, bool noCosmeticPen=false, int width=0, int height=0, const QString &pdfCreator=QString(), const QString &pdfTitle=QString()); bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0); bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1); QPixmap toPixmap(int width=0, int height=0, double scale=1.0); void toPainter(QCPPainter *painter, int width=0, int height=0); Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpHint); QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; QCPLegend *legend; signals: void mouseDoubleClick(QMouseEvent *event); void mousePress(QMouseEvent *event); void mouseMove(QMouseEvent *event); void mouseRelease(QMouseEvent *event); void mouseWheel(QWheelEvent *event); void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); void plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event); void itemClick(QCPAbstractItem *item, QMouseEvent *event); void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event); void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void titleClick(QMouseEvent *event, QCPPlotTitle *title); void titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title); void selectionChangedByUser(); void beforeReplot(); void afterReplot(); protected: // property members: QRect mViewport; QCPLayoutGrid *mPlotLayout; bool mAutoAddPlottableToLegend; QList mPlottables; QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph QList mItems; QList mLayers; QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; QCP::Interactions mInteractions; int mSelectionTolerance; bool mNoAntialiasingOnDrag; QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayer *mCurrentLayer; QCP::PlottingHints mPlottingHints; Qt::KeyboardModifier mMultiSelectModifier; // non-property members: QPixmap mPaintBuffer; QPoint mMousePressPos; QPointer mMouseEventElement; bool mReplotting; // reimplemented virtual methods: virtual QSize minimumSizeHint() const; virtual QSize sizeHint() const; virtual void paintEvent(QPaintEvent *event); virtual void resizeEvent(QResizeEvent *event); virtual void mouseDoubleClickEvent(QMouseEvent *event); virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); // introduced virtual methods: virtual void draw(QCPPainter *painter); virtual void axisRemoved(QCPAxis *axis); virtual void legendRemoved(QCPLegend *legend); // non-virtual methods: void updateLayerIndices() const; QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const; void drawBackground(QCPPainter *painter); friend class QCPLegend; friend class QCPAxis; friend class QCPLayer; friend class QCPAxisRect; }; class QCP_LIB_DECL QCPColorGradient { Q_GADGET public: /*! Defines the color spaces in which color interpolation between gradient stops can be performed. \see setColorInterpolation */ enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) }; Q_ENUMS(ColorInterpolation) /*! Defines the available presets that can be loaded with \ref loadPreset. See the documentation there for an image of the presets. */ enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) ,gpCandy ///< Blue over pink to white ,gpGeography ///< Colors suitable to represent different elevations on geographical maps ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) }; Q_ENUMS(GradientPreset) QCPColorGradient(GradientPreset preset=gpCold); bool operator==(const QCPColorGradient &other) const; bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } // getters: int levelCount() const { return mLevelCount; } QMap colorStops() const { return mColorStops; } ColorInterpolation colorInterpolation() const { return mColorInterpolation; } bool periodic() const { return mPeriodic; } // setters: void setLevelCount(int n); void setColorStops(const QMap &colorStops); void setColorStopAt(double position, const QColor &color); void setColorInterpolation(ColorInterpolation interpolation); void setPeriodic(bool enabled); // non-property methods: void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); QRgb color(double position, const QCPRange &range, bool logarithmic=false); void loadPreset(GradientPreset preset); void clearColorStops(); QCPColorGradient inverted() const; protected: void updateColorBuffer(); // property members: int mLevelCount; QMap mColorStops; ColorInterpolation mColorInterpolation; bool mPeriodic; // non-property members: QVector mColorBuffer; bool mColorBufferInvalidated; }; class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) /// \endcond public: explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); virtual ~QCPAxisRect(); // getters: QPixmap background() const { return mBackgroundPixmap; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } Qt::Orientations rangeDrag() const { return mRangeDrag; } Qt::Orientations rangeZoom() const { return mRangeZoom; } QCPAxis *rangeDragAxis(Qt::Orientation orientation); QCPAxis *rangeZoomAxis(Qt::Orientation orientation); double rangeZoomFactor(Qt::Orientation orientation); // setters: void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setRangeDrag(Qt::Orientations orientations); void setRangeZoom(Qt::Orientations orientations); void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); void setRangeZoomFactor(double horizontalFactor, double verticalFactor); void setRangeZoomFactor(double factor); // non-property methods: int axisCount(QCPAxis::AxisType type) const; QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; QList axes(QCPAxis::AxisTypes types) const; QList axes() const; QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=0); QList addAxes(QCPAxis::AxisTypes types); bool removeAxis(QCPAxis *axis); QCPLayoutInset *insetLayout() const { return mInsetLayout; } void setupFullAxesBox(bool connectRanges=false); QList plottables() const; QList graphs() const; QList items() const; // read-only interface imitating a QRect: int left() const { return mRect.left(); } int right() const { return mRect.right(); } int top() const { return mRect.top(); } int bottom() const { return mRect.bottom(); } int width() const { return mRect.width(); } int height() const { return mRect.height(); } QSize size() const { return mRect.size(); } QPoint topLeft() const { return mRect.topLeft(); } QPoint topRight() const { return mRect.topRight(); } QPoint bottomLeft() const { return mRect.bottomLeft(); } QPoint bottomRight() const { return mRect.bottomRight(); } QPoint center() const { return mRect.center(); } // reimplemented virtual methods: virtual void update(UpdatePhase phase); virtual QList elements(bool recursive) const; protected: // property members: QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayoutInset *mInsetLayout; Qt::Orientations mRangeDrag, mRangeZoom; QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; double mRangeZoomFactorHorz, mRangeZoomFactorVert; // non-property members: QCPRange mDragStartHorzRange, mDragStartVertRange; QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; QPoint mDragStart; bool mDragging; QHash > mAxes; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual int calculateAutoMargin(QCP::MarginSide side); // events: virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); // non-property methods: void drawBackground(QCPPainter *painter); void updateAxesOffset(QCPAxis::AxisType type); private: Q_DISABLE_COPY(QCPAxisRect) friend class QCustomPlot; }; class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) /// \endcond public: explicit QCPAbstractLegendItem(QCPLegend *parent); // getters: QCPLegend *parentLegend() const { return mParentLegend; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: QCPLegend *mParentLegend; QFont mFont; QColor mTextColor; QFont mSelectedFont; QColor mSelectedTextColor; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QCP::Interaction selectionCategory() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual QRect clipRect() const; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); private: Q_DISABLE_COPY(QCPAbstractLegendItem) friend class QCPLegend; }; class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem { Q_OBJECT public: QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); // getters: QCPAbstractPlottable *plottable() { return mPlottable; } protected: // property members: QCPAbstractPlottable *mPlottable; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QSize minimumSizeHint() const; // non-virtual methods: QPen getIconBorderPen() const; QColor getTextColor() const; QFont getFont() const; }; class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) /// \endcond public: /*! Defines the selectable parts of a legend \see setSelectedParts, setSelectableParts */ enum SelectablePart { spNone = 0x000 ///< 0x000 None ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) }; Q_FLAGS(SelectablePart SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPLegend(); virtual ~QCPLegend(); // getters: QPen borderPen() const { return mBorderPen; } QBrush brush() const { return mBrush; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QSize iconSize() const { return mIconSize; } int iconTextPadding() const { return mIconTextPadding; } QPen iconBorderPen() const { return mIconBorderPen; } SelectableParts selectableParts() const { return mSelectableParts; } SelectableParts selectedParts() const; QPen selectedBorderPen() const { return mSelectedBorderPen; } QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } QBrush selectedBrush() const { return mSelectedBrush; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } // setters: void setBorderPen(const QPen &pen); void setBrush(const QBrush &brush); void setFont(const QFont &font); void setTextColor(const QColor &color); void setIconSize(const QSize &size); void setIconSize(int width, int height); void setIconTextPadding(int padding); void setIconBorderPen(const QPen &pen); Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); void setSelectedBorderPen(const QPen &pen); void setSelectedIconBorderPen(const QPen &pen); void setSelectedBrush(const QBrush &brush); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: QCPAbstractLegendItem *item(int index) const; QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; int itemCount() const; bool hasItem(QCPAbstractLegendItem *item) const; bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; bool addItem(QCPAbstractLegendItem *item); bool removeItem(int index); bool removeItem(QCPAbstractLegendItem *item); void clearItems(); QList selectedItems() const; signals: void selectionChanged(QCPLegend::SelectableParts parts); void selectableChanged(QCPLegend::SelectableParts parts); protected: // property members: QPen mBorderPen, mIconBorderPen; QBrush mBrush; QFont mFont; QColor mTextColor; QSize mIconSize; int mIconTextPadding; SelectableParts mSelectedParts, mSelectableParts; QPen mSelectedBorderPen, mSelectedIconBorderPen; QBrush mSelectedBrush; QFont mSelectedFont; QColor mSelectedTextColor; // reimplemented virtual methods: virtual void parentPlotInitialized(QCustomPlot *parentPlot); virtual QCP::Interaction selectionCategory() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: QPen getBorderPen() const; QBrush getBrush() const; private: Q_DISABLE_COPY(QCPLegend) friend class QCustomPlot; friend class QCPAbstractLegendItem; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: explicit QCPPlotTitle(QCustomPlot *parentPlot); explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); // getters: QString text() const { return mText; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setText(const QString &text); void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: QString mText; QFont mFont; QColor mTextColor; QFont mSelectedFont; QColor mSelectedTextColor; QRect mTextBoundingRect; bool mSelectable, mSelected; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: QFont mainFont() const; QColor mainTextColor() const; private: Q_DISABLE_COPY(QCPPlotTitle) }; class QCPColorScaleAxisRectPrivate : public QCPAxisRect { Q_OBJECT public: explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); protected: QCPColorScale *mParentColorScale; QImage mGradientImage; bool mGradientImageInvalidated; // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale using QCPAxisRect::calculateAutoMargin; using QCPAxisRect::mousePressEvent; using QCPAxisRect::mouseMoveEvent; using QCPAxisRect::mouseReleaseEvent; using QCPAxisRect::wheelEvent; using QCPAxisRect::update; virtual void draw(QCPPainter *painter); void updateGradientImage(); Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); friend class QCPColorScale; }; class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) Q_PROPERTY(QString label READ label WRITE setLabel) Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) /// \endcond public: explicit QCPColorScale(QCustomPlot *parentPlot); virtual ~QCPColorScale(); // getters: QCPAxis *axis() const { return mColorAxis.data(); } QCPAxis::AxisType type() const { return mType; } QCPRange dataRange() const { return mDataRange; } QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } QCPColorGradient gradient() const { return mGradient; } QString label() const; int barWidth () const { return mBarWidth; } bool rangeDrag() const; bool rangeZoom() const; // setters: void setType(QCPAxis::AxisType type); Q_SLOT void setDataRange(const QCPRange &dataRange); Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); Q_SLOT void setGradient(const QCPColorGradient &gradient); void setLabel(const QString &str); void setBarWidth(int width); void setRangeDrag(bool enabled); void setRangeZoom(bool enabled); // non-property methods: QList colorMaps() const; void rescaleDataRange(bool onlyVisibleMaps); // reimplemented virtual methods: virtual void update(UpdatePhase phase); signals: void dataRangeChanged(QCPRange newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); void gradientChanged(QCPColorGradient newGradient); protected: // property members: QCPAxis::AxisType mType; QCPRange mDataRange; QCPAxis::ScaleType mDataScaleType; QCPColorGradient mGradient; int mBarWidth; // non-property members: QPointer mAxisRect; QPointer mColorAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; // events: virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); private: Q_DISABLE_COPY(QCPColorScale) friend class QCPColorScaleAxisRectPrivate; }; /*! \file */ class QCP_LIB_DECL QCPData { public: QCPData(); QCPData(double key, double value); double key, value; double keyErrorPlus, keyErrorMinus; double valueErrorPlus, valueErrorMinus; }; Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE); /*! \typedef QCPDataMap Container for storing \ref QCPData items in a sorted fashion. The key of the map is the key member of the QCPData instance. This is the container in which QCPGraph holds its data. \see QCPData, QCPGraph::setData */ typedef QMap QCPDataMap; typedef QMapIterator QCPDataMapIterator; typedef QMutableMapIterator QCPDataMutableMapIterator; class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) Q_PROPERTY(QPen errorPen READ errorPen WRITE setErrorPen) Q_PROPERTY(double errorBarSize READ errorBarSize WRITE setErrorBarSize) Q_PROPERTY(bool errorBarSkipSymbol READ errorBarSkipSymbol WRITE setErrorBarSkipSymbol) Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) /// \endcond public: /*! Defines how the graph's line is represented visually in the plot. The line is drawn with the current pen of the graph (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented ///< with symbols according to the scatter style, see \ref setScatterStyle) ,lsLine ///< data points are connected by a straight line ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point ,lsStepCenter ///< line is drawn as steps where the step is in between two data points ,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line }; Q_ENUMS(LineStyle) /*! Defines what kind of error bars are drawn for each data point */ enum ErrorType { etNone ///< No error bars are shown ,etKey ///< Error bars for the key dimension of the data point are shown ,etValue ///< Error bars for the value dimension of the data point are shown ,etBoth ///< Error bars for both key and value dimensions of the data point are shown }; Q_ENUMS(ErrorType) explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPGraph(); // getters: QCPDataMap *data() const { return mData; } LineStyle lineStyle() const { return mLineStyle; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } ErrorType errorType() const { return mErrorType; } QPen errorPen() const { return mErrorPen; } double errorBarSize() const { return mErrorBarSize; } bool errorBarSkipSymbol() const { return mErrorBarSkipSymbol; } QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } bool adaptiveSampling() const { return mAdaptiveSampling; } // setters: void setData(QCPDataMap *data, bool copy=false); void setData(const QVector &key, const QVector &value); void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError); void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus); void setDataValueError(const QVector &key, const QVector &value, const QVector &valueError); void setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus); void setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError); void setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus); void setLineStyle(LineStyle ls); void setScatterStyle(const QCPScatterStyle &style); void setErrorType(ErrorType errorType); void setErrorPen(const QPen &pen); void setErrorBarSize(double size); void setErrorBarSkipSymbol(bool enabled); void setChannelFillGraph(QCPGraph *targetGraph); void setAdaptiveSampling(bool enabled); // non-property methods: void addData(const QCPDataMap &dataMap); void addData(const QCPData &data); void addData(double key, double value); void addData(const QVector &keys, const QVector &values); void removeDataBefore(double key); void removeDataAfter(double key); void removeData(double fromKey, double toKey); void removeData(double key); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; using QCPAbstractPlottable::rescaleAxes; using QCPAbstractPlottable::rescaleKeyAxis; using QCPAbstractPlottable::rescaleValueAxis; void rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface void rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface void rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface protected: // property members: QCPDataMap *mData; QPen mErrorPen; LineStyle mLineStyle; QCPScatterStyle mScatterStyle; ErrorType mErrorType; double mErrorBarSize; bool mErrorBarSkipSymbol; QPointer mChannelFillGraph; bool mAdaptiveSampling; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface // introduced virtual methods: virtual void drawFill(QCPPainter *painter, QVector *lineData) const; virtual void drawScatterPlot(QCPPainter *painter, QVector *scatterData) const; virtual void drawLinePlot(QCPPainter *painter, QVector *lineData) const; virtual void drawImpulsePlot(QCPPainter *painter, QVector *lineData) const; // non-virtual methods: void getPreparedData(QVector *lineData, QVector *scatterData) const; void getPlotData(QVector *lineData, QVector *scatterData) const; void getScatterPlotData(QVector *scatterData) const; void getLinePlotData(QVector *linePixelData, QVector *scatterData) const; void getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const; void getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const; void getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const; void getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const; void drawError(QCPPainter *painter, double x, double y, const QCPData &data) const; void getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const; int countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const; void addFillBasePoints(QVector *lineData) const; void removeFillBasePoints(QVector *lineData) const; QPointF lowerFillBasePoint(double lowerKey) const; QPointF upperFillBasePoint(double upperKey) const; const QPolygonF getChannelFillPolygon(const QVector *lineData) const; int findIndexBelowX(const QVector *data, double x) const; int findIndexAboveX(const QVector *data, double x) const; int findIndexBelowY(const QVector *data, double y) const; int findIndexAboveY(const QVector *data, double y) const; double pointDistance(const QPointF &pixelPoint) const; friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPCurveData { public: QCPCurveData(); QCPCurveData(double t, double key, double value); double t, key, value; }; Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE); /*! \typedef QCPCurveDataMap Container for storing \ref QCPCurveData items in a sorted fashion. The key of the map is the t member of the QCPCurveData instance. This is the container in which QCPCurve holds its data. \see QCPCurveData, QCPCurve::setData */ typedef QMap QCPCurveDataMap; typedef QMapIterator QCPCurveDataMapIterator; typedef QMutableMapIterator QCPCurveDataMutableMapIterator; class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) /// \endcond public: /*! Defines how the curve's line is represented visually in the plot. The line is drawn with the current pen of the curve (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) ,lsLine ///< Data points are connected with a straight line }; explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPCurve(); // getters: QCPCurveDataMap *data() const { return mData; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } LineStyle lineStyle() const { return mLineStyle; } // setters: void setData(QCPCurveDataMap *data, bool copy=false); void setData(const QVector &t, const QVector &key, const QVector &value); void setData(const QVector &key, const QVector &value); void setScatterStyle(const QCPScatterStyle &style); void setLineStyle(LineStyle style); // non-property methods: void addData(const QCPCurveDataMap &dataMap); void addData(const QCPCurveData &data); void addData(double t, double key, double value); void addData(double key, double value); void addData(const QVector &ts, const QVector &keys, const QVector &values); void removeDataBefore(double t); void removeDataAfter(double t); void removeData(double fromt, double tot); void removeData(double t); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPCurveDataMap *mData; QCPScatterStyle mScatterStyle; LineStyle mLineStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // introduced virtual methods: virtual void drawScatterPlot(QCPPainter *painter, const QVector *pointData) const; // non-virtual methods: void getCurveData(QVector *lineData) const; int getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const; QPointF getOptimizedPoint(int prevRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; QVector getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; bool mayTraverse(int prevRegion, int currentRegion) const; bool getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const; void getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector &beforeTraverse, QVector &afterTraverse) const; double pointDistance(const QPointF &pixelPoint) const; friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPBarsGroup : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) Q_PROPERTY(double spacing READ spacing WRITE setSpacing) /// \endcond public: /*! Defines the ways the spacing between bars in the group can be specified. Thus it defines what the number passed to \ref setSpacing actually means. \see setSpacingType, setSpacing */ enum SpacingType { stAbsolute ///< Bar spacing is in absolute pixels ,stAxisRectRatio ///< Bar spacing is given by a fraction of the axis rect size ,stPlotCoords ///< Bar spacing is in key coordinates and thus scales with the key axis range }; QCPBarsGroup(QCustomPlot *parentPlot); ~QCPBarsGroup(); // getters: SpacingType spacingType() const { return mSpacingType; } double spacing() const { return mSpacing; } // setters: void setSpacingType(SpacingType spacingType); void setSpacing(double spacing); // non-virtual methods: QList bars() const { return mBars; } QCPBars* bars(int index) const; int size() const { return mBars.size(); } bool isEmpty() const { return mBars.isEmpty(); } void clear(); bool contains(QCPBars *bars) const { return mBars.contains(bars); } void append(QCPBars *bars); void insert(int i, QCPBars *bars); void remove(QCPBars *bars); protected: // non-property members: QCustomPlot *mParentPlot; SpacingType mSpacingType; double mSpacing; QList mBars; // non-virtual methods: void registerBars(QCPBars *bars); void unregisterBars(QCPBars *bars); // virtual methods: double keyPixelOffset(const QCPBars *bars, double keyCoord); double getPixelSpacing(const QCPBars *bars, double keyCoord); private: Q_DISABLE_COPY(QCPBarsGroup) friend class QCPBars; }; class QCP_LIB_DECL QCPBarData { public: QCPBarData(); QCPBarData(double key, double value); double key, value; }; Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE); /*! \typedef QCPBarDataMap Container for storing \ref QCPBarData items in a sorted fashion. The key of the map is the key member of the QCPBarData instance. This is the container in which QCPBars holds its data. \see QCPBarData, QCPBars::setData */ typedef QMap QCPBarDataMap; typedef QMapIterator QCPBarDataMapIterator; typedef QMutableMapIterator QCPBarDataMutableMapIterator; class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType) Q_PROPERTY(QCPBarsGroup* barsGroup READ barsGroup WRITE setBarsGroup) Q_PROPERTY(double baseValue READ baseValue WRITE setBaseValue) Q_PROPERTY(QCPBars* barBelow READ barBelow) Q_PROPERTY(QCPBars* barAbove READ barAbove) /// \endcond public: /*! Defines the ways the width of the bar can be specified. Thus it defines what the number passed to \ref setWidth actually means. \see setWidthType, setWidth */ enum WidthType { wtAbsolute ///< Bar width is in absolute pixels ,wtAxisRectRatio ///< Bar width is given by a fraction of the axis rect size ,wtPlotCoords ///< Bar width is in key coordinates and thus scales with the key axis range }; Q_ENUMS(WidthType) explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPBars(); // getters: double width() const { return mWidth; } WidthType widthType() const { return mWidthType; } QCPBarsGroup *barsGroup() const { return mBarsGroup; } double baseValue() const { return mBaseValue; } QCPBars *barBelow() const { return mBarBelow.data(); } QCPBars *barAbove() const { return mBarAbove.data(); } QCPBarDataMap *data() const { return mData; } // setters: void setWidth(double width); void setWidthType(WidthType widthType); void setBarsGroup(QCPBarsGroup *barsGroup); void setBaseValue(double baseValue); void setData(QCPBarDataMap *data, bool copy=false); void setData(const QVector &key, const QVector &value); // non-property methods: void moveBelow(QCPBars *bars); void moveAbove(QCPBars *bars); void addData(const QCPBarDataMap &dataMap); void addData(const QCPBarData &data); void addData(double key, double value); void addData(const QVector &keys, const QVector &values); void removeDataBefore(double key); void removeDataAfter(double key); void removeData(double fromKey, double toKey); void removeData(double key); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPBarDataMap *mData; double mWidth; WidthType mWidthType; QCPBarsGroup *mBarsGroup; double mBaseValue; QPointer mBarBelow, mBarAbove; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // non-virtual methods: void getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const; QPolygonF getBarPolygon(double key, double value) const; void getPixelWidth(double key, double &lower, double &upper) const; double getStackedBaseValue(double key, bool positive) const; static void connectBars(QCPBars* lower, QCPBars* upper); friend class QCustomPlot; friend class QCPLegend; friend class QCPBarsGroup; }; /*! \file */ class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(double key READ key WRITE setKey) Q_PROPERTY(double minimum READ minimum WRITE setMinimum) Q_PROPERTY(double lowerQuartile READ lowerQuartile WRITE setLowerQuartile) Q_PROPERTY(double median READ median WRITE setMedian) Q_PROPERTY(double upperQuartile READ upperQuartile WRITE setUpperQuartile) Q_PROPERTY(double maximum READ maximum WRITE setMaximum) Q_PROPERTY(QVector outliers READ outliers WRITE setOutliers) Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen) Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen) Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen) Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) /// \endcond public: explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); // getters: double key() const { return mKey; } double minimum() const { return mMinimum; } double lowerQuartile() const { return mLowerQuartile; } double median() const { return mMedian; } double upperQuartile() const { return mUpperQuartile; } double maximum() const { return mMaximum; } QVector outliers() const { return mOutliers; } double width() const { return mWidth; } double whiskerWidth() const { return mWhiskerWidth; } QPen whiskerPen() const { return mWhiskerPen; } QPen whiskerBarPen() const { return mWhiskerBarPen; } QPen medianPen() const { return mMedianPen; } QCPScatterStyle outlierStyle() const { return mOutlierStyle; } // setters: void setKey(double key); void setMinimum(double value); void setLowerQuartile(double value); void setMedian(double value); void setUpperQuartile(double value); void setMaximum(double value); void setOutliers(const QVector &values); void setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum); void setWidth(double width); void setWhiskerWidth(double width); void setWhiskerPen(const QPen &pen); void setWhiskerBarPen(const QPen &pen); void setMedianPen(const QPen &pen); void setOutlierStyle(const QCPScatterStyle &style); // non-property methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QVector mOutliers; double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; double mWidth; double mWhiskerWidth; QPen mWhiskerPen, mWhiskerBarPen, mMedianPen; QCPScatterStyle mOutlierStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // introduced virtual methods: virtual void drawQuartileBox(QCPPainter *painter, QRectF *quartileBox=0) const; virtual void drawMedian(QCPPainter *painter) const; virtual void drawWhiskers(QCPPainter *painter) const; virtual void drawOutliers(QCPPainter *painter) const; friend class QCustomPlot; friend class QCPLegend; }; class QCP_LIB_DECL QCPColorMapData { public: QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); ~QCPColorMapData(); QCPColorMapData(const QCPColorMapData &other); QCPColorMapData &operator=(const QCPColorMapData &other); // getters: int keySize() const { return mKeySize; } int valueSize() const { return mValueSize; } QCPRange keyRange() const { return mKeyRange; } QCPRange valueRange() const { return mValueRange; } QCPRange dataBounds() const { return mDataBounds; } double data(double key, double value); double cell(int keyIndex, int valueIndex); // setters: void setSize(int keySize, int valueSize); void setKeySize(int keySize); void setValueSize(int valueSize); void setRange(const QCPRange &keyRange, const QCPRange &valueRange); void setKeyRange(const QCPRange &keyRange); void setValueRange(const QCPRange &valueRange); void setData(double key, double value, double z); void setCell(int keyIndex, int valueIndex, double z); // non-property methods: void recalculateDataBounds(); void clear(); void fill(double z); bool isEmpty() const { return mIsEmpty; } void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const; void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const; protected: // property members: int mKeySize, mValueSize; QCPRange mKeyRange, mValueRange; bool mIsEmpty; // non-property members: double *mData; QCPRange mDataBounds; bool mDataModified; friend class QCPColorMap; }; class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) /// \endcond public: explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPColorMap(); // getters: QCPColorMapData *data() const { return mMapData; } QCPRange dataRange() const { return mDataRange; } QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } bool interpolate() const { return mInterpolate; } bool tightBoundary() const { return mTightBoundary; } QCPColorGradient gradient() const { return mGradient; } QCPColorScale *colorScale() const { return mColorScale.data(); } // setters: void setData(QCPColorMapData *data, bool copy=false); Q_SLOT void setDataRange(const QCPRange &dataRange); Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); Q_SLOT void setGradient(const QCPColorGradient &gradient); void setInterpolate(bool enabled); void setTightBoundary(bool enabled); void setColorScale(QCPColorScale *colorScale); // non-property methods: void rescaleDataRange(bool recalculateDataBounds=false); Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void dataRangeChanged(QCPRange newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); void gradientChanged(QCPColorGradient newGradient); protected: // property members: QCPRange mDataRange; QCPAxis::ScaleType mDataScaleType; QCPColorMapData *mMapData; QCPColorGradient mGradient; bool mInterpolate; bool mTightBoundary; QPointer mColorScale; // non-property members: QImage mMapImage, mUndersampledMapImage; QPixmap mLegendIcon; bool mMapImageInvalidated; // introduced virtual methods: virtual void updateMapImage(); // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPFinancialData { public: QCPFinancialData(); QCPFinancialData(double key, double open, double high, double low, double close); double key, open, high, low, close; }; Q_DECLARE_TYPEINFO(QCPFinancialData, Q_MOVABLE_TYPE); /*! \typedef QCPFinancialDataMap Container for storing \ref QCPFinancialData items in a sorted fashion. The key of the map is the key member of the QCPFinancialData instance. This is the container in which QCPFinancial holds its data. \see QCPFinancial, QCPFinancial::setData */ typedef QMap QCPFinancialDataMap; typedef QMapIterator QCPFinancialDataMapIterator; typedef QMutableMapIterator QCPFinancialDataMutableMapIterator; class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle) Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored) Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive) Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative) Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) /// \endcond public: /*! Defines the possible representations of OHLC data in the plot. \see setChartStyle */ enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation ,csCandlestick ///< Candlestick representation }; Q_ENUMS(ChartStyle) explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPFinancial(); // getters: QCPFinancialDataMap *data() const { return mData; } ChartStyle chartStyle() const { return mChartStyle; } double width() const { return mWidth; } bool twoColored() const { return mTwoColored; } QBrush brushPositive() const { return mBrushPositive; } QBrush brushNegative() const { return mBrushNegative; } QPen penPositive() const { return mPenPositive; } QPen penNegative() const { return mPenNegative; } // setters: void setData(QCPFinancialDataMap *data, bool copy=false); void setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close); void setChartStyle(ChartStyle style); void setWidth(double width); void setTwoColored(bool twoColored); void setBrushPositive(const QBrush &brush); void setBrushNegative(const QBrush &brush); void setPenPositive(const QPen &pen); void setPenNegative(const QPen &pen); // non-property methods: void addData(const QCPFinancialDataMap &dataMap); void addData(const QCPFinancialData &data); void addData(double key, double open, double high, double low, double close); void addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close); void removeDataBefore(double key); void removeDataAfter(double key); void removeData(double fromKey, double toKey); void removeData(double key); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // static methods: static QCPFinancialDataMap timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); protected: // property members: QCPFinancialDataMap *mData; ChartStyle mChartStyle; double mWidth; bool mTwoColored; QBrush mBrushPositive, mBrushNegative; QPen mPenPositive, mPenNegative; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // non-virtual methods: void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; void getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const; friend class QCustomPlot; friend class QCPLegend; }; class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: QCPItemStraightLine(QCustomPlot *parentPlot); virtual ~QCPItemStraightLine(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const point1; QCPItemPosition * const point2; protected: // property members: QPen mPen, mSelectedPen; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: double distToStraightLine(const QVector2D &point1, const QVector2D &vec, const QVector2D &point) const; QLineF getRectClippedStraightLine(const QVector2D &point1, const QVector2D &vec, const QRect &rect) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: QCPItemLine(QCustomPlot *parentPlot); virtual ~QCPItemLine(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QCPLineEnding head() const { return mHead; } QCPLineEnding tail() const { return mTail; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setHead(const QCPLineEnding &head); void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const start; QCPItemPosition * const end; protected: // property members: QPen mPen, mSelectedPen; QCPLineEnding mHead, mTail; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: QCPItemCurve(QCustomPlot *parentPlot); virtual ~QCPItemCurve(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QCPLineEnding head() const { return mHead; } QCPLineEnding tail() const { return mTail; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setHead(const QCPLineEnding &head); void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const start; QCPItemPosition * const startDir; QCPItemPosition * const endDir; QCPItemPosition * const end; protected: // property members: QPen mPen, mSelectedPen; QCPLineEnding mHead, mTail; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QPen mainPen() const; }; class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: QCPItemRect(QCustomPlot *parentPlot); virtual ~QCPItemRect(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) Q_PROPERTY(double rotation READ rotation WRITE setRotation) Q_PROPERTY(QMargins padding READ padding WRITE setPadding) /// \endcond public: QCPItemText(QCustomPlot *parentPlot); virtual ~QCPItemText(); // getters: QColor color() const { return mColor; } QColor selectedColor() const { return mSelectedColor; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } QFont font() const { return mFont; } QFont selectedFont() const { return mSelectedFont; } QString text() const { return mText; } Qt::Alignment positionAlignment() const { return mPositionAlignment; } Qt::Alignment textAlignment() const { return mTextAlignment; } double rotation() const { return mRotation; } QMargins padding() const { return mPadding; } // setters; void setColor(const QColor &color); void setSelectedColor(const QColor &color); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setFont(const QFont &font); void setSelectedFont(const QFont &font); void setText(const QString &text); void setPositionAlignment(Qt::Alignment alignment); void setTextAlignment(Qt::Alignment alignment); void setRotation(double degrees); void setPadding(const QMargins &padding); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const position; QCPItemAnchor * const topLeft; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottomRight; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QColor mColor, mSelectedColor; QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; QFont mFont, mSelectedFont; QString mText; Qt::Alignment mPositionAlignment; Qt::Alignment mTextAlignment; double mRotation; QMargins mPadding; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; QFont mainFont() const; QColor mainColor() const; QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: QCPItemEllipse(QCustomPlot *parentPlot); virtual ~QCPItemEllipse(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const topLeftRim; QCPItemAnchor * const top; QCPItemAnchor * const topRightRim; QCPItemAnchor * const right; QCPItemAnchor * const bottomRightRim; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeftRim; QCPItemAnchor * const left; QCPItemAnchor * const center; protected: enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) Q_PROPERTY(bool scaled READ scaled WRITE setScaled) Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: QCPItemPixmap(QCustomPlot *parentPlot); virtual ~QCPItemPixmap(); // getters: QPixmap pixmap() const { return mPixmap; } bool scaled() const { return mScaled; } Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } Qt::TransformationMode transformationMode() const { return mTransformationMode; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } // setters; void setPixmap(const QPixmap &pixmap); void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QPixmap mPixmap; QPixmap mScaledPixmap; bool mScaled; Qt::AspectRatioMode mAspectRatioMode; Qt::TransformationMode mTransformationMode; QPen mPen, mSelectedPen; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(double size READ size WRITE setSize) Q_PROPERTY(TracerStyle style READ style WRITE setStyle) Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) /// \endcond public: /*! The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. \see setStyle */ enum TracerStyle { tsNone ///< The tracer is not visible ,tsPlus ///< A plus shaped crosshair with limited size ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect ,tsCircle ///< A circle ,tsSquare ///< A square }; Q_ENUMS(TracerStyle) QCPItemTracer(QCustomPlot *parentPlot); virtual ~QCPItemTracer(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } double size() const { return mSize; } TracerStyle style() const { return mStyle; } QCPGraph *graph() const { return mGraph; } double graphKey() const { return mGraphKey; } bool interpolating() const { return mInterpolating; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setSize(double size); void setStyle(TracerStyle style); void setGraph(QCPGraph *graph); void setGraphKey(double key); void setInterpolating(bool enabled); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: void updatePosition(); QCPItemPosition * const position; protected: // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; double mSize; TracerStyle mStyle; QCPGraph *mGraph; double mGraphKey; bool mInterpolating; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(double length READ length WRITE setLength) Q_PROPERTY(BracketStyle style READ style WRITE setStyle) /// \endcond public: enum BracketStyle { bsSquare ///< A brace with angled edges ,bsRound ///< A brace with round edges ,bsCurly ///< A curly brace ,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression }; QCPItemBracket(QCustomPlot *parentPlot); virtual ~QCPItemBracket(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } double length() const { return mLength; } BracketStyle style() const { return mStyle; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setLength(double length); void setStyle(BracketStyle style); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const left; QCPItemPosition * const right; QCPItemAnchor * const center; protected: // property members: enum AnchorIndex {aiCenter}; QPen mPen, mSelectedPen; double mLength; BracketStyle mStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; }; #endif // QCUSTOMPLOT_H thermald-1.5/tools/thermal_monitor/qcustomplot/qcustomplot.cpp0000664000175000017500000317503512661205366023703 0ustar kingking/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2015 Emanuel Eichhammer ** ** ** ** 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 http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 25.04.15 ** ** Version: 1.3.1 ** ****************************************************************************/ #include "qcustomplot.h" //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPainter //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPainter \brief QPainter subclass used internally This QPainter subclass is used to provide some extended functionality e.g. for tweaking position consistency between antialiased and non-antialiased painting. Further it provides workarounds for QPainter quirks. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and restore. So while it is possible to pass a QCPPainter instance to a function that expects a QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because it will call the base class implementations of the functions actually hidden by QCPPainter). */ /*! Creates a new QCPPainter instance and sets default values */ QCPPainter::QCPPainter() : QPainter(), mModes(pmDefault), mIsAntialiasing(false) { // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and // a call to begin() will follow } /*! Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just like the analogous QPainter constructor, begins painting on \a device immediately. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. */ QCPPainter::QCPPainter(QPaintDevice *device) : QPainter(device), mModes(pmDefault), mIsAntialiasing(false) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. if (isActive()) setRenderHint(QPainter::NonCosmeticDefaultPen); #endif } QCPPainter::~QCPPainter() { } /*! Sets the pen of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QPen &pen) { QPainter::setPen(pen); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QColor &color) { QPainter::setPen(color); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(Qt::PenStyle penStyle) { QPainter::setPen(penStyle); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to integer coordinates and then passes it to the original drawLine. \note this function hides the non-virtual base class implementation. */ void QCPPainter::drawLine(const QLineF &line) { if (mIsAntialiasing || mModes.testFlag(pmVectorized)) QPainter::drawLine(line); else QPainter::drawLine(line.toLine()); } /*! Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for AA/Non-AA painting). */ void QCPPainter::setAntialiasing(bool enabled) { setRenderHint(QPainter::Antialiasing, enabled); if (mIsAntialiasing != enabled) { mIsAntialiasing = enabled; if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs { if (mIsAntialiasing) translate(0.5, 0.5); else translate(-0.5, -0.5); } } } /*! Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setModes(QCPPainter::PainterModes modes) { mModes = modes; } /*! Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that behaviour. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets the render hint as appropriate. \note this function hides the non-virtual base class implementation. */ bool QCPPainter::begin(QPaintDevice *device) { bool result = QPainter::begin(device); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. if (result) setRenderHint(QPainter::NonCosmeticDefaultPen); #endif return result; } /*! \overload Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) { if (!enabled && mModes.testFlag(mode)) mModes &= ~mode; else if (enabled && !mModes.testFlag(mode)) mModes |= mode; } /*! Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. \note this function hides the non-virtual base class implementation. \see restore */ void QCPPainter::save() { mAntialiasingStack.push(mIsAntialiasing); QPainter::save(); } /*! Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. \note this function hides the non-virtual base class implementation. \see save */ void QCPPainter::restore() { if (!mAntialiasingStack.isEmpty()) mIsAntialiasing = mAntialiasingStack.pop(); else qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; QPainter::restore(); } /*! Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen overrides when the \ref pmNonCosmetic mode is set. */ void QCPPainter::makeNonCosmetic() { if (qFuzzyIsNull(pen().widthF())) { QPen p = pen(); p.setWidth(1); QPainter::setPen(p); } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPScatterStyle //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPScatterStyle \brief Represents the visual appearance of scatter points This class holds information about shape, color and size of scatter points. In plottables like QCPGraph it is used to store how scatter points shall be drawn. For example, \ref QCPGraph::setScatterStyle takes a QCPScatterStyle instance. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can be controlled with \ref setSize. \section QCPScatterStyle-defining Specifying a scatter style You can set all these configurations either by calling the respective functions on an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1 Or you can use one of the various constructors that take different parameter combinations, making it easy to specify a scatter style in a single call, like so: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2 \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref isPenDefined will return false. It leads to scatter points that inherit the pen from the plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes it very convenient to set up typical scatter settings: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size) constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref ScatterShape, where actually a QCPScatterStyle is expected. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref setCustomPath function or call the constructor that takes a painter path. The scatter shape will automatically be set to \ref ssCustom. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap. Note that \ref setSize does not influence the appearance of the pixmap. */ /* start documentation of inline functions */ /*! \fn bool QCPScatterStyle::isNone() const Returns whether the scatter shape is \ref ssNone. \see setShape */ /*! \fn bool QCPScatterStyle::isPenDefined() const Returns whether a pen has been defined for this scatter style. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is left undefined, the scatter color will be inherited from the plottable that uses this scatter style. \see setPen */ /* end documentation of inline functions */ /*! Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited from the plottable that uses this scatter style. */ QCPScatterStyle::QCPScatterStyle() : mSize(6), mShape(ssNone), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or brush is defined. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited from the plottable that uses this scatter style. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : mSize(size), mShape(shape), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, and size to \a size. No brush is defined, i.e. the scatter point will not be filled. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(Qt::NoBrush), mPenDefined(true) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, the brush color to \a fill (with a solid pattern), and size to \a size. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(QBrush(fill)), mPenDefined(true) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the brush to \a brush, and size to \a size. \warning In some cases it might be tempting to directly use a pen style like Qt::NoPen as \a pen and a color like Qt::blue as \a brush. Notice however, that the corresponding call\n QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)\n doesn't necessarily lead C++ to use this constructor in some cases, but might mistake Qt::NoPen for a QColor and use the \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) constructor instead (which will lead to an unexpected look of the scatter points). To prevent this, be more explicit with the parameter types. For example, use QBrush(Qt::blue) instead of just Qt::blue, to clearly point out to the compiler that this constructor is wanted. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) : mSize(size), mShape(shape), mPen(pen), mBrush(brush), mPenDefined(pen.style() != Qt::NoPen) { } /*! Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape is set to \ref ssPixmap. */ QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : mSize(5), mShape(ssPixmap), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPixmap(pixmap), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The scatter shape is set to \ref ssCustom. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly different meaning than for built-in scatter points: The custom path will be drawn scaled by a factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its natural size by default. To double the size of the path for example, set \a size to 12. */ QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) : mSize(size), mShape(ssCustom), mPen(pen), mBrush(brush), mCustomPath(customPath), mPenDefined(pen.style() != Qt::NoPen) { } /*! Sets the size (pixel diameter) of the drawn scatter points to \a size. \see setShape */ void QCPScatterStyle::setSize(double size) { mSize = size; } /*! Sets the shape to \a shape. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref ssPixmap and \ref ssCustom, respectively. \see setSize */ void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape) { mShape = shape; } /*! Sets the pen that will be used to draw scatter points to \a pen. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after a call to this function, even if \a pen is Qt::NoPen. \see setBrush */ void QCPScatterStyle::setPen(const QPen &pen) { mPenDefined = true; mPen = pen; } /*! Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does. \see setPen */ void QCPScatterStyle::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the pixmap that will be drawn as scatter point to \a pixmap. Note that \ref setSize does not influence the appearance of the pixmap. The scatter shape is automatically set to \ref ssPixmap. */ void QCPScatterStyle::setPixmap(const QPixmap &pixmap) { setShape(ssPixmap); mPixmap = pixmap; } /*! Sets the custom shape that will be drawn as scatter point to \a customPath. The scatter shape is automatically set to \ref ssCustom. */ void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) { setShape(ssCustom); mCustomPath = customPath; } /*! Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead. This function is used by plottables (or any class that wants to draw scatters) just before a number of scatters with this style shall be drawn with the \a painter. \see drawShape */ void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const { painter->setPen(mPenDefined ? mPen : defaultPen); painter->setBrush(mBrush); } /*! Draws the scatter shape with \a painter at position \a pos. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be called before scatter points are drawn with \ref drawShape. \see applyTo */ void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const { drawShape(painter, pos.x(), pos.y()); } /*! \overload Draws the scatter shape with \a painter at position \a x and \a y. */ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const { double w = mSize/2.0; switch (mShape) { case ssNone: break; case ssDot: { painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y)); break; } case ssCross: { painter->drawLine(QLineF(x-w, y-w, x+w, y+w)); painter->drawLine(QLineF(x-w, y+w, x+w, y-w)); break; } case ssPlus: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); break; } case ssCircle: { painter->drawEllipse(QPointF(x , y), w, w); break; } case ssDisc: { QBrush b = painter->brush(); painter->setBrush(painter->pen().color()); painter->drawEllipse(QPointF(x , y), w, w); painter->setBrush(b); break; } case ssSquare: { painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssDiamond: { painter->drawLine(QLineF(x-w, y, x, y-w)); painter->drawLine(QLineF( x, y-w, x+w, y)); painter->drawLine(QLineF(x+w, y, x, y+w)); painter->drawLine(QLineF( x, y+w, x-w, y)); break; } case ssStar: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707)); painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707)); break; } case ssTriangle: { painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w)); painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w)); painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w)); break; } case ssTriangleInverted: { painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w)); painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w)); painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w)); break; } case ssCrossSquare: { painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95)); painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w)); painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssPlusSquare: { painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssCrossCircle: { painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670)); painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPlusCircle: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPeace: { painter->drawLine(QLineF(x, y-w, x, y+w)); painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707)); painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPixmap: { painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap); break; } case ssCustom: { QTransform oldTransform = painter->transform(); painter->translate(x, y); painter->scale(mSize/6.0, mSize/6.0); painter->drawPath(mCustomPath); painter->setTransform(oldTransform); break; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayer \brief A layer that may contain objects, to control the rendering order The Layering system of QCustomPlot is the mechanism to control the rendering order of the elements inside the plot. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer, QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers bottom to top and successively draws the layerables of the layers. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base class from which almost all visible objects derive, like axes, grids, graphs, items, etc. Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in that order). The top two layers "axes" and "legend" contain the default axes and legend, so they will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of course, the layer affiliation of the individual objects can be changed as required (\ref QCPLayerable::setLayer). Controlling the ordering of objects is easy: Create a new layer in the position you want it to be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will be placed on the new layer automatically, due to the current layer setting. Alternatively you could have also ignored the current layer setting and just moved the objects with QCPLayerable::setLayer to the desired layer after creating them. It is also possible to move whole layers. For example, If you want the grid to be shown in front of all plottables/items on the "main" layer, just move it above "main" with QCustomPlot::moveLayer. The rendering order within one layer is simply by order of creation or insertion. The item created last (or added last to the layer), is drawn on top of all other objects on that layer. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below the deleted layer, see QCustomPlot::removeLayer. */ /* start documentation of inline functions */ /*! \fn QList QCPLayer::children() const Returns a list of all layerables on this layer. The order corresponds to the rendering order: layerables with higher indices are drawn above layerables with lower indices. */ /*! \fn int QCPLayer::index() const Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be accessed via \ref QCustomPlot::layer. Layers with higher indices will be drawn above layers with lower indices. */ /* end documentation of inline functions */ /*! Creates a new QCPLayer instance. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. This check is only performed by \ref QCustomPlot::addLayer. */ QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : QObject(parentPlot), mParentPlot(parentPlot), mName(layerName), mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function mVisible(true) { // Note: no need to make sure layerName is unique, because layer // management is done with QCustomPlot functions. } QCPLayer::~QCPLayer() { // If child layerables are still on this layer, detach them, so they don't try to reach back to this // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) while (!mChildren.isEmpty()) mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() if (mParentPlot->currentLayer() == this) qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; } /*! Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this layer will be invisible. This function doesn't change the visibility property of the layerables (\ref QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the visibility of the parent layer into account. */ void QCPLayer::setVisible(bool visible) { mVisible = visible; } /*! \internal Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will be prepended to the list, i.e. be drawn beneath the other layerables already in the list. This function does not change the \a mLayer member of \a layerable to this layer. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) \see removeChild */ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) { if (!mChildren.contains(layerable)) { if (prepend) mChildren.prepend(layerable); else mChildren.append(layerable); } else qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); } /*! \internal Removes the \a layerable from the list of this layer. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) \see addChild */ void QCPLayer::removeChild(QCPLayerable *layerable) { if (!mChildren.removeOne(layerable)) qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayerable //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayerable \brief Base class for all drawable objects This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid etc. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking the layers accordingly. For details about the layering mechanism, see the QCPLayer documentation. */ /* start documentation of inline functions */ /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const Returns the parent layerable of this layerable. The parent layerable is used to provide visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables only get drawn if their parent layerables are visible, too. Note that a parent layerable is not necessarily also the QObject parent for memory management. Further, a layerable doesn't always have a parent layerable, so this function may return 0. A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be set manually by the user. */ /* end documentation of inline functions */ /* start documentation of pure virtual functions */ /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 \internal This function applies the default antialiasing setting to the specified \a painter, using the function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing setting may be specified individually, this function should set the antialiasing state of the most prominent entity. In this case however, the \ref draw function usually calls the specialized versions of this function before drawing each entity, effectively overriding the setting of the default antialiasing hint. First example: QCPGraph has multiple entities that have an antialiasing setting: The graph line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased, QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw calls the respective specialized applyAntialiasingHint function. Second example: QCPItemLine consists only of a line so there is only one antialiasing setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the respective layerable subclass.) Consequently it only has the normal QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to care about setting any antialiasing states, because the default antialiasing hint is already set on the painter when the \ref draw function is called, and that's the state it wants to draw the line with. */ /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 \internal This function draws the layerable with the specified \a painter. It is only called by QCustomPlot, if the layerable is visible (\ref setVisible). Before this function is called, the painter's antialiasing state is set via \ref applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was set to \ref clipRect. */ /* end documentation of pure virtual functions */ /* start documentation of signals */ /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to a different layer. \see setLayer */ /* end documentation of signals */ /*! Creates a new QCPLayerable instance. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the derived classes. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a targetLayer is an empty string, it places itself on the current layer of the plot (see \ref QCustomPlot::setCurrentLayer). It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later time with \ref initializeParentPlot. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents are mainly used to control visibility in a hierarchy of layerables. This means a layerable is only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a plot does. */ QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : QObject(plot), mVisible(true), mParentPlot(plot), mParentLayerable(parentLayerable), mLayer(0), mAntialiased(true) { if (mParentPlot) { if (targetLayer.isEmpty()) setLayer(mParentPlot->currentLayer()); else if (!setLayer(targetLayer)) qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; } } QCPLayerable::~QCPLayerable() { if (mLayer) { mLayer->removeChild(this); mLayer = 0; } } /*! Sets the visibility of this layerable object. If an object is not visible, it will not be drawn on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not possible. */ void QCPLayerable::setVisible(bool on) { mVisible = on; } /*! Sets the \a layer of this layerable object. The object will be placed on top of the other objects already on \a layer. Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::setLayer(QCPLayer *layer) { return moveToLayer(layer, false); } /*! \overload Sets the layer of this layerable object by name Returns true on success, i.e. if \a layerName is a valid layer name. */ bool QCPLayerable::setLayer(const QString &layerName) { if (!mParentPlot) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } if (QCPLayer *layer = mParentPlot->layer(layerName)) { return setLayer(layer); } else { qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; return false; } } /*! Sets whether this object will be drawn antialiased or not. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPLayerable::setAntialiased(bool enabled) { mAntialiased = enabled; } /*! Returns whether this layerable is visible, taking the visibility of the layerable parent and the visibility of the layer this layerable is on into account. This is the method that is consulted to decide whether a layerable shall be drawn or not. If this layerable has a direct layerable parent (usually set via hierarchies implemented in subclasses, like in the case of QCPLayoutElement), this function returns true only if this layerable has its visibility set to true and the parent layerable's \ref realVisibility returns true. If this layerable doesn't have a direct layerable parent, returns the state of this layerable's visibility. */ bool QCPLayerable::realVisibility() const { return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); } /*! This function is used to decide whether a click hits a layerable object or not. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the shortest pixel distance of this point to the object. If the object is either invisible or the distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the object is not selectable, -1.0 is returned, too. If the object is represented not by single lines but by an area like a \ref QCPItemText or the bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In these cases this function thus returns a constant value greater zero but still below the parent plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99). Providing a constant value for area objects allows selecting line objects even when they are obscured by such area objects, by clicking close to the lines (i.e. closer than 0.99*selectionTolerance). The actual setting of the selection state is not done by this function. This is handled by the parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified via the selectEvent/deselectEvent methods. \a details is an optional output parameter. Every layerable subclass may place any information in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot decides on the basis of this selectTest call, that the object was successfully selected. The subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be placed in \a details. So in the subsequent \ref selectEvent, the decision which part was selected doesn't have to be done a second time for a single selection operation. You may pass 0 as \a details to indicate that you are not interested in those selection details. \see selectEvent, deselectEvent, QCustomPlot::setInteractions */ double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(pos) Q_UNUSED(onlySelectable) Q_UNUSED(details) return -1.0; } /*! \internal Sets the parent plot of this layerable. Use this function once to set the parent plot if you have passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to another one. Note that, unlike when passing a non-null parent plot in the constructor, this function does not make \a parentPlot the QObject-parent of this layerable. If you want this, call QObject::setParent(\a parentPlot) in addition to this function. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to make the layerable appear on the QCustomPlot. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized so they can react accordingly (e.g. also initialize the parent plot of child layerables, like QCPLayout does). */ void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) { if (mParentPlot) { qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; return; } if (!parentPlot) qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; mParentPlot = parentPlot; parentPlotInitialized(mParentPlot); } /*! \internal Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable. The parent layerable has influence on the return value of the \ref realVisibility method. Only layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be drawn. \see realVisibility */ void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) { mParentLayerable = parentLayerable; } /*! \internal Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is false, the object will be appended. Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) { if (layer && !mParentPlot) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } if (layer && layer->parentPlot() != mParentPlot) { qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; return false; } QCPLayer *oldLayer = mLayer; if (mLayer) mLayer->removeChild(this); mLayer = layer; if (mLayer) mLayer->addChild(this, prepend); if (mLayer != oldLayer) emit layerChanged(mLayer); return true; } /*! \internal Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is controlled via \a overrideElement. */ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const { if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) painter->setAntialiasing(false); else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) painter->setAntialiasing(true); else painter->setAntialiasing(localAntialiased); } /*! \internal This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the parent plot is set at a later time. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To propagate the parent plot to all the children of the hierarchy, the top level element then uses this function to pass the parent plot on to its child elements. The default implementation does nothing. \see initializeParentPlot */ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) { Q_UNUSED(parentPlot) } /*! \internal Returns the selection category this layerable shall belong to. The selection category is used in conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and which aren't. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref QCP::iSelectOther. This is what the default implementation returns. \see QCustomPlot::setInteractions */ QCP::Interaction QCPLayerable::selectionCategory() const { return QCP::iSelectOther; } /*! \internal Returns the clipping rectangle of this layerable object. By default, this is the viewport of the parent QCustomPlot. Specific subclasses may reimplement this function to provide different clipping rects. The returned clipping rect is set on the painter before the draw function of the respective object is called. */ QRect QCPLayerable::clipRect() const { if (mParentPlot) return mParentPlot->viewport(); else return QRect(); } /*! \internal This event is called when the layerable shall be selected, as a consequence of a click by the user. Subclasses should react to it by setting their selection state appropriately. The default implementation does nothing. \a event is the mouse event that caused the selection. \a additive indicates, whether the user was holding the multi-select-modifier while performing the selection (see \ref QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled (i.e. become selected when unselected and unselected when selected). Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). The \a details data you output from \ref selectTest is fed back via \a details here. You may use it to transport any kind of information from the selectTest to the possibly subsequent selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need to do the calculation again to find out which part was actually clicked. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must set the value either to true or false, depending on whether the selection state of this layerable was actually changed. For layerables that only are selectable as a whole and not in parts, this is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the layerable was previously unselected and now is switched to the selected state. \see selectTest, deselectEvent */ void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(additive) Q_UNUSED(details) Q_UNUSED(selectionStateChanged) } /*! \internal This event is called when the layerable shall be deselected, either as consequence of a user interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by unsetting their selection appropriately. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must return true or false when the selection state of this layerable has changed or not changed, respectively. \see selectTest, selectEvent */ void QCPLayerable::deselectEvent(bool *selectionStateChanged) { Q_UNUSED(selectionStateChanged) } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPRange //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPRange \brief Represents the range an axis is encompassing. contains a \a lower and \a upper double value and provides convenience input, output and modification functions. \see QCPAxis::setRange */ /*! Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller intervals would cause errors due to the 11-bit exponent of double precision numbers, corresponding to a minimum magnitude of roughly 1e-308. \see validRange, maxRange */ const double QCPRange::minRange = 1e-280; /*! Maximum values (negative and positive) the range will accept in range-changing functions. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers, corresponding to a maximum magnitude of roughly 1e308. Since the number of planck-volumes in the entire visible universe is only ~1e183, this should be enough. \see validRange, minRange */ const double QCPRange::maxRange = 1e250; /*! Constructs a range with \a lower and \a upper set to zero. */ QCPRange::QCPRange() : lower(0), upper(0) { } /*! \overload Constructs a range with the specified \a lower and \a upper values. */ QCPRange::QCPRange(double lower, double upper) : lower(lower), upper(upper) { normalize(); } /*! Returns the size of the range, i.e. \a upper-\a lower */ double QCPRange::size() const { return upper-lower; } /*! Returns the center of the range, i.e. (\a upper+\a lower)*0.5 */ double QCPRange::center() const { return (upper+lower)*0.5; } /*! Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are swapped. */ void QCPRange::normalize() { if (lower > upper) qSwap(lower, upper); } /*! Expands this range such that \a otherRange is contained in the new range. It is assumed that both this range and \a otherRange are normalized (see \ref normalize). If \a otherRange is already inside the current range, this function does nothing. \see expanded */ void QCPRange::expand(const QCPRange &otherRange) { if (lower > otherRange.lower) lower = otherRange.lower; if (upper < otherRange.upper) upper = otherRange.upper; } /*! Returns an expanded range that contains this and \a otherRange. It is assumed that both this range and \a otherRange are normalized (see \ref normalize). \see expand */ QCPRange QCPRange::expanded(const QCPRange &otherRange) const { QCPRange result = *this; result.expand(otherRange); return result; } /*! Returns a sanitized version of the range. Sanitized means for logarithmic scales, that the range won't span the positive and negative sign domain, i.e. contain zero. Further \a lower will always be numerically smaller (or equal) to \a upper. If the original range does span positive and negative sign domains or contains zero, the returned range will try to approximate the original range as good as possible. If the positive interval of the original range is wider than the negative interval, the returned range will only contain the positive interval, with lower bound set to \a rangeFac or \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval is wider than the positive interval, this time by changing the \a upper bound. */ QCPRange QCPRange::sanitizedForLogScale() const { double rangeFac = 1e-3; QCPRange sanitizedRange(lower, upper); sanitizedRange.normalize(); // can't have range spanning negative and positive values in log plot, so change range to fix it //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) { // case lower is 0 if (rangeFac < sanitizedRange.upper*rangeFac) sanitizedRange.lower = rangeFac; else sanitizedRange.lower = sanitizedRange.upper*rangeFac; } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) { // case upper is 0 if (-rangeFac > sanitizedRange.lower*rangeFac) sanitizedRange.upper = -rangeFac; else sanitizedRange.upper = sanitizedRange.lower*rangeFac; } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) { // find out whether negative or positive interval is wider to decide which sign domain will be chosen if (-sanitizedRange.lower > sanitizedRange.upper) { // negative is wider, do same as in case upper is 0 if (-rangeFac > sanitizedRange.lower*rangeFac) sanitizedRange.upper = -rangeFac; else sanitizedRange.upper = sanitizedRange.lower*rangeFac; } else { // positive is wider, do same as in case lower is 0 if (rangeFac < sanitizedRange.upper*rangeFac) sanitizedRange.lower = rangeFac; else sanitizedRange.lower = sanitizedRange.upper*rangeFac; } } // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper= lower && value <= upper; } /*! Checks, whether the specified range is within valid bounds, which are defined as QCPRange::maxRange and QCPRange::minRange. A valid range means: \li range bounds within -maxRange and maxRange \li range size above minRange \li range size below maxRange */ bool QCPRange::validRange(double lower, double upper) { /* return (lower > -maxRange && upper < maxRange && qAbs(lower-upper) > minRange && (lower < -minRange || lower > minRange) && (upper < -minRange || upper > minRange)); */ return (lower > -maxRange && upper < maxRange && qAbs(lower-upper) > minRange && qAbs(lower-upper) < maxRange); } /*! \overload Checks, whether the specified range is within valid bounds, which are defined as QCPRange::maxRange and QCPRange::minRange. A valid range means: \li range bounds within -maxRange and maxRange \li range size above minRange \li range size below maxRange */ bool QCPRange::validRange(const QCPRange &range) { /* return (range.lower > -maxRange && range.upper < maxRange && qAbs(range.lower-range.upper) > minRange && qAbs(range.lower-range.upper) < maxRange && (range.lower < -minRange || range.lower > minRange) && (range.upper < -minRange || range.upper > minRange)); */ return (range.lower > -maxRange && range.upper < maxRange && qAbs(range.lower-range.upper) > minRange && qAbs(range.lower-range.upper) < maxRange); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPMarginGroup //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPMarginGroup \brief A margin group allows synchronization of margin sides if working with multiple layout elements. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that they will all have the same size, based on the largest required margin in the group. \n \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" \n In certain situations it is desirable that margins at specific sides are synchronized across layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will provide a cleaner look to the user if the left and right margins of the two axis rects are of the same size. The left axis of the top axis rect will then be at the same horizontal position as the left axis of the lower axis rect, making them appear aligned. The same applies for the right axes. This is what QCPMarginGroup makes possible. To add/remove a specific side of a layout element to/from a margin group, use the \ref QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call \ref clear, or just delete the margin group. \section QCPMarginGroup-example Example First create a margin group: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1 Then set this group on the layout element sides: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2 Here, we've used the first two axis rects of the plot and synchronized their left margins with each other and their right margins with each other. */ /* start documentation of inline functions */ /*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const Returns a list of all layout elements that have their margin \a side associated with this margin group. */ /* end documentation of inline functions */ /*! Creates a new QCPMarginGroup instance in \a parentPlot. */ QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : QObject(parentPlot), mParentPlot(parentPlot) { mChildren.insert(QCP::msLeft, QList()); mChildren.insert(QCP::msRight, QList()); mChildren.insert(QCP::msTop, QList()); mChildren.insert(QCP::msBottom, QList()); } QCPMarginGroup::~QCPMarginGroup() { clear(); } /*! Returns whether this margin group is empty. If this function returns true, no layout elements use this margin group to synchronize margin sides. */ bool QCPMarginGroup::isEmpty() const { QHashIterator > it(mChildren); while (it.hasNext()) { it.next(); if (!it.value().isEmpty()) return false; } return true; } /*! Clears this margin group. The synchronization of the margin sides that use this margin group is lifted and they will use their individual margin sizes again. */ void QCPMarginGroup::clear() { // make all children remove themselves from this margin group: QHashIterator > it(mChildren); while (it.hasNext()) { it.next(); const QList elements = it.value(); for (int i=elements.size()-1; i>=0; --i) elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild } } /*! \internal Returns the synchronized common margin for \a side. This is the margin value that will be used by the layout element on the respective side, if it is part of this margin group. The common margin is calculated by requesting the automatic margin (\ref QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into account, too.) */ int QCPMarginGroup::commonMargin(QCP::MarginSide side) const { // query all automatic margins of the layout elements in this margin group side and find maximum: int result = 0; const QList elements = mChildren.value(side); for (int i=0; iautoMargins().testFlag(side)) continue; int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); if (m > result) result = m; } return result; } /*! \internal Adds \a element to the internal list of child elements, for the margin \a side. This function does not modify the margin group property of \a element. */ void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) { if (!mChildren[side].contains(element)) mChildren[side].append(element); else qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); } /*! \internal Removes \a element from the internal list of child elements, for the margin \a side. This function does not modify the margin group property of \a element. */ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) { if (!mChildren[side].removeOne(element)) qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutElement //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutElement \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference between outer and inner rect is called its margin. The margin can either be set to automatic or manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, the layout element subclass will control the value itself (via \ref calculateAutoMargin). Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are invisible by themselves, because they don't draw anything. Their only purpose is to manage the position and size of other layout elements. This category of layout elements usually use QCPLayout as base class. Then there is the category of layout elements which actually draw something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does not necessarily mean that the latter category can't have child layout elements. QCPLegend for instance, actually derives from QCPLayoutGrid and the individual legend items are child layout elements in the grid layout. */ /* start documentation of inline functions */ /*! \fn QCPLayout *QCPLayoutElement::layout() const Returns the parent layout of this layout element. */ /*! \fn QRect QCPLayoutElement::rect() const Returns the inner rect of this layout element. The inner rect is the outer rect (\ref setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). In some cases, the area between outer and inner rect is left blank. In other cases the margin area is used to display peripheral graphics while the main content is in the inner rect. This is where automatic margin calculation becomes interesting because it allows the layout element to adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if \ref setAutoMargins is enabled) according to the space required by the labels of the axes. */ /*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event) This event is called, if the mouse was pressed while being inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event) This event is called, if the mouse is moved inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event) This event is called, if the mouse was previously pressed inside the outer rect of this layout element and is now released. */ /*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event) This event is called, if the mouse is double-clicked inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event) This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this layout element. */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutElement and sets default values. */ QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) mParentLayout(0), mMinimumSize(), mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), mRect(0, 0, 0, 0), mOuterRect(0, 0, 0, 0), mMargins(0, 0, 0, 0), mMinimumMargins(0, 0, 0, 0), mAutoMargins(QCP::msAll) { } QCPLayoutElement::~QCPLayoutElement() { setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any // unregister at layout: if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor mParentLayout->take(this); } /*! Sets the outer rect of this layout element. If the layout element is inside a layout, the layout sets the position and size of this layout element using this function. Calling this function externally has no effect, since the layout will overwrite any changes to the outer rect upon the next replot. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. \see rect */ void QCPLayoutElement::setOuterRect(const QRect &rect) { if (mOuterRect != rect) { mOuterRect = rect; mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); } } /*! Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all sides, this function is used to manually set the margin on those sides. Sides that are still set to be handled automatically are ignored and may have any value in \a margins. The margin is the distance between the outer rect (controlled by the parent layout via \ref setOuterRect) and the inner \ref rect (which usually contains the main content of this layout element). \see setAutoMargins */ void QCPLayoutElement::setMargins(const QMargins &margins) { if (mMargins != margins) { mMargins = margins; mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); } } /*! If \ref setAutoMargins is enabled on some or all margins, this function is used to provide minimum values for those margins. The minimum values are not enforced on margin sides that were set to be under manual control via \ref setAutoMargins. \see setAutoMargins */ void QCPLayoutElement::setMinimumMargins(const QMargins &margins) { if (mMinimumMargins != margins) { mMinimumMargins = margins; } } /*! Sets on which sides the margin shall be calculated automatically. If a side is calculated automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is set to be controlled manually, the value may be specified with \ref setMargins. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref setMarginGroup), to synchronize (align) it with other layout elements in the plot. \see setMinimumMargins, setMargins */ void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) { mAutoMargins = sides; } /*! Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot propagates the layout's size constraints to the outside by setting its own minimum QWidget size accordingly, so violations of \a size should be exceptions. */ void QCPLayoutElement::setMinimumSize(const QSize &size) { if (mMinimumSize != size) { mMinimumSize = size; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! \overload Sets the minimum size for the inner \ref rect of this layout element. */ void QCPLayoutElement::setMinimumSize(int width, int height) { setMinimumSize(QSize(width, height)); } /*! Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. */ void QCPLayoutElement::setMaximumSize(const QSize &size) { if (mMaximumSize != size) { mMaximumSize = size; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! \overload Sets the maximum size for the inner \ref rect of this layout element. */ void QCPLayoutElement::setMaximumSize(int width, int height) { setMaximumSize(QSize(width, height)); } /*! Sets the margin \a group of the specified margin \a sides. Margin groups allow synchronizing specified margins across layout elements, see the documentation of \ref QCPMarginGroup. To unset the margin group of \a sides, set \a group to 0. Note that margin groups only work for margin sides that are set to automatic (\ref setAutoMargins). */ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group) { QVector sideVector; if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); for (int i=0; iremoveChild(side, this); if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there { mMarginGroups.remove(side); } else // setting to a new group { mMarginGroups[side] = group; group->addChild(side, this); } } } } /*! Updates the layout element and sub-elements. This function is automatically called before every replot by the parent layout element. It is called multiple times, once for every \ref UpdatePhase. The phases are run through in the order of the enum values. For details about what happens at the different phases, see the documentation of \ref UpdatePhase. Layout elements that have child elements should call the \ref update method of their child elements, and pass the current \a phase unchanged. The default implementation executes the automatic margin mechanism in the \ref upMargins phase. Subclasses should make sure to call the base class implementation. */ void QCPLayoutElement::update(UpdatePhase phase) { if (phase == upMargins) { if (mAutoMargins != QCP::msNone) { // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: QMargins newMargins = mMargins; QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; foreach (QCP::MarginSide side, allMarginSides) { if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically { if (mMarginGroups.contains(side)) QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group else QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly // apply minimum margin restrictions: if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); } } setMargins(newMargins); } } } /*! Returns the minimum size this layout element (the inner \ref rect) may be compressed to. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this function to determine the minimum allowed size of this layout element. (A manual minimum size is considered set if it is non-zero.) */ QSize QCPLayoutElement::minimumSizeHint() const { return mMinimumSize; } /*! Returns the maximum size this layout element (the inner \ref rect) may be expanded to. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this function to determine the maximum allowed size of this layout element. (A manual maximum size is considered set if it is smaller than Qt's QWIDGETSIZE_MAX.) */ QSize QCPLayoutElement::maximumSizeHint() const { return mMaximumSize; } /*! Returns a list of all child elements in this layout element. If \a recursive is true, all sub-child elements are included in the list, too. \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have empty cells which yield 0 at the respective index.) */ QList QCPLayoutElement::elements(bool recursive) const { Q_UNUSED(recursive) return QList(); } /*! Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer rect, this method returns a value corresponding to 0.99 times the parent plot's selection tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is true, -1.0 is returned. See \ref QCPLayerable::selectTest for a general explanation of this virtual method. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test behaviour. */ double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable) return -1; if (QRectF(mOuterRect).contains(pos)) { if (mParentPlot) return mParentPlot->selectionTolerance()*0.99; else { qDebug() << Q_FUNC_INFO << "parent plot not defined"; return -1; } } else return -1; } /*! \internal propagates the parent plot initialization to all child elements, by calling \ref QCPLayerable::initializeParentPlot on them. */ void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) { foreach (QCPLayoutElement* el, elements(false)) { if (!el->parentPlot()) el->initializeParentPlot(parentPlot); } } /*! \internal Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the returned value will not be smaller than the specified minimum margin. The default implementation just returns the respective manual margin (\ref setMargins) or the minimum margin, whichever is larger. */ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) { return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayout //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayout \brief The abstract base class for layouts This is an abstract base class for layout elements whose main purpose is to define the position and size of other child layout elements. In most cases, layouts don't draw anything themselves (but there are exceptions to this, e.g. QCPLegend). QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions to this interface which are more specialized to the form of the layout. For example, \ref QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid more conveniently. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its subclasses like QCPLayoutGrid or QCPLayoutInset. For a general introduction to the layout system, see the dedicated documentation page \ref thelayoutsystem "The Layout System". */ /* start documentation of pure virtual functions */ /*! \fn virtual int QCPLayout::elementCount() const = 0 Returns the number of elements/cells in the layout. \see elements, elementAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 Returns the element in the cell with the given \a index. If \a index is invalid, returns 0. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check whether a cell is empty or not. \see elements, elementCount, takeAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 Removes the element with the given \a index from the layout and returns it. If the \a index is invalid or the cell with that index is empty, returns 0. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see elementAt, take */ /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 Removes the specified \a element from the layout and returns true on success. If the \a element isn't in this layout, returns false. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see takeAt */ /* end documentation of pure virtual functions */ /*! Creates an instance of QCPLayout and sets default values. Note that since QCPLayout is an abstract base class, it can't be instantiated directly. */ QCPLayout::QCPLayout() { } /*! First calls the QCPLayoutElement::update base class implementation to update the margins on this layout. Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells. Finally, \ref update is called on all child elements. */ void QCPLayout::update(UpdatePhase phase) { QCPLayoutElement::update(phase); // set child element rects according to layout: if (phase == upLayout) updateLayout(); // propagate update call to child elements: const int elCount = elementCount(); for (int i=0; iupdate(phase); } } /* inherits documentation from base class */ QList QCPLayout::elements(bool recursive) const { const int c = elementCount(); QList result; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) result.reserve(c); #endif for (int i=0; ielements(recursive); } } return result; } /*! Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the default implementation does nothing. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit simplification while QCPLayoutGrid does. */ void QCPLayout::simplify() { } /*! Removes and deletes the element at the provided \a index. Returns true on success. If \a index is invalid or points to an empty cell, returns false. This function internally uses \ref takeAt to remove the element from the layout and then deletes the returned element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see remove, takeAt */ bool QCPLayout::removeAt(int index) { if (QCPLayoutElement *el = takeAt(index)) { delete el; return true; } else return false; } /*! Removes and deletes the provided \a element. Returns true on success. If \a element is not in the layout, returns false. This function internally uses \ref takeAt to remove the element from the layout and then deletes the element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see removeAt, take */ bool QCPLayout::remove(QCPLayoutElement *element) { if (take(element)) { delete element; return true; } else return false; } /*! Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure all empty cells are collapsed. \see remove, removeAt */ void QCPLayout::clear() { for (int i=elementCount()-1; i>=0; --i) { if (elementAt(i)) removeAt(i); } simplify(); } /*! Subclasses call this method to report changed (minimum/maximum) size constraints. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, it may update itself and resize cells accordingly. */ void QCPLayout::sizeConstraintsChanged() const { if (QWidget *w = qobject_cast(parent())) w->updateGeometry(); else if (QCPLayout *l = qobject_cast(parent())) l->sizeConstraintsChanged(); } /*! \internal Subclasses reimplement this method to update the position and sizes of the child elements/cells via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay within that rect. \ref getSectionSizes may help with the reimplementation of this function. \see update */ void QCPLayout::updateLayout() { } /*! \internal Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the \ref QCPLayerable::parentLayerable and the QObject parent to this layout. Further, if \a el didn't previously have a parent plot, calls \ref QCPLayerable::initializeParentPlot on \a el to set the paret plot. This method is used by subclass specific methods that add elements to the layout. Note that this method only changes properties in \a el. The removal from the old layout and the insertion into the new layout must be done additionally. */ void QCPLayout::adoptElement(QCPLayoutElement *el) { if (el) { el->mParentLayout = this; el->setParentLayerable(this); el->setParent(this); if (!el->parentPlot()) el->initializeParentPlot(mParentPlot); } else qDebug() << Q_FUNC_INFO << "Null element passed"; } /*! \internal Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent QCustomPlot. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref take or \ref takeAt). Note that this method only changes properties in \a el. The removal from the old layout must be done additionally. */ void QCPLayout::releaseElement(QCPLayoutElement *el) { if (el) { el->mParentLayout = 0; el->setParentLayerable(0); el->setParent(mParentPlot); // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot } else qDebug() << Q_FUNC_INFO << "Null element passed"; } /*! \internal This is a helper function for the implementation of \ref updateLayout in subclasses. It calculates the sizes of one-dimensional sections with provided constraints on maximum section sizes, minimum section sizes, relative stretch factors and the final total size of all sections. The QVector entries refer to the sections. Thus all QVectors must have the same size. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size imposed, set all vector values to Qt's QWIDGETSIZE_MAX. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, not exceeding the allowed total size is taken to be more important than not going below minimum section sizes.) \a stretchFactors give the relative proportions of the sections to each other. If all sections shall be scaled equally, set all values equal. If the first section shall be double the size of each individual other section, set the first number of \a stretchFactors to double the value of the other individual values (e.g. {2, 1, 1, 1}). \a totalSize is the value that the final section sizes will add up to. Due to rounding, the actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, you could distribute the remaining difference on the sections. The return value is a QVector containing the section sizes. */ QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const { if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) { qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; return QVector(); } if (stretchFactors.isEmpty()) return QVector(); int sectionCount = stretchFactors.size(); QVector sectionSizes(sectionCount); // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): int minSizeSum = 0; for (int i=0; i minimumLockedSections; QList unfinishedSections; for (int i=0; i result(sectionCount); for (int i=0; i= 0 && row < mElements.size()) { if (column >= 0 && column < mElements.first().size()) { if (QCPLayoutElement *result = mElements.at(row).at(column)) return result; else qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; } else qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; } else qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; return 0; } /*! Returns the number of rows in the layout. \see columnCount */ int QCPLayoutGrid::rowCount() const { return mElements.size(); } /*! Returns the number of columns in the layout. \see rowCount */ int QCPLayoutGrid::columnCount() const { if (mElements.size() > 0) return mElements.first().size(); else return 0; } /*! Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it is first removed from there. If \a row or \a column don't exist yet, the layout is expanded accordingly. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column didn't already have an element. \see element, hasElement, take, remove */ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) { if (element) { if (!hasElement(row, column)) { if (element->layout()) // remove from old layout first element->layout()->take(element); expandTo(row+1, column+1); mElements[row][column] = element; adoptElement(element); return true; } else qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; } else qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; return false; } /*! Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't empty. \see element */ bool QCPLayoutGrid::hasElement(int row, int column) { if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) return mElements.at(row).at(column); else return false; } /*! Sets the stretch \a factor of \a column. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactors, setRowStretchFactor */ void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) { if (column >= 0 && column < columnCount()) { if (factor > 0) mColumnStretchFactors[column] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; } else qDebug() << Q_FUNC_INFO << "Invalid column:" << column; } /*! Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactor, setRowStretchFactors */ void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) { if (factors.size() == mColumnStretchFactors.size()) { mColumnStretchFactors = factors; for (int i=0; i= 0 && row < rowCount()) { if (factor > 0) mRowStretchFactors[row] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; } else qDebug() << Q_FUNC_INFO << "Invalid row:" << row; } /*! Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setRowStretchFactor, setColumnStretchFactors */ void QCPLayoutGrid::setRowStretchFactors(const QList &factors) { if (factors.size() == mRowStretchFactors.size()) { mRowStretchFactors = factors; for (int i=0; i()); mRowStretchFactors.append(1); } // go through rows and expand columns as necessary: int newColCount = qMax(columnCount(), newColumnCount); for (int i=0; i rowCount()) newIndex = rowCount(); mRowStretchFactors.insert(newIndex, 1); QList newRow; for (int col=0; col columnCount()) newIndex = columnCount(); mColumnStretchFactors.insert(newIndex, 1); for (int row=0; row minColWidths, minRowHeights, maxColWidths, maxRowHeights; getMinimumRowColSizes(&minColWidths, &minRowHeights); getMaximumRowColSizes(&maxColWidths, &maxRowHeights); int totalRowSpacing = (rowCount()-1) * mRowSpacing; int totalColSpacing = (columnCount()-1) * mColumnSpacing; QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); // go through cells and set rects accordingly: int yOffset = mRect.top(); for (int row=0; row 0) yOffset += rowHeights.at(row-1)+mRowSpacing; int xOffset = mRect.left(); for (int col=0; col 0) xOffset += colWidths.at(col-1)+mColumnSpacing; if (mElements.at(row).at(col)) mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); } } } /* inherits documentation from base class */ int QCPLayoutGrid::elementCount() const { return rowCount()*columnCount(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const { if (index >= 0 && index < elementCount()) return mElements.at(index / columnCount()).at(index % columnCount()); else return 0; } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutGrid::takeAt(int index) { if (QCPLayoutElement *el = elementAt(index)) { releaseElement(el); mElements[index / columnCount()][index % columnCount()] = 0; return el; } else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return 0; } } /* inherits documentation from base class */ bool QCPLayoutGrid::take(QCPLayoutElement *element) { if (element) { for (int i=0; i QCPLayoutGrid::elements(bool recursive) const { QList result; int colC = columnCount(); int rowC = rowCount(); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) result.reserve(colC*rowC); #endif for (int row=0; rowelements(recursive); } } return result; } /*! Simplifies the layout by collapsing rows and columns which only contain empty cells. */ void QCPLayoutGrid::simplify() { // remove rows with only empty cells: for (int row=rowCount()-1; row>=0; --row) { bool hasElements = false; for (int col=0; col=0; --col) { bool hasElements = false; for (int row=0; row minColWidths, minRowHeights; getMinimumRowColSizes(&minColWidths, &minRowHeights); QSize result(0, 0); for (int i=0; i maxColWidths, maxRowHeights; getMaximumRowColSizes(&maxColWidths, &maxRowHeights); QSize result(0, 0); for (int i=0; i *minColWidths, QVector *minRowHeights) const { *minColWidths = QVector(columnCount(), 0); *minRowHeights = QVector(rowCount(), 0); for (int row=0; rowminimumSizeHint(); QSize min = mElements.at(row).at(col)->minimumSize(); QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height()); if (minColWidths->at(col) < final.width()) (*minColWidths)[col] = final.width(); if (minRowHeights->at(row) < final.height()) (*minRowHeights)[row] = final.height(); } } } } /*! \internal Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights respectively. The maximum height of a row is the smallest maximum height of any element in that row. The maximum width of a column is the smallest maximum width of any element in that column. This is a helper function for \ref updateLayout. \see getMinimumRowColSizes */ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const { *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); for (int row=0; rowmaximumSizeHint(); QSize max = mElements.at(row).at(col)->maximumSize(); QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height()); if (maxColWidths->at(col) > final.width()) (*maxColWidths)[col] = final.width(); if (maxRowHeights->at(row) > final.height()) (*maxRowHeights)[row] = final.height(); } } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutInset //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutInset \brief A layout that places child elements aligned to the border or arbitrarily positioned Elements are placed either aligned to the border or at arbitrary position in the area of the layout. Which placement applies is controlled with the \ref InsetPlacement (\ref setInsetPlacement). Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset placement will default to \ref ipBorderAligned and the element will be aligned according to the \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at arbitrary position and size, defined by \a rect. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout. */ /* start documentation of inline functions */ /*! \fn virtual void QCPLayoutInset::simplify() The QCPInsetLayout does not need simplification since it can never have empty cells due to its linear index structure. This method does nothing. */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutInset and sets default values. */ QCPLayoutInset::QCPLayoutInset() { } QCPLayoutInset::~QCPLayoutInset() { // clear all child layout elements. This is important because only the specific layouts know how // to handle removing elements (clear calls virtual removeAt method to do that). clear(); } /*! Returns the placement type of the element with the specified \a index. */ QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const { if (elementAt(index)) return mInsetPlacement.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return ipFree; } } /*! Returns the alignment of the element with the specified \a index. The alignment only has a meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned. */ Qt::Alignment QCPLayoutInset::insetAlignment(int index) const { if (elementAt(index)) return mInsetAlignment.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return 0; } } /*! Returns the rect of the element with the specified \a index. The rect only has a meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree. */ QRectF QCPLayoutInset::insetRect(int index) const { if (elementAt(index)) return mInsetRect.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return QRectF(); } } /*! Sets the inset placement type of the element with the specified \a index to \a placement. \see InsetPlacement */ void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement) { if (elementAt(index)) mInsetPlacement[index] = placement; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /*! If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function is used to set the alignment of the element with the specified \a index to \a alignment. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. */ void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment) { if (elementAt(index)) mInsetAlignment[index] = alignment; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /*! If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the position and size of the element with the specified \a index to \a rect. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. Note that the minimum and maximum sizes of the embedded element (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced. */ void QCPLayoutInset::setInsetRect(int index, const QRectF &rect) { if (elementAt(index)) mInsetRect[index] = rect; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /* inherits documentation from base class */ void QCPLayoutInset::updateLayout() { for (int i=0; iminimumSizeHint(); QSize maxSizeHint = mElements.at(i)->maximumSizeHint(); finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width()); finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height()); finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width()); finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height()); if (mInsetPlacement.at(i) == ipFree) { insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(), rect().y()+rect().height()*mInsetRect.at(i).y(), rect().width()*mInsetRect.at(i).width(), rect().height()*mInsetRect.at(i).height()); if (insetRect.size().width() < finalMinSize.width()) insetRect.setWidth(finalMinSize.width()); if (insetRect.size().height() < finalMinSize.height()) insetRect.setHeight(finalMinSize.height()); if (insetRect.size().width() > finalMaxSize.width()) insetRect.setWidth(finalMaxSize.width()); if (insetRect.size().height() > finalMaxSize.height()) insetRect.setHeight(finalMaxSize.height()); } else if (mInsetPlacement.at(i) == ipBorderAligned) { insetRect.setSize(finalMinSize); Qt::Alignment al = mInsetAlignment.at(i); if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter } mElements.at(i)->setOuterRect(insetRect); } } /* inherits documentation from base class */ int QCPLayoutInset::elementCount() const { return mElements.size(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::elementAt(int index) const { if (index >= 0 && index < mElements.size()) return mElements.at(index); else return 0; } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::takeAt(int index) { if (QCPLayoutElement *el = elementAt(index)) { releaseElement(el); mElements.removeAt(index); mInsetPlacement.removeAt(index); mInsetAlignment.removeAt(index); mInsetRect.removeAt(index); return el; } else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return 0; } } /* inherits documentation from base class */ bool QCPLayoutInset::take(QCPLayoutElement *element) { if (element) { for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) return mParentPlot->selectionTolerance()*0.99; } return -1; } /*! Adds the specified \a element to the layout as an inset aligned at the border (\ref setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a alignment. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. \see addElement(QCPLayoutElement *element, const QRectF &rect) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) { if (element) { if (element->layout()) // remove from old layout first element->layout()->take(element); mElements.append(element); mInsetPlacement.append(ipBorderAligned); mInsetAlignment.append(alignment); mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); adoptElement(element); } else qDebug() << Q_FUNC_INFO << "Can't add null element"; } /*! Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a rect. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) { if (element) { if (element->layout()) // remove from old layout first element->layout()->take(element); mElements.append(element); mInsetPlacement.append(ipFree); mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); mInsetRect.append(rect); adoptElement(element); } else qDebug() << Q_FUNC_INFO << "Can't add null element"; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLineEnding //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLineEnding \brief Handles the different ending decorations for line-like items \image html QCPLineEnding.png "The various ending styles currently supported" For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite directions, e.g. "outward". This can be changed by \ref setInverted, which would make the respective arrow point inward. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead */ /*! Creates a QCPLineEnding instance with default values (style \ref esNone). */ QCPLineEnding::QCPLineEnding() : mStyle(esNone), mWidth(8), mLength(10), mInverted(false) { } /*! Creates a QCPLineEnding instance with the specified values. */ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : mStyle(style), mWidth(width), mLength(length), mInverted(inverted) { } /*! Sets the style of the ending decoration. */ void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) { mStyle = style; } /*! Sets the width of the ending decoration, if the style supports it. On arrows, for example, the width defines the size perpendicular to the arrow's pointing direction. \see setLength */ void QCPLineEnding::setWidth(double width) { mWidth = width; } /*! Sets the length of the ending decoration, if the style supports it. On arrows, for example, the length defines the size in pointing direction. \see setWidth */ void QCPLineEnding::setLength(double length) { mLength = length; } /*! Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point inward when \a inverted is set to true. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are affected by it, which can be used to control to which side the half bar points to. */ void QCPLineEnding::setInverted(bool inverted) { mInverted = inverted; } /*! \internal Returns the maximum pixel radius the ending decoration might cover, starting from the position the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). This is relevant for clipping. Only omit painting of the decoration when the position where the decoration is supposed to be drawn is farther away from the clipping rect than the returned distance. */ double QCPLineEnding::boundingDistance() const { switch (mStyle) { case esNone: return 0; case esFlatArrow: case esSpikeArrow: case esLineArrow: case esSkewedBar: return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length case esDisc: case esSquare: case esDiamond: case esBar: case esHalfBar: return mWidth*1.42; // items that only have a width -> width*sqrt(2) } return 0; } /*! Starting from the origin of this line ending (which is style specific), returns the length covered by the line ending symbol, in backward direction. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if both have the same \ref setLength value, because the spike arrow has an inward curved back, which reduces the length along its center axis (the drawing origin for arrows is at the tip). This function is used for precise, style specific placement of line endings, for example in QCPAxes. */ double QCPLineEnding::realLength() const { switch (mStyle) { case esNone: case esLineArrow: case esSkewedBar: case esBar: case esHalfBar: return 0; case esFlatArrow: return mLength; case esDisc: case esSquare: case esDiamond: return mWidth*0.5; case esSpikeArrow: return mLength*0.8; } return 0; } /*! \internal Draws the line ending with the specified \a painter at the position \a pos. The direction of the line ending is controlled with \a dir. */ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const { if (mStyle == esNone) return; QVector2D lengthVec(dir.normalized()); if (lengthVec.isNull()) lengthVec = QVector2D(1, 0); QVector2D widthVec(-lengthVec.y(), lengthVec.x()); lengthVec *= (float)(mLength*(mInverted ? -1 : 1)); widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1)); QPen penBackup = painter->pen(); QBrush brushBackup = painter->brush(); QPen miterPen = penBackup; miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey QBrush brush(painter->pen().color(), Qt::SolidPattern); switch (mStyle) { case esNone: break; case esFlatArrow: { QPointF points[3] = {pos.toPointF(), (pos-lengthVec+widthVec).toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 3); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esSpikeArrow: { QPointF points[4] = {pos.toPointF(), (pos-lengthVec+widthVec).toPointF(), (pos-lengthVec*0.8f).toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esLineArrow: { QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), pos.toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->drawPolyline(points, 3); painter->setPen(penBackup); break; } case esDisc: { painter->setBrush(brush); painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); painter->setBrush(brushBackup); break; } case esSquare: { QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), (pos-widthVecPerp-widthVec).toPointF(), (pos+widthVecPerp-widthVec).toPointF(), (pos+widthVecPerp+widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esDiamond: { QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); QPointF points[4] = {(pos-widthVecPerp).toPointF(), (pos-widthVec).toPointF(), (pos+widthVecPerp).toPointF(), (pos+widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esBar: { painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); break; } case esHalfBar: { painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); break; } case esSkewedBar: { if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic)) { // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(), (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF()); } else { // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(), (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF()); } break; } } } /*! \internal \overload Draws the line ending. The direction is controlled with the \a angle parameter in radians. */ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const { draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGrid //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGrid \brief Responsible for drawing the grid of a QCPAxis. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. The axis and grid drawing was split into two classes to allow them to be placed on different layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid in the background and the axes in the foreground, and any plottables/items in between. This described situation is the default setup, see the QCPLayer documentation. */ /*! Creates a QCPGrid instance and sets default values. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. */ QCPGrid::QCPGrid(QCPAxis *parentAxis) : QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), mParentAxis(parentAxis) { // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called setParent(parentAxis); setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); setSubGridVisible(false); setAntialiased(false); setAntialiasedSubGrid(false); setAntialiasedZeroLine(false); } /*! Sets whether grid lines at sub tick marks are drawn. \see setSubGridPen */ void QCPGrid::setSubGridVisible(bool visible) { mSubGridVisible = visible; } /*! Sets whether sub grid lines are drawn antialiased. */ void QCPGrid::setAntialiasedSubGrid(bool enabled) { mAntialiasedSubGrid = enabled; } /*! Sets whether zero lines are drawn antialiased. */ void QCPGrid::setAntialiasedZeroLine(bool enabled) { mAntialiasedZeroLine = enabled; } /*! Sets the pen with which (major) grid lines are drawn. */ void QCPGrid::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen with which sub grid lines are drawn. */ void QCPGrid::setSubGridPen(const QPen &pen) { mSubGridPen = pen; } /*! Sets the pen with which zero lines are drawn. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. */ void QCPGrid::setZeroLinePen(const QPen &pen) { mZeroLinePen = pen; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPGrid::draw(QCPPainter *painter) { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } if (mSubGridVisible) drawSubGridLines(painter); drawGridLines(painter); } /*! \internal Draws the main grid lines and possibly a zero line with the specified painter. This is a helper function called by \ref draw. */ void QCPGrid::drawGridLines(QCPPainter *painter) const { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } int lowTick = mParentAxis->mLowestVisibleTick; int highTick = mParentAxis->mHighestVisibleTick; double t; // helper variable, result of coordinate-to-pixel transforms if (mParentAxis->orientation() == Qt::Horizontal) { // draw zeroline: int zeroLineIndex = -1; if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(mZeroLinePen); double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero for (int i=lowTick; i <= highTick; ++i) { if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { zeroLineIndex = i; t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); break; } } } // draw grid lines: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); for (int i=lowTick; i <= highTick; ++i) { if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); } } else { // draw zeroline: int zeroLineIndex = -1; if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(mZeroLinePen); double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero for (int i=lowTick; i <= highTick; ++i) { if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { zeroLineIndex = i; t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); break; } } } // draw grid lines: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); for (int i=lowTick; i <= highTick; ++i) { if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } } } /*! \internal Draws the sub grid lines with the specified painter. This is a helper function called by \ref draw. */ void QCPGrid::drawSubGridLines(QCPPainter *painter) const { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); double t; // helper variable, result of coordinate-to-pixel transforms painter->setPen(mSubGridPen); if (mParentAxis->orientation() == Qt::Horizontal) { for (int i=0; imSubTickVector.size(); ++i) { t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); } } else { for (int i=0; imSubTickVector.size(); ++i) { t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxis //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxis \brief Manages a single axis inside a QCustomPlot. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and QCustomPlot::yAxis2 (right). Axes are always part of an axis rect, see QCPAxisRect. \image html AxisNamesOverview.png
Naming convention of axis parts
\n \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line on the left represents the QCustomPlot widget border.
*/ /* start of documentation of inline functions */ /*! \fn Qt::Orientation QCPAxis::orientation() const Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced from the axis type (left, top, right or bottom). \see orientation(AxisType type) */ /*! \fn QCPGrid *QCPAxis::grid() const Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the grid is displayed. */ /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type) Returns the orientation of the specified axis type \see orientation() */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCPAxis::ticksRequest() This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick labels for a replot. Modifying the tick positions can be done with \ref setTickVector. If you also want to control the tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref setTickVectorLabels. If you only want static ticks you probably don't need this signal, since you can just set the tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this signal and set the vector/vectors there. */ /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange) This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper range shouldn't go beyond certain values. For example, the following slot would limit the x axis to only positive ranges: \code if (newRange.lower < 0) plot->xAxis->setRange(0, newRange.size()); \endcode */ /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ /* end of documentation of signals */ /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, create them manually and then inject them also via \ref QCPAxisRect::addAxis. */ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : QCPLayerable(parent->parentPlot(), QString(), parent), // axis base: mAxisType(type), mAxisRect(parent), mPadding(5), mOrientation(orientation(type)), mSelectableParts(spAxis | spTickLabels | spAxisLabel), mSelectedParts(spNone), mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedBasePen(QPen(Qt::blue, 2)), // axis label: mLabel(), mLabelFont(mParentPlot->font()), mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), mLabelColor(Qt::black), mSelectedLabelColor(Qt::blue), // tick labels: mTickLabels(true), mAutoTickLabels(true), mTickLabelType(ltNumber), mTickLabelFont(mParentPlot->font()), mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), mTickLabelColor(Qt::black), mSelectedTickLabelColor(Qt::blue), mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")), mDateTimeSpec(Qt::LocalTime), mNumberPrecision(6), mNumberFormatChar('g'), mNumberBeautifulPowers(true), // ticks and subticks: mTicks(true), mTickStep(1), mSubTickCount(4), mAutoTickCount(6), mAutoTicks(true), mAutoTickStep(true), mAutoSubTicks(true), mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedTickPen(QPen(Qt::blue, 2)), mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedSubTickPen(QPen(Qt::blue, 2)), // scale and range: mRange(0, 5), mRangeReversed(false), mScaleType(stLinear), mScaleLogBase(10), mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)), // internal members: mGrid(new QCPGrid(this)), mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), mLowestVisibleTick(0), mHighestVisibleTick(-1), mCachedMarginValid(false), mCachedMargin(0) { mGrid->setVisible(false); setAntialiased(false); setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again if (type == atTop) { setTickLabelPadding(3); setLabelPadding(6); } else if (type == atRight) { setTickLabelPadding(7); setLabelPadding(12); } else if (type == atBottom) { setTickLabelPadding(3); setLabelPadding(3); } else if (type == atLeft) { setTickLabelPadding(5); setLabelPadding(10); } } QCPAxis::~QCPAxis() { delete mAxisPainter; delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order } /* No documentation as it is a property getter */ int QCPAxis::tickLabelPadding() const { return mAxisPainter->tickLabelPadding; } /* No documentation as it is a property getter */ double QCPAxis::tickLabelRotation() const { return mAxisPainter->tickLabelRotation; } /* No documentation as it is a property getter */ QCPAxis::LabelSide QCPAxis::tickLabelSide() const { return mAxisPainter->tickLabelSide; } /* No documentation as it is a property getter */ QString QCPAxis::numberFormat() const { QString result; result.append(mNumberFormatChar); if (mNumberBeautifulPowers) { result.append(QLatin1Char('b')); if (mAxisPainter->numberMultiplyCross) result.append(QLatin1Char('c')); } return result; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthIn() const { return mAxisPainter->tickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthOut() const { return mAxisPainter->tickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthIn() const { return mAxisPainter->subTickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthOut() const { return mAxisPainter->subTickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::labelPadding() const { return mAxisPainter->labelPadding; } /* No documentation as it is a property getter */ int QCPAxis::offset() const { return mAxisPainter->offset; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::lowerEnding() const { return mAxisPainter->lowerEnding; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::upperEnding() const { return mAxisPainter->upperEnding; } /*! Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major ticks, consider choosing a logarithm base of 100, 1000 or even higher. If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" part). To only display the decimal power, set the number precision to zero with \ref setNumberPrecision. */ void QCPAxis::setScaleType(QCPAxis::ScaleType type) { if (mScaleType != type) { mScaleType = type; if (mScaleType == stLogarithmic) setRange(mRange.sanitizedForLogScale()); mCachedMarginValid = false; emit scaleTypeChanged(mScaleType); } } /*! If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major ticks, consider choosing \a base 100, 1000 or even higher. */ void QCPAxis::setScaleLogBase(double base) { if (base > 1) { mScaleLogBase = base; mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation mCachedMarginValid = false; } else qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base; } /*! Sets the range of the axis. This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. To invert the direction of an axis, use \ref setRangeReversed. */ void QCPAxis::setRange(const QCPRange &range) { if (range.lower == mRange.lower && range.upper == mRange.upper) return; if (!QCPRange::validRange(range)) return; QCPRange oldRange = mRange; if (mScaleType == stLogarithmic) { mRange = range.sanitizedForLogScale(); } else { mRange = range.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPAxis::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part, independent of the \ref setSelectableParts setting. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPAxis::setSelectedParts(const SelectableParts &selected) { if (mSelectedParts != selected) { mSelectedParts = selected; emit selectionChanged(mSelectedParts); } } /*! \overload Sets the lower and upper bound of the axis range. To invert the direction of an axis, use \ref setRangeReversed. There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPAxis::setRange(double lower, double upper) { if (lower == mRange.lower && upper == mRange.upper) return; if (!QCPRange::validRange(lower, upper)) return; QCPRange oldRange = mRange; mRange.lower = lower; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! \overload Sets the range of the axis. The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, or center of the range to be aligned with \a position. Any other values of \a alignment will default to Qt::AlignCenter. */ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) { if (alignment == Qt::AlignLeft) setRange(position, position+size); else if (alignment == Qt::AlignRight) setRange(position-size, position); else // alignment == Qt::AlignCenter setRange(position-size/2.0, position+size/2.0); } /*! Sets the lower bound of the axis range. The upper bound is not changed. \see setRange */ void QCPAxis::setRangeLower(double lower) { if (mRange.lower == lower) return; QCPRange oldRange = mRange; mRange.lower = lower; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets the upper bound of the axis range. The lower bound is not changed. \see setRange */ void QCPAxis::setRangeUpper(double upper) { if (mRange.upper == upper) return; QCPRange oldRange = mRange; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the direction of increasing values is inverted. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part of the \ref setRange interface will still reference the mathematically smaller number than the \a upper part. */ void QCPAxis::setRangeReversed(bool reversed) { if (mRangeReversed != reversed) { mRangeReversed = reversed; mCachedMarginValid = false; } } /*! Sets whether the tick positions should be calculated automatically (either from an automatically generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep). If \a on is set to false, you must provide the tick positions manually via \ref setTickVector. For these manual ticks you may let QCPAxis generate the appropriate labels automatically by leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels manually, set \ref setAutoTickLabels to false and provide the label strings with \ref setTickVectorLabels. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the vectors in a slot connected to the \ref ticksRequest signal. \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep */ void QCPAxis::setAutoTicks(bool on) { if (mAutoTicks != on) { mAutoTicks = on; mCachedMarginValid = false; } } /*! When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be generated in the visible range, approximately. It's not guaranteed that this number of ticks is met exactly, but approximately within a tolerance of about two. Only values greater than zero are accepted as \a approximateCount. \see setAutoTickStep, setAutoTicks, setAutoSubTicks */ void QCPAxis::setAutoTickCount(int approximateCount) { if (mAutoTickCount != approximateCount) { if (approximateCount > 0) { mAutoTickCount = approximateCount; mCachedMarginValid = false; } else qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount; } } /*! Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat. If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This is usually used in a combination with \ref setAutoTicks set to false for complete control over tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi" etc. as tick labels. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the vectors in a slot connected to the \ref ticksRequest signal. \see setAutoTicks */ void QCPAxis::setAutoTickLabels(bool on) { if (mAutoTickLabels != on) { mAutoTickLabels = on; mCachedMarginValid = false; } } /*! Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human readable plots. The number of ticks the algorithm aims for within the visible range can be specified with \ref setAutoTickCount. If \a on is set to false, you may set the tick step manually with \ref setTickStep. \see setAutoTicks, setAutoSubTicks, setAutoTickCount */ void QCPAxis::setAutoTickStep(bool on) { if (mAutoTickStep != on) { mAutoTickStep = on; mCachedMarginValid = false; } } /*! Sets whether the number of sub ticks in one tick interval is determined automatically. This works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is always the case. When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually. \see setAutoTickCount, setAutoTicks, setAutoTickStep */ void QCPAxis::setAutoSubTicks(bool on) { if (mAutoSubTicks != on) { mAutoSubTicks = on; mCachedMarginValid = false; } } /*! Sets whether tick marks are displayed. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve that, see \ref setTickLabels. */ void QCPAxis::setTicks(bool show) { if (mTicks != show) { mTicks = show; mCachedMarginValid = false; } } /*! Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. */ void QCPAxis::setTickLabels(bool show) { if (mTickLabels != show) { mTickLabels = show; mCachedMarginValid = false; } } /*! Sets the distance between the axis base line (including any outward ticks) and the tick labels. \see setLabelPadding, setPadding */ void QCPAxis::setTickLabelPadding(int padding) { if (mAxisPainter->tickLabelPadding != padding) { mAxisPainter->tickLabelPadding = padding; mCachedMarginValid = false; } } /*! Sets whether the tick labels display numbers or dates/times. If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply. If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply. In QCustomPlot, date/time coordinates are double numbers representing the seconds since 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in milliseconds. Divide its return value by 1000.0 to get a value with the format needed for date/time plotting, with a resolution of one millisecond. Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C. (represented by a negative number), unlike the toTime_t function, which works with unsigned integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes. \see setTickLabels */ void QCPAxis::setTickLabelType(LabelType type) { if (mTickLabelType != type) { mTickLabelType = type; mCachedMarginValid = false; } } /*! Sets the font of the tick labels. \see setTickLabels, setTickLabelColor */ void QCPAxis::setTickLabelFont(const QFont &font) { if (font != mTickLabelFont) { mTickLabelFont = font; mCachedMarginValid = false; } } /*! Sets the color of the tick labels. \see setTickLabels, setTickLabelFont */ void QCPAxis::setTickLabelColor(const QColor &color) { if (color != mTickLabelColor) { mTickLabelColor = color; mCachedMarginValid = false; } } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPAxis::setTickLabelRotation(double degrees) { if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) { mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); mCachedMarginValid = false; } } /*! Sets whether the tick labels (numbers) shall appear inside or outside the axis rect. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels appear on the inside are additionally clipped to the axis rect. */ void QCPAxis::setTickLabelSide(LabelSide side) { mAxisPainter->tickLabelSide = side; mCachedMarginValid = false; } /*! Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime. for details about the \a format string, see the documentation of QDateTime::toString(). Newlines can be inserted with "\n". \see setDateTimeSpec */ void QCPAxis::setDateTimeFormat(const QString &format) { if (mDateTimeFormat != format) { mDateTimeFormat = format; mCachedMarginValid = false; } } /*! Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref ltDateTime. The default value of QDateTime objects (and also QCustomPlot) is Qt::LocalTime. However, if the date time values passed to QCustomPlot are given in the UTC spec, set \a timeSpec to Qt::UTC to get the correct axis labels. \see setDateTimeFormat */ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) { mDateTimeSpec = timeSpec; } /*! Sets the number format for the numbers drawn as tick labels (if tick label type is \ref ltNumber). This \a formatCode is an extended version of the format code used e.g. by QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" section in the detailed description of the QString class. \a formatCode is a string of one, two or three characters. The first character is identical to the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, whichever is shorter. The second and third characters are optional and specific to QCustomPlot:\n If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b' option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" part). To only display the decimal power, set the number precision to zero with \ref setNumberPrecision. Examples for \a formatCode: \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, normal scientific format is used \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with beautifully typeset decimal powers and a dot as multiplication sign \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as multiplication sign \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal powers. Format code will be reduced to 'f'. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format code will not be changed. */ void QCPAxis::setNumberFormat(const QString &formatCode) { if (formatCode.isEmpty()) { qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; return; } mCachedMarginValid = false; // interpret first char as number format char: QString allowedFormatChars(QLatin1String("eEfgG")); if (allowedFormatChars.contains(formatCode.at(0))) { mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; return; } if (formatCode.length() < 2) { mNumberBeautifulPowers = false; mAxisPainter->numberMultiplyCross = false; return; } // interpret second char as indicator for beautiful decimal powers: if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) { mNumberBeautifulPowers = true; } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; return; } if (formatCode.length() < 3) { mAxisPainter->numberMultiplyCross = false; return; } // interpret third char as indicator for dot or cross multiplication symbol: if (formatCode.at(2) == QLatin1Char('c')) { mAxisPainter->numberMultiplyCross = true; } else if (formatCode.at(2) == QLatin1Char('d')) { mAxisPainter->numberMultiplyCross = false; } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; return; } } /*! Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) for details. The effect of precisions are most notably for number Formats starting with 'e', see \ref setNumberFormat If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10 [superscript] n", set \a precision to zero. */ void QCPAxis::setNumberPrecision(int precision) { if (mNumberPrecision != precision) { mNumberPrecision = precision; mCachedMarginValid = false; } } /*! If \ref setAutoTickStep is set to false, use this function to set the tick step manually. The tick step is the interval between (major) ticks, in plot coordinates. \see setSubTickCount */ void QCPAxis::setTickStep(double step) { if (mTickStep != step) { mTickStep = step; mCachedMarginValid = false; } } /*! If you want full control over what ticks (and possibly labels) the axes show, this function is used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else the provided tick vector will be overwritten with automatically generated tick coordinates upon replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels. \a vec is a vector containing the positions of the ticks, in plot coordinates. \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this. \see setTickVectorLabels */ void QCPAxis::setTickVector(const QVector &vec) { // don't check whether mTickVector != vec here, because it takes longer than we would save mTickVector = vec; mCachedMarginValid = false; } /*! If you want full control over what ticks and labels the axes show, this function is used to set a number of QStrings that will be displayed at the tick positions which you need to provide with \ref setTickVector. These two vectors should have the same size. (Note that you need to disable \ref setAutoTicks and \ref setAutoTickLabels first.) \a vec is a vector containing the labels of the ticks. The entries correspond to the respective indices in the tick vector, passed via \ref setTickVector. \see setTickVector */ void QCPAxis::setTickVectorLabels(const QVector &vec) { // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save mTickVectorLabels = vec; mCachedMarginValid = false; } /*! Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPAxis::setTickLength(int inside, int outside) { setTickLengthIn(inside); setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthIn(int inside) { if (mAxisPainter->tickLengthIn != inside) { mAxisPainter->tickLengthIn = inside; } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthOut(int outside) { if (mAxisPainter->tickLengthOut != outside) { mAxisPainter->tickLengthOut = outside; mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example, divides the tick intervals in four sub intervals. By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is always the case. If you want to disable automatic sub tick count and use this function to set the count manually, see \ref setAutoSubTicks. */ void QCPAxis::setSubTickCount(int count) { mSubTickCount = count; } /*! Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPAxis::setSubTickLength(int inside, int outside) { setSubTickLengthIn(inside); setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthIn(int inside) { if (mAxisPainter->subTickLengthIn != inside) { mAxisPainter->subTickLengthIn = inside; } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthOut(int outside) { if (mAxisPainter->subTickLengthOut != outside) { mAxisPainter->subTickLengthOut = outside; mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the pen, the axis base line is drawn with. \see setTickPen, setSubTickPen */ void QCPAxis::setBasePen(const QPen &pen) { mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. \see setTickLength, setBasePen */ void QCPAxis::setTickPen(const QPen &pen) { mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. \see setSubTickCount, setSubTickLength, setBasePen */ void QCPAxis::setSubTickPen(const QPen &pen) { mSubTickPen = pen; } /*! Sets the font of the axis label. \see setLabelColor */ void QCPAxis::setLabelFont(const QFont &font) { if (mLabelFont != font) { mLabelFont = font; mCachedMarginValid = false; } } /*! Sets the color of the axis label. \see setLabelFont */ void QCPAxis::setLabelColor(const QColor &color) { mLabelColor = color; } /*! Sets the text of the axis label that will be shown below/above or next to the axis, depending on its orientation. To disable axis labels, pass an empty string as \a str. */ void QCPAxis::setLabel(const QString &str) { if (mLabel != str) { mLabel = str; mCachedMarginValid = false; } } /*! Sets the distance between the tick labels and the axis label. \see setTickLabelPadding, setPadding */ void QCPAxis::setLabelPadding(int padding) { if (mAxisPainter->labelPadding != padding) { mAxisPainter->labelPadding = padding; mCachedMarginValid = false; } } /*! Sets the padding of the axis. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, that is left blank. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. \see setLabelPadding, setTickLabelPadding */ void QCPAxis::setPadding(int padding) { if (mPadding != padding) { mPadding = padding; mCachedMarginValid = false; } } /*! Sets the offset the axis has to its axis rect side. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, only the offset of the inner most axis has meaning (even if it is set to be invisible). The offset of the other, outer axes is controlled automatically, to place them at appropriate positions. */ void QCPAxis::setOffset(int offset) { mAxisPainter->offset = offset; } /*! Sets the font that is used for tick labels when they are selected. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelFont(const QFont &font) { if (font != mSelectedTickLabelFont) { mSelectedTickLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } } /*! Sets the font that is used for the axis label when it is selected. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelFont(const QFont &font) { mSelectedLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelColor(const QColor &color) { if (color != mSelectedTickLabelColor) { mSelectedTickLabelColor = color; } } /*! Sets the color that is used for the axis label when it is selected. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelColor(const QColor &color) { mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedBasePen(const QPen &pen) { mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickPen(const QPen &pen) { mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedSubTickPen(const QPen &pen) { mSelectedSubTickPen = pen; } /*! Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available styles. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. \see setUpperEnding */ void QCPAxis::setLowerEnding(const QCPLineEnding &ending) { mAxisPainter->lowerEnding = ending; } /*! Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available styles. For horizontal axes, this method refers to the right ending, for vertical axes the top ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. \see setLowerEnding */ void QCPAxis::setUpperEnding(const QCPLineEnding &ending) { mAxisPainter->upperEnding = ending; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPAxis::moveRange(double diff) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { mRange.lower += diff; mRange.upper += diff; } else // mScaleType == stLogarithmic { mRange.lower *= diff; mRange.upper *= diff; } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates around 1.0 will have moved symmetrically closer to 1.0). */ void QCPAxis::scaleRange(double factor, double center) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { QCPRange newRange; newRange.lower = (mRange.lower-center)*factor + center; newRange.upper = (mRange.upper-center)*factor + center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLinScale(); } else // mScaleType == stLogarithmic { if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range { QCPRange newRange; newRange.lower = qPow(mRange.lower/center, factor)*center; newRange.upper = qPow(mRange.upper/center, factor)*center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLogScale(); } else qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will be done around the center of the current axis range. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the axis rect has. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent will follow. */ void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) { int otherPixelSize, ownPixelSize; if (otherAxis->orientation() == Qt::Horizontal) otherPixelSize = otherAxis->axisRect()->width(); else otherPixelSize = otherAxis->axisRect()->height(); if (orientation() == Qt::Horizontal) ownPixelSize = axisRect()->width(); else ownPixelSize = axisRect()->height(); double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize; setRange(range().center(), newRangeSize, Qt::AlignCenter); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPAxis::rescale(bool onlyVisiblePlottables) { QList p = plottables(); QCPRange newRange; bool haveRange = false; for (int i=0; irealVisibility() && onlyVisiblePlottables) continue; QCPRange plottableRange; bool currentFoundRange; QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; if (mScaleType == stLogarithmic) signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive); if (p.at(i)->keyAxis() == this) plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); else plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); if (currentFoundRange) { if (!haveRange) newRange = plottableRange; else newRange.expand(plottableRange); haveRange = true; } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mScaleType == stLinear) { newRange.lower = center-mRange.size()/2.0; newRange.upper = center+mRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mRange.upper/mRange.lower); newRange.upper = center*qSqrt(mRange.upper/mRange.lower); } } setRange(newRange); } } /*! Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. */ double QCPAxis::pixelToCoord(double value) const { if (orientation() == Qt::Horizontal) { if (mScaleType == stLinear) { if (!mRangeReversed) return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; else return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; else return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; } } else // orientation() == Qt::Vertical { if (mScaleType == stLinear) { if (!mRangeReversed) return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; else return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; else return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; } } } /*! Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. */ double QCPAxis::coordToPixel(double value) const { if (orientation() == Qt::Horizontal) { if (mScaleType == stLinear) { if (!mRangeReversed) return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); else return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); } else // mScaleType == stLogarithmic { if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; else { if (!mRangeReversed) return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); else return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); } } } else // orientation() == Qt::Vertical { if (mScaleType == stLinear) { if (!mRangeReversed) return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); else return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); } else // mScaleType == stLogarithmic { if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; else { if (!mRangeReversed) return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); else return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); } } } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. If the axis is not visible (\ref setVisible), this function always returns \ref spNone. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const { if (!mVisible) return spNone; if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) return spAxis; else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) return spTickLabels; else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) return spAxisLabel; else return spNone; } /* inherits documentation from base class */ double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; SelectablePart part = getPartAt(pos); if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) return -1; if (details) details->setValue(part); return mParentPlot->selectionTolerance()*0.99; } /*! Returns a list of all the plottables that have this axis as key or value axis. If you are only interested in plottables of type QCPGraph, see \ref graphs. \see graphs, items */ QList QCPAxis::plottables() const { QList result; if (!mParentPlot) return result; for (int i=0; imPlottables.size(); ++i) { if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) result.append(mParentPlot->mPlottables.at(i)); } return result; } /*! Returns a list of all the graphs that have this axis as key or value axis. \see plottables, items */ QList QCPAxis::graphs() const { QList result; if (!mParentPlot) return result; for (int i=0; imGraphs.size(); ++i) { if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) result.append(mParentPlot->mGraphs.at(i)); } return result; } /*! Returns a list of all the items that are associated with this axis. An item is considered associated with an axis if at least one of its positions uses the axis as key or value axis. \see plottables, graphs */ QList QCPAxis::items() const { QList result; if (!mParentPlot) return result; for (int itemId=0; itemIdmItems.size(); ++itemId) { QList positions = mParentPlot->mItems.at(itemId)->positions(); for (int posId=0; posIdkeyAxis() == this || positions.at(posId)->valueAxis() == this) { result.append(mParentPlot->mItems.at(itemId)); break; } } } return result; } /*! Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.) */ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) { switch (side) { case QCP::msLeft: return atLeft; case QCP::msRight: return atRight; case QCP::msTop: return atTop; case QCP::msBottom: return atBottom; default: break; } qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; return atLeft; } /*! Returns the axis type that describes the opposite axis of an axis with the specified \a type. */ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) { switch (type) { case atLeft: return atRight; break; case atRight: return atLeft; break; case atBottom: return atTop; break; case atTop: return atBottom; break; default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break; } } /*! \internal This function is called to prepare the tick vector, sub tick vector and tick label vector. If \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to provide external tick positions. Then the sub tick vectors and tick label vectors are created. */ void QCPAxis::setupTickVectors() { if (!mParentPlot) return; if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself if (mAutoTicks) { generateAutoTicks(); } else { emit ticksRequest(); } visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick); if (mTickVector.isEmpty()) { mSubTickVector.clear(); return; } // generate subticks between ticks: mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount); if (mSubTickCount > 0) { double subTickStep = 0; double subTickPosition = 0; int subTickIndex = 0; bool done = false; int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick; int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick; for (int i=lowTick+1; i<=highTick; ++i) { subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1); for (int k=1; k<=mSubTickCount; ++k) { subTickPosition = mTickVector.at(i-1) + k*subTickStep; if (subTickPosition < mRange.lower) continue; if (subTickPosition > mRange.upper) { done = true; break; } mSubTickVector[subTickIndex] = subTickPosition; subTickIndex++; } if (done) break; } mSubTickVector.resize(subTickIndex); } // generate tick labels according to tick positions: if (mAutoTickLabels) { int vecsize = mTickVector.size(); mTickVectorLabels.resize(vecsize); if (mTickLabelType == ltNumber) { for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar.toLatin1(), mNumberPrecision); } else if (mTickLabelType == ltDateTime) { for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) { #if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz") mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat); #else mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat); #endif } } } else // mAutoTickLabels == false { if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels { emit ticksRequest(); } // make sure provided tick label vector has correct (minimal) length: if (mTickVectorLabels.size() < mTickVector.size()) mTickVectorLabels.resize(mTickVector.size()); } } /*! \internal If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to generate reasonable tick positions (and subtick count). The algorithm tries to create approximately mAutoTickCount ticks (set via \ref setAutoTickCount). If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every power of the current logarithm base, set via \ref setScaleLogBase. */ void QCPAxis::generateAutoTicks() { if (mScaleType == stLinear) { if (mAutoTickStep) { // Generate tick positions according to linear scaling: mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. double tickStepMantissa = mTickStep/magnitudeFactor; if (tickStepMantissa < 5) { // round digit after decimal point to 0.5 mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor; } else { // round to first digit in multiples of 2 mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor; } } if (mAutoSubTicks) mSubTickCount = calculateAutoSubTickCount(mTickStep); // Generate tick positions according to mTickStep: qint64 firstStep = floor(mRange.lower/mTickStep); // do not use qFloor here, or we'll lose 64 bit precision qint64 lastStep = ceil(mRange.upper/mTickStep); // do not use qCeil here, or we'll lose 64 bit precision int tickcount = lastStep-firstStep+1; if (tickcount < 0) tickcount = 0; mTickVector.resize(tickcount); for (int i=0; i 0 && mRange.upper > 0) // positive range { double lowerMag = basePow(qFloor(baseLog(mRange.lower))); double currentMag = lowerMag; mTickVector.clear(); mTickVector.append(currentMag); while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case { currentMag *= mScaleLogBase; mTickVector.append(currentMag); } } else if (mRange.lower < 0 && mRange.upper < 0) // negative range { double lowerMag = -basePow(qCeil(baseLog(-mRange.lower))); double currentMag = lowerMag; mTickVector.clear(); mTickVector.append(currentMag); while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case { currentMag /= mScaleLogBase; mTickVector.append(currentMag); } } else // invalid range for logarithmic scale, because lower and upper have different sign { mTickVector.clear(); qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper; } } } /*! \internal Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks, because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note that a subtick count of 4 means dividing the major tick step into 5 sections. This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is returned. */ int QCPAxis::calculateAutoSubTickCount(double tickStep) const { int result = mSubTickCount; // default to current setting, if no proper value can be found // get mantissa of tickstep: double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. double tickStepMantissa = tickStep/magnitudeFactor; // separate integer and fractional part of mantissa: double epsilon = 0.01; double intPartf; int intPart; double fracPart = modf(tickStepMantissa, &intPartf); intPart = intPartf; // handle cases with (almost) integer mantissa: if (fracPart < epsilon || 1.0-fracPart < epsilon) { if (1.0-fracPart < epsilon) ++intPart; switch (intPart) { case 1: result = 4; break; // 1.0 -> 0.2 substep case 2: result = 3; break; // 2.0 -> 0.5 substep case 3: result = 2; break; // 3.0 -> 1.0 substep case 4: result = 3; break; // 4.0 -> 1.0 substep case 5: result = 4; break; // 5.0 -> 1.0 substep case 6: result = 2; break; // 6.0 -> 2.0 substep case 7: result = 6; break; // 7.0 -> 1.0 substep case 8: result = 3; break; // 8.0 -> 2.0 substep case 9: result = 2; break; // 9.0 -> 3.0 substep } } else { // handle cases with significantly fractional mantissa: if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa { switch (intPart) { case 1: result = 2; break; // 1.5 -> 0.5 substep case 2: result = 4; break; // 2.5 -> 0.5 substep case 3: result = 4; break; // 3.5 -> 0.7 substep case 4: result = 2; break; // 4.5 -> 1.5 substep case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on) case 6: result = 4; break; // 6.5 -> 1.3 substep case 7: result = 2; break; // 7.5 -> 2.5 substep case 8: result = 4; break; // 8.5 -> 1.7 substep case 9: result = 4; break; // 9.5 -> 1.9 substep } } // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default } return result; } /* inherits documentation from base class */ void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) SelectablePart part = details.value(); if (mSelectableParts.testFlag(part)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^part : part); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPAxis::deselectEvent(bool *selectionStateChanged) { SelectableParts selBefore = mSelectedParts; setSelectedParts(mSelectedParts & ~mSelectableParts); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. */ void QCPAxis::draw(QCPPainter *painter) { const int lowTick = mLowestVisibleTick; const int highTick = mHighestVisibleTick; QVector subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickLabels; // the final vector passed to QCPAxisPainter tickPositions.reserve(highTick-lowTick+1); tickLabels.reserve(highTick-lowTick+1); subTickPositions.reserve(mSubTickVector.size()); if (mTicks) { for (int i=lowTick; i<=highTick; ++i) { tickPositions.append(coordToPixel(mTickVector.at(i))); if (mTickLabels) tickLabels.append(mTickVectorLabels.at(i)); } if (mSubTickCount > 0) { const int subTickCount = mSubTickVector.size(); for (int i=0; itype = mAxisType; mAxisPainter->basePen = getBasePen(); mAxisPainter->labelFont = getLabelFont(); mAxisPainter->labelColor = getLabelColor(); mAxisPainter->label = mLabel; mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; mAxisPainter->tickPen = getTickPen(); mAxisPainter->subTickPen = getSubTickPen(); mAxisPainter->tickLabelFont = getTickLabelFont(); mAxisPainter->tickLabelColor = getTickLabelColor(); mAxisPainter->axisRect = mAxisRect->rect(); mAxisPainter->viewportRect = mParentPlot->viewport(); mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; mAxisPainter->reversedEndings = mRangeReversed; mAxisPainter->tickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; mAxisPainter->subTickPositions = subTickPositions; mAxisPainter->draw(painter); } /*! \internal Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in the current range. The return values are indices of the tick vector, not the positions of the ticks themselves. The actual use of this function is when an external tick vector is provided, since it might exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of subticks. If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be smaller than lowIndex. There is one case, where this function returns indices that are not really visible in the current axis range: When the tick spacing is larger than the axis range size and one tick is below the axis range and the next tick is already above the axis range. Because in such cases it is usually desirable to know the tick pair, to draw proper subticks. */ void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const { bool lowFound = false; bool highFound = false; lowIndex = 0; highIndex = -1; for (int i=0; i < mTickVector.size(); ++i) { if (mTickVector.at(i) >= mRange.lower) { lowFound = true; lowIndex = i; break; } } for (int i=mTickVector.size()-1; i >= 0; --i) { if (mTickVector.at(i) <= mRange.upper) { highFound = true; highIndex = i; break; } } if (!lowFound && highFound) lowIndex = highIndex+1; else if (lowFound && !highFound) highIndex = lowIndex-1; } /*! \internal A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation. This is set to 1.0/qLn(mScaleLogBase) in \ref setScaleLogBase. \see basePow, setScaleLogBase, setScaleType */ double QCPAxis::baseLog(double value) const { return qLn(value)*mScaleLogBaseLogInv; } /*! \internal A power function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic scales with arbitrary log base. \see baseLog, setScaleLogBase, setScaleType */ double QCPAxis::basePow(double value) const { return qPow(mScaleLogBase, value); } /*! \internal Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPAxis::getBasePen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPAxis::getTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPAxis::getSubTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPAxis::getTickLabelFont() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPAxis::getLabelFont() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPAxis::getTickLabelColor() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPAxis::getLabelColor() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /*! \internal Returns the appropriate outward margin for this axis. It is needed if \ref QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom margin and so forth. For the calculation, this function goes through similar steps as \ref draw, so changing one function likely requires the modification of the other one as well. The margin consists of the outward tick length, tick label padding, tick label size, label padding, label size, and padding. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. unchanged are very fast. */ int QCPAxis::calculateMargin() { if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis return 0; if (mCachedMarginValid) return mCachedMargin; // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels int margin = 0; int lowTick, highTick; visibleTickBounds(lowTick, highTick); QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickLabels; // the final vector passed to QCPAxisPainter tickPositions.reserve(highTick-lowTick+1); tickLabels.reserve(highTick-lowTick+1); if (mTicks) { for (int i=lowTick; i<=highTick; ++i) { tickPositions.append(coordToPixel(mTickVector.at(i))); if (mTickLabels) tickLabels.append(mTickVectorLabels.at(i)); } } // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters mAxisPainter->type = mAxisType; mAxisPainter->labelFont = getLabelFont(); mAxisPainter->label = mLabel; mAxisPainter->tickLabelFont = mTickLabelFont; mAxisPainter->axisRect = mAxisRect->rect(); mAxisPainter->viewportRect = mParentPlot->viewport(); mAxisPainter->tickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; margin += mAxisPainter->size(); margin += mPadding; mCachedMargin = margin; mCachedMarginValid = true; return margin; } /* inherits documentation from base class */ QCP::Interaction QCPAxis::selectionCategory() const { return QCP::iSelectAxes; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisPainterPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisPainterPrivate \internal \brief (Private) This is a private class and not part of the public QCustomPlot interface. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and axis label. It also buffers the labels to reduce replot times. The parameters are configured by directly accessing the public member variables. */ /*! Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every redraw, to utilize the caching mechanisms. */ QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : type(QCPAxis::atLeft), basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), lowerEnding(QCPLineEnding::esNone), upperEnding(QCPLineEnding::esNone), labelPadding(0), tickLabelPadding(0), tickLabelRotation(0), tickLabelSide(QCPAxis::lsOutside), substituteExponent(true), numberMultiplyCross(false), tickLengthIn(5), tickLengthOut(0), subTickLengthIn(2), subTickLengthOut(0), tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), offset(0), abbreviateDecimalPowers(false), reversedEndings(false), mParentPlot(parentPlot), mLabelCache(16) // cache at most 16 (tick) labels { } QCPAxisPainterPrivate::~QCPAxisPainterPrivate() { } /*! \internal Draws the axis with the specified \a painter. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set here, too. */ void QCPAxisPainterPrivate::draw(QCPPainter *painter) { QByteArray newHash = generateLabelParameterHash(); if (newHash != mLabelParameterHash) { mLabelCache.clear(); mLabelParameterHash = newHash; } QPoint origin; switch (type) { case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break; case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break; case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break; case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break; } double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) switch (type) { case QCPAxis::atTop: yCor = -1; break; case QCPAxis::atRight: xCor = 1; break; default: break; } int margin = 0; // draw baseline: QLineF baseLine; painter->setPen(basePen); if (QCPAxis::orientation(type) == Qt::Horizontal) baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor)); else baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor)); if (reversedEndings) baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later painter->drawLine(baseLine); // draw ticks: if (!tickPositions.isEmpty()) { painter->setPen(tickPen); int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) if (QCPAxis::orientation(type) == Qt::Horizontal) { for (int i=0; idrawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor)); } else { for (int i=0; idrawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor)); } } // draw subticks: if (!subTickPositions.isEmpty()) { painter->setPen(subTickPen); // direction of ticks ("inward" is right for left axis and left for right axis) int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; if (QCPAxis::orientation(type) == Qt::Horizontal) { for (int i=0; idrawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); } else { for (int i=0; idrawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor)); } } margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // draw axis base endings: bool antialiasingBackup = painter->antialiasing(); painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't painter->setBrush(QBrush(basePen.color())); QVector2D baseLineVector(baseLine.dx(), baseLine.dy()); if (lowerEnding.style() != QCPLineEnding::esNone) lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); if (upperEnding.style() != QCPLineEnding::esNone) upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); painter->setAntialiasing(antialiasingBackup); // tick labels: QRect oldClipRect; if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect { oldClipRect = painter->clipRegion().boundingRect(); painter->setClipRect(axisRect); } QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label if (!tickLabels.isEmpty()) { if (tickLabelSide == QCPAxis::lsOutside) margin += tickLabelPadding; painter->setFont(tickLabelFont); painter->setPen(QPen(tickLabelColor)); const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); int distanceToAxis = margin; if (tickLabelSide == QCPAxis::lsInside) distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); for (int i=0; isetClipRect(oldClipRect); // axis label: QRect labelBounds; if (!label.isEmpty()) { margin += labelPadding; painter->setFont(labelFont); painter->setPen(QPen(labelColor)); labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); if (type == QCPAxis::atLeft) { QTransform oldTransform = painter->transform(); painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); painter->rotate(-90); painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); painter->setTransform(oldTransform); } else if (type == QCPAxis::atRight) { QTransform oldTransform = painter->transform(); painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height()); painter->rotate(90); painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); painter->setTransform(oldTransform); } else if (type == QCPAxis::atTop) painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); else if (type == QCPAxis::atBottom) painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); } // set selection boxes: int selectionTolerance = 0; if (mParentPlot) selectionTolerance = mParentPlot->selectionTolerance(); else qDebug() << Q_FUNC_INFO << "mParentPlot is null"; int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); int selAxisInSize = selectionTolerance; int selTickLabelSize; int selTickLabelOffset; if (tickLabelSide == QCPAxis::lsOutside) { selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; } else { selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); } int selLabelSize = labelBounds.height(); int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding; if (type == QCPAxis::atLeft) { mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom()); mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom()); mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom()); } else if (type == QCPAxis::atRight) { mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom()); mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom()); mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom()); } else if (type == QCPAxis::atTop) { mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize); mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset); mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset); } else if (type == QCPAxis::atBottom) { mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize); mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset); mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset); } mAxisSelectionBox = mAxisSelectionBox.normalized(); mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); mLabelSelectionBox = mLabelSelectionBox.normalized(); // draw hitboxes for debug purposes: //painter->setBrush(Qt::NoBrush); //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); } /*! \internal Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ int QCPAxisPainterPrivate::size() const { int result = 0; // get length of tick marks pointing outwards: if (!tickPositions.isEmpty()) result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // calculate size of tick labels: if (tickLabelSide == QCPAxis::lsOutside) { QSize tickLabelsSize(0, 0); if (!tickLabels.isEmpty()) { for (int i=0; iplottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled { CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache if (!cachedLabel) // no cached label existed, create it { cachedLabel = new CachedLabel; TickLabelData labelData = getTickLabelData(painter->font(), text); cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft(); cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); cachedLabel->pixmap.fill(Qt::transparent); QCPPainter cachePainter(&cachedLabel->pixmap); cachePainter.setPen(painter->pen()); drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); } // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): bool labelClippedByBorder = false; if (tickLabelSide == QCPAxis::lsOutside) { if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left(); else labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); } if (!labelClippedByBorder) { painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); finalSize = cachedLabel->pixmap.size(); } mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created } else // label caching disabled, draw text directly on surface: { TickLabelData labelData = getTickLabelData(painter->font(), text); QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): bool labelClippedByBorder = false; if (tickLabelSide == QCPAxis::lsOutside) { if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); else labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); } if (!labelClippedByBorder) { drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); finalSize = labelData.rotatedTotalBounds.size(); } } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } /*! \internal This is a \ref placeTickLabel helper function. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when QCP::phCacheLabels plotting hint is not set. */ void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const { // backup painter settings that we're about to change: QTransform oldTransform = painter->transform(); QFont oldFont = painter->font(); // transform painter to position/rotation: painter->translate(x, y); if (!qFuzzyIsNull(tickLabelRotation)) painter->rotate(tickLabelRotation); // draw text: if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used { painter->setFont(labelData.baseFont); painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); painter->setFont(labelData.expFont); painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); } else { painter->setFont(labelData.baseFont); painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); } // reset painter settings to what it was before: painter->setTransform(oldTransform); painter->setFont(oldFont); } /*! \internal This is a \ref placeTickLabel helper function. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const { TickLabelData result; // determine whether beautiful decimal powers should be used bool useBeautifulPowers = false; int ePos = -1; if (substituteExponent) { ePos = text.indexOf(QLatin1Char('e')); if (ePos > -1) useBeautifulPowers = true; } // calculate text bounding rects and do string preparation for beautiful decimal powers: result.baseFont = font; if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding if (useBeautifulPowers) { // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent: result.basePart = text.left(ePos); // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base: if (abbreviateDecimalPowers && result.basePart == QLatin1String("1")) result.basePart = QLatin1String("10"); else result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10"); result.expPart = text.mid(ePos+1); // clip "+" and leading zeros off expPart: while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e' result.expPart.remove(1, 1); if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) result.expPart.remove(0, 1); // prepare smaller font for exponent: result.expFont = font; if (result.expFont.pointSize() > 0) result.expFont.setPointSize(result.expFont.pointSize()*0.75); else result.expFont.setPixelSize(result.expFont.pixelSize()*0.75); // calculate bounding rects of base part, exponent part and total one: result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA } else // useBeautifulPowers == false { result.basePart = text; result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); } result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler // calculate possibly different bounding rect after rotation: result.rotatedTotalBounds = result.totalBounds; if (!qFuzzyIsNull(tickLabelRotation)) { QTransform transform; transform.rotate(tickLabelRotation); result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); } return result; } /*! \internal This is a \ref placeTickLabel helper function. Calculates the offset at which the top left corner of the specified tick label shall be drawn. The offset is relative to a point right next to the tick the label belongs to. This function is thus responsible for e.g. centering tick labels under ticks and positioning them appropriately when they are rotated. */ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const { /* calculate label offset from base point at tick (non-trivial, for best visual appearance): short explanation for bottom axis: The anchor, i.e. the point in the label that is placed horizontally under the corresponding tick is always on the label side that is closer to the axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text will be centered under the tick (i.e. displaced horizontally by half its height). At the same time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick labels. */ bool doRotation = !qFuzzyIsNull(tickLabelRotation); bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. double radians = tickLabelRotation/180.0*M_PI; int x=0, y=0; if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = -qCos(radians)*labelData.totalBounds.width(); y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; } else { x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; } } else { x = -labelData.totalBounds.width(); y = -labelData.totalBounds.height()/2.0; } } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = +qSin(radians)*labelData.totalBounds.height(); y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; } else { x = 0; y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; } } else { x = 0; y = -labelData.totalBounds.height()/2.0; } } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); } else { x = -qSin(-radians)*labelData.totalBounds.height()/2.0; y = -qCos(-radians)*labelData.totalBounds.height(); } } else { x = -labelData.totalBounds.width()/2.0; y = -labelData.totalBounds.height(); } } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label { if (doRotation) { if (tickLabelRotation > 0) { x = +qSin(radians)*labelData.totalBounds.height()/2.0; y = 0; } else { x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; y = +qSin(-radians)*labelData.totalBounds.width(); } } else { x = -labelData.totalBounds.width()/2.0; y = 0; } } return QPointF(x, y); } /*! \internal Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a smaller width/height. */ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const { // note: this function must return the same tick label sizes as the placeTickLabel function. QSize finalSize; if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label { const CachedLabel *cachedLabel = mLabelCache.object(text); finalSize = cachedLabel->pixmap.size(); } else // label caching disabled or no label with this text cached: { TickLabelData labelData = getTickLabelData(font, text); finalSize = labelData.rotatedTotalBounds.size(); } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractPlottable //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractPlottable \brief The abstract base class for all data representing objects in a plot. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new ways of displaying data (see "Creating own plottables" below). All further specifics are in the subclasses, for example: \li A normal graph with possibly a line, scatter points and error bars: \ref QCPGraph (typically created with \ref QCustomPlot::addGraph) \li A parametric curve: \ref QCPCurve \li A bar chart: \ref QCPBars \li A statistical box plot: \ref QCPStatisticalBox \li A color encoded two-dimensional map: \ref QCPColorMap \li An OHLC/Candlestick chart: \ref QCPFinancial \section plottables-subclassing Creating own plottables To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure virtual functions, you must implement: \li \ref clearData \li \ref selectTest \li \ref draw \li \ref drawLegendIcon \li \ref getKeyRange \li \ref getValueRange See the documentation of those functions for what they need to do. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot coordinates to pixel coordinates. This function is quite convenient, because it takes the orientation of the key and value axes into account for you (x and y are swapped when the key axis is vertical and the value axis horizontal). If you are worried about performance (i.e. you need to translate many points in a loop like QCPGraph), you can directly use \ref QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis yourself. Here are some important members you inherit from QCPAbstractPlottable:
QCustomPlot *\b mParentPlot A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.
QString \b mName The name of the plottable.
QPen \b mPen The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)
QPen \b mSelectedPen The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).
QBrush \b mBrush The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)
QBrush \b mSelectedBrush The generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).
QPointer\b mKeyAxis, \b mValueAxis The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension. Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.
bool \b mSelected indicates whether the plottable is selected or not.
*/ /* start of documentation of pure virtual functions */ /*! \fn void QCPAbstractPlottable::clearData() = 0 Clears all data in the plottable. */ /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 \internal called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation of this plottable inside \a rect, next to the plottable name. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't appear outside the legend icon border. */ /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0 \internal called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref sdNegative and all positive points will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output parameter that indicates whether a range could be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data). Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by this function may have size zero, which wouldn't count as a valid range. \see rescaleAxes, getValueRange */ /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0 \internal called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref sdNegative and all positive points will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output parameter that indicates whether a range could be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data). Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by this function may have size zero, which wouldn't count as a valid range. \see rescaleAxes, getKeyRange */ /* end of documentation of pure virtual functions */ /* start of documentation of signals */ /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected) This signal is emitted when the selection state of this plottable has changed, either by user interaction or by a direct call to \ref setSelected. */ /*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable); This signal is emitted when the selectability of this plottable has changed. \see setSelectable */ /* end of documentation of signals */ /*! Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and have perpendicular orientations. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, it can't be directly instantiated. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. */ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), mName(), mAntialiasedFill(true), mAntialiasedScatters(true), mAntialiasedErrorBars(false), mPen(Qt::black), mSelectedPen(Qt::black), mBrush(Qt::NoBrush), mSelectedBrush(Qt::NoBrush), mKeyAxis(keyAxis), mValueAxis(valueAxis), mSelectable(true), mSelected(false) { if (keyAxis->parentPlot() != valueAxis->parentPlot()) qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; if (keyAxis->orientation() == valueAxis->orientation()) qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other."; } /*! The name is the textual representation of this plottable as it is displayed in the legend (\ref QCPLegend). It may contain any UTF-8 characters, including newlines. */ void QCPAbstractPlottable::setName(const QString &name) { mName = name; } /*! Sets whether fills of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedFill(bool enabled) { mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedScatters(bool enabled) { mAntialiasedScatters = enabled; } /*! Sets whether the error bars of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled) { mAntialiasedErrorBars = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. For example, the \ref QCPGraph subclass draws its graph lines with this pen. \see setBrush */ void QCPAbstractPlottable::setPen(const QPen &pen) { mPen = pen; } /*! When the plottable is selected, this pen is used to draw basic lines instead of the normal pen set via \ref setPen. \see setSelected, setSelectable, setSelectedBrush, selectTest */ void QCPAbstractPlottable::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! The brush is used to draw basic fills of the plottable representation in the plot. The Fill can be a color, gradient or texture, see the usage of QBrush. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. \see setPen */ void QCPAbstractPlottable::setBrush(const QBrush &brush) { mBrush = brush; } /*! When the plottable is selected, this brush is used to draw fills instead of the normal brush set via \ref setBrush. \see setSelected, setSelectable, setSelectedPen, selectTest */ void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setValueAxis */ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) { mKeyAxis = axis; } /*! The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's key axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setKeyAxis */ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) { mValueAxis = axis; } /*! Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectPlottables.) However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected directly. \see setSelected */ void QCPAbstractPlottable::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this plottable is selected or not. When selected, it uses a different pen and brush to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush. The entire selection mechanism for plottables is handled automatically when \ref QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when you wish to change the selection state manually. This function can change the selection state even when \ref setSelectable was set to false. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPAbstractPlottable::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /*! Rescales the key and value axes associated with this plottable to contain all displayed data, so the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie outside of that domain. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has \a onlyEnlarge set to false (the default), and all subsequent set to true. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale */ void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const { rescaleKeyAxis(onlyEnlarge); rescaleValueAxis(onlyEnlarge); } /*! Rescales the key axis of the plottable so the whole plottable is visible. See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const { QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } SignDomain signDomain = sdBoth; if (keyAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getKeyRange(foundRange, signDomain); if (foundRange) { if (onlyEnlarge) newRange.expand(keyAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (keyAxis->scaleType() == QCPAxis::stLinear) { newRange.lower = center-keyAxis->range().size()/2.0; newRange.upper = center+keyAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); } } keyAxis->setRange(newRange); } } /*! Rescales the value axis of the plottable so the whole plottable is visible. Returns true if the axis was actually scaled. This might not be the case if this plottable has an invalid range, e.g. because it has no data points. See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const { QCPAxis *valueAxis = mValueAxis.data(); if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } SignDomain signDomain = sdBoth; if (valueAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getValueRange(foundRange, signDomain); if (foundRange) { if (onlyEnlarge) newRange.expand(valueAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (valueAxis->scaleType() == QCPAxis::stLinear) { newRange.lower = center-valueAxis->range().size()/2.0; newRange.upper = center+valueAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); } } valueAxis->setRange(newRange); } } /*! Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend). Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable needs a more specialized representation in the legend, this function will take this into account and instead create the specialized subclass of QCPAbstractLegendItem. Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in the legend. \see removeFromLegend, QCPLegend::addItem */ bool QCPAbstractPlottable::addToLegend() { if (!mParentPlot || !mParentPlot->legend) return false; if (!mParentPlot->legend->hasItemWithPlottable(this)) { mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); return true; } else return false; } /*! Removes the plottable from the legend of the parent QCustomPlot. This means the QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable is removed. Returns true on success, i.e. if the legend exists and a legend item associated with this plottable was found and removed. \see addToLegend, QCPLegend::removeItem */ bool QCPAbstractPlottable::removeFromLegend() const { if (!mParentPlot->legend) return false; if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) return mParentPlot->legend->removeItem(lip); else return false; } /* inherits documentation from base class */ QRect QCPAbstractPlottable::clipRect() const { if (mKeyAxis && mValueAxis) return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); else return QRect(); } /* inherits documentation from base class */ QCP::Interaction QCPAbstractPlottable::selectionCategory() const { return QCP::iSelectPlottables; } /*! \internal Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface, taking the orientations of the axes associated with this plottable into account (e.g. whether key represents x or y). \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y. \see pixelsToCoords, QCPAxis::coordToPixel */ void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { x = keyAxis->coordToPixel(key); y = valueAxis->coordToPixel(value); } else { y = keyAxis->coordToPixel(key); x = valueAxis->coordToPixel(value); } } /*! \internal \overload Returns the input as pixel coordinates in a QPointF. */ const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } if (keyAxis->orientation() == Qt::Horizontal) return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value)); else return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key)); } /*! \internal Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates, taking the orientations of the axes associated with this plottable into account (e.g. whether key represents x or y). \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value. \see coordsToPixels, QCPAxis::coordToPixel */ void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { key = keyAxis->pixelToCoord(x); value = valueAxis->pixelToCoord(y); } else { key = keyAxis->pixelToCoord(y); value = valueAxis->pixelToCoord(x); } } /*! \internal \overload Returns the pixel input \a pixelPos as plot coordinates \a key and \a value. */ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); } /*! \internal Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the graph is not selected and mSelectedPen when it is. */ QPen QCPAbstractPlottable::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the graph is not selected and mSelectedBrush when it is. */ QBrush QCPAbstractPlottable::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable fills. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable scatter points. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable error bars. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint */ void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars); } /*! \internal Finds the shortest squared distance of \a point to the line segment defined by \a start and \a end. This function may be used to help with the implementation of the \ref selectTest function for specific plottables. \note This function is identical to QCPAbstractItem::distSqrToLine */ double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const { QVector2D a(start); QVector2D b(end); QVector2D p(point); QVector2D v(b-a); double vLengthSqr = v.lengthSquared(); if (!qFuzzyIsNull(vLengthSqr)) { double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; if (mu < 0) return (a-p).lengthSquared(); else if (mu > 1) return (b-p).lengthSquared(); else return ((a + mu*v)-p).lengthSquared(); } else return (a-p).lengthSquared(); } /* inherits documentation from base class */ void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemAnchor //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemAnchor \brief An anchor of an item to which positions can be attached to. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't control anything on its item, but provides a way to tie other items via their positions to the anchor. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the QCPItemRect. This way the start of the line will now always follow the respective anchor location on the rect item. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an anchor to other positions. To learn how to provide anchors in your own item subclasses, see the subclassing section of the QCPAbstractItem documentation. */ /* start documentation of inline functions */ /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with gcc compiler). */ /* end documentation of inline functions */ /*! Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) : mName(name), mParentPlot(parentPlot), mParentItem(parentItem), mAnchorId(anchorId) { } QCPItemAnchor::~QCPItemAnchor() { // unregister as parent at children: foreach (QCPItemPosition *child, mChildrenX.toList()) { if (child->parentAnchorX() == this) child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX } foreach (QCPItemPosition *child, mChildrenY.toList()) { if (child->parentAnchorY() == this) child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY } } /*! Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the parent item, QCPItemAnchor is just an intermediary. */ QPointF QCPItemAnchor::pixelPoint() const { if (mParentItem) { if (mAnchorId > -1) { return mParentItem->anchorPixelPoint(mAnchorId); } else { qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; return QPointF(); } } else { qDebug() << Q_FUNC_INFO << "no parent item set"; return QPointF(); } } /*! \internal Adds \a pos to the childX list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildX(QCPItemPosition *pos) { if (!mChildrenX.contains(pos)) mChildrenX.insert(pos); else qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); } /*! \internal Removes \a pos from the childX list of this anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) { if (!mChildrenX.remove(pos)) qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); } /*! \internal Adds \a pos to the childY list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildY(QCPItemPosition *pos) { if (!mChildrenY.contains(pos)) mChildrenY.insert(pos); else qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); } /*! \internal Removes \a pos from the childY list of this anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) { if (!mChildrenY.remove(pos)) qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPosition //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemPosition \brief Manages the position of an item. Every item has at least one public QCPItemPosition member pointer which provides ways to position the item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: \a topLeft and \a bottomRight. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel coordinates, as plot coordinates of certain axes, etc. For more advanced plots it is also possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref setTypeY). This way an item could be positioned at a fixed pixel distance from the top in the Y direction, while following a plot coordinate in the X direction. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords) are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0) means directly ontop of the parent anchor. For example, You could attach the \a start position of a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line always be centered under the text label, no matter where the text is moved to. For more advanced plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B in Y. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other positions. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified pixel values. */ /* start documentation of inline functions */ /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const Returns the current position type. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the type of the X coordinate. In that case rather use \a typeX() and \a typeY(). \see setType */ /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const Returns the current parent anchor. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY), this method returns the parent anchor of the Y coordinate. In that case rather use \a parentAnchorX() and \a parentAnchorY(). \see setParentAnchor */ /* end documentation of inline functions */ /*! Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) : QCPItemAnchor(parentPlot, parentItem, name), mPositionTypeX(ptAbsolute), mPositionTypeY(ptAbsolute), mKey(0), mValue(0), mParentAnchorX(0), mParentAnchorY(0) { } QCPItemPosition::~QCPItemPosition() { // unregister as parent at children: // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint foreach (QCPItemPosition *child, mChildrenX.toList()) { if (child->parentAnchorX() == this) child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX } foreach (QCPItemPosition *child, mChildrenY.toList()) { if (child->parentAnchorY() == this) child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY } // unregister as child in parent: if (mParentAnchorX) mParentAnchorX->removeChildX(this); if (mParentAnchorY) mParentAnchorY->removeChildY(this); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPItemPosition::axisRect() const { return mAxisRect.data(); } /*! Sets the type of the position. The type defines how the coordinates passed to \ref setCoords should be handled and how the QCPItemPosition should behave in the plot. The possible values for \a type can be separated in two main categories: \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. By default, the QCustomPlot's x- and yAxis are used. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref ptAxisRectRatio. They differ only in the way the absolute position is described, see the documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify the axis rect with \ref setAxisRect. By default this is set to the main axis rect. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position has no parent anchor (\ref setParentAnchor). If the type is changed, the apparent pixel position on the plot is preserved. This means the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. This method sets the type for both X and Y directions. It is also possible to set different types for X and Y, see \ref setTypeX, \ref setTypeY. */ void QCPItemPosition::setType(QCPItemPosition::PositionType type) { setTypeX(type); setTypeY(type); } /*! This method sets the position type of the X coordinate to \a type. For a detailed description of what a position type is, see the documentation of \ref setType. \see setType, setTypeY */ void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type) { if (mPositionTypeX != type) { // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. bool retainPixelPosition = true; if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) retainPixelPosition = false; if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) retainPixelPosition = false; QPointF pixel; if (retainPixelPosition) pixel = pixelPoint(); mPositionTypeX = type; if (retainPixelPosition) setPixelPoint(pixel); } } /*! This method sets the position type of the Y coordinate to \a type. For a detailed description of what a position type is, see the documentation of \ref setType. \see setType, setTypeX */ void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type) { if (mPositionTypeY != type) { // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. bool retainPixelPosition = true; if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) retainPixelPosition = false; if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) retainPixelPosition = false; QPointF pixel; if (retainPixelPosition) pixel = pixelPoint(); mPositionTypeY = type; if (retainPixelPosition) setPixelPoint(pixel); } } /*! Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now follow any position changes of the anchor. The local coordinate system of positions with a parent anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.) if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position will be exactly on top of the parent anchor. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is set to \ref ptAbsolute, to keep the position in a valid state. This method sets the parent anchor for both X and Y directions. It is also possible to set different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY. */ bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); return successX && successY; } /*! This method sets the parent anchor of the X coordinate to \a parentAnchor. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. \see setParentAnchor, setParentAnchorY */ bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { // make sure self is not assigned as parent: if (parentAnchor == this) { qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; } // make sure no recursive parent-child-relationships are created: QCPItemAnchor *currentParent = parentAnchor; while (currentParent) { if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { // is a QCPItemPosition, might have further parent, so keep iterating if (currentParentPos == this) { qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); return false; } currentParent = currentParentPos->parentAnchorX(); } else { // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the // same, to prevent a position being child of an anchor which itself depends on the position, // because they're both on the same item: if (currentParent->mParentItem == mParentItem) { qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); return false; } break; } } // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) setTypeX(ptAbsolute); // save pixel position: QPointF pixelP; if (keepPixelPosition) pixelP = pixelPoint(); // unregister at current parent anchor: if (mParentAnchorX) mParentAnchorX->removeChildX(this); // register at new parent anchor: if (parentAnchor) parentAnchor->addChildX(this); mParentAnchorX = parentAnchor; // restore pixel position under new parent: if (keepPixelPosition) setPixelPoint(pixelP); else setCoords(0, coords().y()); return true; } /*! This method sets the parent anchor of the Y coordinate to \a parentAnchor. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. \see setParentAnchor, setParentAnchorX */ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { // make sure self is not assigned as parent: if (parentAnchor == this) { qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; } // make sure no recursive parent-child-relationships are created: QCPItemAnchor *currentParent = parentAnchor; while (currentParent) { if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { // is a QCPItemPosition, might have further parent, so keep iterating if (currentParentPos == this) { qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); return false; } currentParent = currentParentPos->parentAnchorY(); } else { // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the // same, to prevent a position being child of an anchor which itself depends on the position, // because they're both on the same item: if (currentParent->mParentItem == mParentItem) { qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); return false; } break; } } // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) setTypeY(ptAbsolute); // save pixel position: QPointF pixelP; if (keepPixelPosition) pixelP = pixelPoint(); // unregister at current parent anchor: if (mParentAnchorY) mParentAnchorY->removeChildY(this); // register at new parent anchor: if (parentAnchor) parentAnchor->addChildY(this); mParentAnchorY = parentAnchor; // restore pixel position under new parent: if (keepPixelPosition) setPixelPoint(pixelP); else setCoords(coords().x(), 0); return true; } /*! Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type (\ref setType, \ref setTypeX, \ref setTypeY). For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the plot coordinate system defined by the axes set by \ref setAxes. By default those are the QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available coordinate types and their meaning. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a value must also be provided in the different coordinate systems. Here, the X type refers to \a key, and the Y type refers to \a value. \see setPixelPoint */ void QCPItemPosition::setCoords(double key, double value) { mKey = key; mValue = value; } /*! \overload Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the meaning of \a value of the \ref setCoords(double key, double value) method. */ void QCPItemPosition::setCoords(const QPointF &pos) { setCoords(pos.x(), pos.y()); } /*! Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor). \see setPixelPoint */ QPointF QCPItemPosition::pixelPoint() const { QPointF result; // determine X: switch (mPositionTypeX) { case ptAbsolute: { result.rx() = mKey; if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPoint().x(); break; } case ptViewportRatio: { result.rx() = mKey*mParentPlot->viewport().width(); if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPoint().x(); else result.rx() += mParentPlot->viewport().left(); break; } case ptAxisRectRatio: { if (mAxisRect) { result.rx() = mKey*mAxisRect.data()->width(); if (mParentAnchorX) result.rx() += mParentAnchorX->pixelPoint().x(); else result.rx() += mAxisRect.data()->left(); } else qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) result.rx() = mKeyAxis.data()->coordToPixel(mKey); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) result.rx() = mValueAxis.data()->coordToPixel(mValue); else qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; break; } } // determine Y: switch (mPositionTypeY) { case ptAbsolute: { result.ry() = mValue; if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPoint().y(); break; } case ptViewportRatio: { result.ry() = mValue*mParentPlot->viewport().height(); if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPoint().y(); else result.ry() += mParentPlot->viewport().top(); break; } case ptAxisRectRatio: { if (mAxisRect) { result.ry() = mValue*mAxisRect.data()->height(); if (mParentAnchorY) result.ry() += mParentAnchorY->pixelPoint().y(); else result.ry() += mAxisRect.data()->top(); } else qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) result.ry() = mKeyAxis.data()->coordToPixel(mKey); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) result.ry() = mValueAxis.data()->coordToPixel(mValue); else qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; break; } } return result; } /*! When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and yAxis of the QCustomPlot. */ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) { mKeyAxis = keyAxis; mValueAxis = valueAxis; } /*! When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of the QCustomPlot. */ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) { mAxisRect = axisRect; } /*! Sets the apparent pixel position. This works no matter what type (\ref setType) this QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed appropriately, to make the position finally appear at the specified pixel values. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is identical to that of \ref setCoords. \see pixelPoint, setCoords */ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) { double x = pixelPoint.x(); double y = pixelPoint.y(); switch (mPositionTypeX) { case ptAbsolute: { if (mParentAnchorX) x -= mParentAnchorX->pixelPoint().x(); break; } case ptViewportRatio: { if (mParentAnchorX) x -= mParentAnchorX->pixelPoint().x(); else x -= mParentPlot->viewport().left(); x /= (double)mParentPlot->viewport().width(); break; } case ptAxisRectRatio: { if (mAxisRect) { if (mParentAnchorX) x -= mParentAnchorX->pixelPoint().x(); else x -= mAxisRect.data()->left(); x /= (double)mAxisRect.data()->width(); } else qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) x = mKeyAxis.data()->pixelToCoord(x); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) y = mValueAxis.data()->pixelToCoord(x); else qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; break; } } switch (mPositionTypeY) { case ptAbsolute: { if (mParentAnchorY) y -= mParentAnchorY->pixelPoint().y(); break; } case ptViewportRatio: { if (mParentAnchorY) y -= mParentAnchorY->pixelPoint().y(); else y -= mParentPlot->viewport().top(); y /= (double)mParentPlot->viewport().height(); break; } case ptAxisRectRatio: { if (mAxisRect) { if (mParentAnchorY) y -= mParentAnchorY->pixelPoint().y(); else y -= mAxisRect.data()->top(); y /= (double)mAxisRect.data()->height(); } else qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; break; } case ptPlotCoords: { if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) x = mKeyAxis.data()->pixelToCoord(y); else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) y = mValueAxis.data()->pixelToCoord(y); else qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; break; } } setCoords(x, y); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractItem \brief The abstract base class for all items in a plot. In QCustomPlot, items are supplemental graphical elements that are neither plottables (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each specific item has at least one QCPItemPosition member which controls the positioning. Some items are defined by more than one coordinate and thus have two or more QCPItemPosition members (For example, QCPItemRect has \a topLeft and \a bottomRight). This abstract base class defines a very basic interface like visibility and clipping. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new items. The built-in items are:
QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
QCPItemStraightLineA straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.
QCPItemCurveA curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).
QCPItemRectA rectangle
QCPItemEllipseAn ellipse
QCPItemPixmapAn arbitrary pixmap
QCPItemTextA text label
QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
\section items-clipping Clipping Items are by default clipped to the main axis rect (they are only visible inside the axis rect). To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect "setClipToAxisRect(false)". On the other hand if you want the item to be clipped to a different axis rect, specify it via \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and in principle is independent of the coordinate axes the item might be tied to via its position members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping also contains the axes used for the item positions. \section items-using Using items First you instantiate the item you want to use and add it to the plot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1 by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just set the plot coordinates where the line should start/end: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2 If we don't want the line to be positioned in plot coordinates but a different coordinate system, e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3 Then we can set the coordinates, this time in pixels: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4 and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5 For more advanced plots, it is even possible to set different types and parent anchors per X/Y coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition. \section items-subclassing Creating own items To create an own item, you implement a subclass of QCPAbstractItem. These are the pure virtual functions, you must implement: \li \ref selectTest \li \ref draw See the documentation of those functions for what they need to do. \subsection items-positioning Allowing the item to be positioned As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add a public member of type QCPItemPosition like so: \code QCPItemPosition * const myPosition;\endcode the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition instance it points to, can be modified, of course). The initialization of this pointer is made easy with the \ref createPosition function. Just assign the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition takes a string which is the name of the position, typically this is identical to the variable name. For example, the constructor of QCPItemExample could look like this: \code QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), myPosition(createPosition("myPosition")) { // other constructor code } \endcode \subsection items-drawing The draw function To give your item a visual representation, reimplement the \ref draw function and use the passed QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the position member(s) via \ref QCPItemPosition::pixelPoint. To optimize performance you should calculate a bounding rect first (don't forget to take the pen width into account), check whether it intersects the \ref clipRect, and only draw the item at all if this is the case. \subsection items-selection The selectTest function Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and \ref rectSelectTest. With these, the implementation of the selection test becomes significantly simpler for most items. See the documentation of \ref selectTest for what the function parameters mean and what the function should return. \subsection anchors Providing anchors Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public member, e.g. \code QCPItemAnchor * const bottom;\endcode and create it in the constructor with the \ref createAnchor function, assigning it a name and an anchor id (an integer enumerating all anchors on the item, you may create an own enum for this). Since anchors can be placed anywhere, relative to the item's position(s), your item needs to provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int anchorId) function. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel position when anything attached to the anchor needs to know the coordinates. */ /* start of documentation of inline functions */ /*! \fn QList QCPAbstractItem::positions() const Returns all positions of the item in a list. \see anchors, position */ /*! \fn QList QCPAbstractItem::anchors() const Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always also an anchor, the list will also contain the positions of this item. \see positions, anchor */ /* end of documentation of inline functions */ /* start documentation of pure virtual functions */ /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 \internal Draws this item with the provided \a painter. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this function is called. The clipRect depends on the clipping settings defined by \ref setClipToAxisRect and \ref setClipAxisRect. */ /* end documentation of pure virtual functions */ /* start documentation of signals */ /*! \fn void QCPAbstractItem::selectionChanged(bool selected) This signal is emitted when the selection state of this item has changed, either by user interaction or by a direct call to \ref setSelected. */ /* end documentation of signals */ /*! Base class constructor which initializes base class members. */ QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : QCPLayerable(parentPlot), mClipToAxisRect(false), mSelectable(true), mSelected(false) { QList rects = parentPlot->axisRects(); if (rects.size() > 0) { setClipToAxisRect(true); setClipAxisRect(rects.first()); } } QCPAbstractItem::~QCPAbstractItem() { // don't delete mPositions because every position is also an anchor and thus in mAnchors qDeleteAll(mAnchors); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPAbstractItem::clipAxisRect() const { return mClipAxisRect.data(); } /*! Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. \see setClipAxisRect */ void QCPAbstractItem::setClipToAxisRect(bool clip) { mClipToAxisRect = clip; if (mClipToAxisRect) setParentLayerable(mClipAxisRect.data()); } /*! Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref setClipToAxisRect is set to true. \see setClipToAxisRect */ void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) { mClipAxisRect = rect; if (mClipToAxisRect) setParentLayerable(mClipAxisRect.data()); } /*! Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected. \see QCustomPlot::setInteractions, setSelected */ void QCPAbstractItem::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this item is selected or not. When selected, it might use a different visual appearance (e.g. pen and brush), this depends on the specific item though. The entire selection mechanism for items is handled automatically when \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this function when you wish to change the selection state manually. This function can change the selection state even when \ref setSelectable was set to false. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPAbstractItem::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /*! Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by that name, returns 0. This function provides an alternative way to access item positions. Normally, you access positions direcly by their member pointers (which typically have the same variable name as \a name). \see positions, anchor */ QCPItemPosition *QCPAbstractItem::position(const QString &name) const { for (int i=0; iname() == name) return mPositions.at(i); } qDebug() << Q_FUNC_INFO << "position with name not found:" << name; return 0; } /*! Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by that name, returns 0. This function provides an alternative way to access item anchors. Normally, you access anchors direcly by their member pointers (which typically have the same variable name as \a name). \see anchors, position */ QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const { for (int i=0; iname() == name) return mAnchors.at(i); } qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; return 0; } /*! Returns whether this item has an anchor with the specified \a name. Note that you can check for positions with this function, too. This is because every position is also an anchor (QCPItemPosition inherits from QCPItemAnchor). \see anchor, position */ bool QCPAbstractItem::hasAnchor(const QString &name) const { for (int i=0; iname() == name) return true; } return false; } /*! \internal Returns the rect the visual representation of this item is clipped to. This depends on the current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect. If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned. \see draw */ QRect QCPAbstractItem::clipRect() const { if (mClipToAxisRect && mClipAxisRect) return mClipAxisRect.data()->rect(); else return mParentPlot->viewport(); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing item lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); } /*! \internal Finds the shortest squared distance of \a point to the line segment defined by \a start and \a end. This function may be used to help with the implementation of the \ref selectTest function for specific items. \note This function is identical to QCPAbstractPlottable::distSqrToLine \see rectSelectTest */ double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const { QVector2D a(start); QVector2D b(end); QVector2D p(point); QVector2D v(b-a); double vLengthSqr = v.lengthSquared(); if (!qFuzzyIsNull(vLengthSqr)) { double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; if (mu < 0) return (a-p).lengthSquared(); else if (mu > 1) return (b-p).lengthSquared(); else return ((a + mu*v)-p).lengthSquared(); } else return (a-p).lengthSquared(); } /*! \internal A convenience function which returns the selectTest value for a specified \a rect and a specified click position \a pos. \a filledRect defines whether a click inside the rect should also be considered a hit or whether only the rect border is sensitive to hits. This function may be used to help with the implementation of the \ref selectTest function for specific items. For example, if your item consists of four rects, call this function four times, once for each rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned values. \see distSqrToLine */ double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const { double result = -1; // distance to border: QList lines; lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); double minDistSqr = std::numeric_limits::max(); for (int i=0; i mParentPlot->selectionTolerance()*0.99) { if (rect.contains(pos)) result = mParentPlot->selectionTolerance()*0.99; } return result; } /*! \internal Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in item subclasses if they want to provide anchors (QCPItemAnchor). For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor ids and returns the respective pixel points of the specified anchor. \see createAnchor */ QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const { qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; return QPointF(); } /*! \internal Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the position member (This is needed to provide the name-based \ref position access to positions). Don't delete positions created by this function manually, as the item will take care of it. Use this function in the constructor (initialization list) of the specific item subclass to create each position member. Don't create QCPItemPositions with \b new yourself, because they won't be registered with the item properly. \see createAnchor */ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) { if (hasAnchor(name)) qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); mPositions.append(newPosition); mAnchors.append(newPosition); // every position is also an anchor newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); newPosition->setType(QCPItemPosition::ptPlotCoords); if (mParentPlot->axisRect()) newPosition->setAxisRect(mParentPlot->axisRect()); newPosition->setCoords(0, 0); return newPosition; } /*! \internal Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the anchor member (This is needed to provide the name based \ref anchor access to anchors). The \a anchorId must be a number identifying the created anchor. It is recommended to create an enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns the correct pixel coordinates for the passed anchor id. Don't delete anchors created by this function manually, as the item will take care of it. Use this function in the constructor (initialization list) of the specific item subclass to create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they won't be registered with the item properly. \see createPosition */ QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) { if (hasAnchor(name)) qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); mAnchors.append(newAnchor); return newAnchor; } /* inherits documentation from base class */ void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractItem::selectionCategory() const { return QCP::iSelectItems; } /*! \file */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCustomPlot //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCustomPlot \brief The central class of the library. This is the QWidget which displays the plot and interacts with the user. For tutorials on how to use QCustomPlot, see the website\n http://www.qcustomplot.com/ */ /* start of documentation of inline functions */ /*! \fn QRect QCustomPlot::viewport() const Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger and contains also the axes themselves, their tick numbers, their labels, the plot title etc. Only when saving to a file (see \ref savePng, \ref savePdf etc.) the viewport is temporarily modified to allow saving plots with sizes independent of the current widget size. */ /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just one cell with the main QCPAxisRect inside. */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse double click event. */ /*! \fn void QCustomPlot::mousePress(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse press event. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. */ /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse move event. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, because the dragging starting point was saved the moment the mouse was pressed. Thus it only has a meaning for the range drag axes that were set at that moment. If you want to change the drag axes, consider doing this in the \ref mousePress signal instead. */ /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse release event. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or \ref QCPAbstractPlottable::setSelectable. */ /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse wheel event. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. */ /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event) This signal is emitted when a plottable is clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. \see plottableDoubleClick */ /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event) This signal is emitted when a plottable is double clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. \see plottableClick */ /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) This signal is emitted when an item is clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. \see itemDoubleClick */ /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) This signal is emitted when an item is double clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. \see itemClick */ /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is clicked. \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. \see axisDoubleClick */ /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is double clicked. \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. \see axisClick */ /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is clicked. \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. \see legendDoubleClick */ /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is double clicked. \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. \see legendClick */ /*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title) This signal is emitted when a plot title is clicked. \a event is the mouse event that caused the click and \a title is the plot title that received the click. \see titleDoubleClick */ /*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title) This signal is emitted when a plot title is double clicked. \a event is the mouse event that caused the click and \a title is the plot title that received the click. \see titleClick */ /*! \fn void QCustomPlot::selectionChangedByUser() This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by clicking. It is not emitted when the selection state of an object has changed programmatically by a direct call to setSelected() on an object or by calling \ref deselectAll. In addition to this signal, selectable objects also provide individual signals, for example QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are emitted even if the selection state is changed programmatically. See the documentation of \ref setInteractions for details about the selection mechanism. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends */ /*! \fn void QCustomPlot::beforeReplot() This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref replot). It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. \see replot, afterReplot */ /*! \fn void QCustomPlot::afterReplot() This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref replot). It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. \see replot, beforeReplot */ /* end of documentation of signals */ /* start of documentation of public members */ /*! \var QCPAxis *QCustomPlot::xAxis A pointer to the primary x Axis (bottom) of the main axis rect of the plot. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::yAxis A pointer to the primary y Axis (left) of the main axis rect of the plot. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::xAxis2 A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::yAxis2 A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPLegend *QCustomPlot::legend A pointer to the default legend of the main axis rect. The legend is invisible by default. Use QCPLegend::setVisible to change this. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple legends to the plot, use the layout system interface to access the new legend. For example, legends can be placed inside an axis rect's \ref QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointer becomes 0. */ /* end of documentation of public members */ /*! Constructs a QCustomPlot and sets reasonable default values. */ QCustomPlot::QCustomPlot(QWidget *parent) : QWidget(parent), xAxis(0), yAxis(0), xAxis2(0), yAxis2(0), legend(0), mPlotLayout(0), mAutoAddPlottableToLegend(true), mAntialiasedElements(QCP::aeNone), mNotAntialiasedElements(QCP::aeNone), mInteractions(0), mSelectionTolerance(8), mNoAntialiasingOnDrag(false), mBackgroundBrush(Qt::white, Qt::SolidPattern), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mCurrentLayer(0), mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint), mMultiSelectModifier(Qt::ControlModifier), mPaintBuffer(size()), mMouseEventElement(0), mReplotting(false) { setAttribute(Qt::WA_NoMousePropagation); setAttribute(Qt::WA_OpaquePaintEvent); setMouseTracking(true); QLocale currentLocale = locale(); currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); setLocale(currentLocale); // create initial layers: mLayers.append(new QCPLayer(this, QLatin1String("background"))); mLayers.append(new QCPLayer(this, QLatin1String("grid"))); mLayers.append(new QCPLayer(this, QLatin1String("main"))); mLayers.append(new QCPLayer(this, QLatin1String("axes"))); mLayers.append(new QCPLayer(this, QLatin1String("legend"))); updateLayerIndices(); setCurrentLayer(QLatin1String("main")); // create initial layout, axis rect and legend: mPlotLayout = new QCPLayoutGrid; mPlotLayout->initializeParentPlot(this); mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry mPlotLayout->setLayer(QLatin1String("main")); QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); mPlotLayout->addElement(0, 0, defaultAxisRect); xAxis = defaultAxisRect->axis(QCPAxis::atBottom); yAxis = defaultAxisRect->axis(QCPAxis::atLeft); xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); legend = new QCPLegend; legend->setVisible(false); defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); defaultAxisRect->setLayer(QLatin1String("background")); xAxis->setLayer(QLatin1String("axes")); yAxis->setLayer(QLatin1String("axes")); xAxis2->setLayer(QLatin1String("axes")); yAxis2->setLayer(QLatin1String("axes")); xAxis->grid()->setLayer(QLatin1String("grid")); yAxis->grid()->setLayer(QLatin1String("grid")); xAxis2->grid()->setLayer(QLatin1String("grid")); yAxis2->grid()->setLayer(QLatin1String("grid")); legend->setLayer(QLatin1String("legend")); setViewport(rect()); // needs to be called after mPlotLayout has been created replot(); } QCustomPlot::~QCustomPlot() { clearPlottables(); clearItems(); if (mPlotLayout) { delete mPlotLayout; mPlotLayout = 0; } mCurrentLayer = 0; qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed mLayers.clear(); } /*! Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is removed from there. \see setNotAntialiasedElements */ void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) { mAntialiasedElements = antialiasedElements; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mNotAntialiasedElements |= ~mAntialiasedElements; } /*! Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. See \ref setAntialiasedElements for details. \see setNotAntialiasedElement */ void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) { if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) mAntialiasedElements &= ~antialiasedElement; else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) mAntialiasedElements |= antialiasedElement; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mNotAntialiasedElements |= ~mAntialiasedElements; } /*! Sets which elements are forcibly drawn not antialiased as an \a or combination of QCP::AntialiasedElement. This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is removed from there. \see setAntialiasedElements */ void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) { mNotAntialiasedElements = notAntialiasedElements; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mAntialiasedElements |= ~mNotAntialiasedElements; } /*! Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. See \ref setNotAntialiasedElements for details. \see setAntialiasedElement */ void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) { if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) mNotAntialiasedElements &= ~notAntialiasedElement; else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) mNotAntialiasedElements |= notAntialiasedElement; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mAntialiasedElements |= ~mNotAntialiasedElements; } /*! If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the plottable to the legend (QCustomPlot::legend). \see addPlottable, addGraph, QCPLegend::addItem */ void QCustomPlot::setAutoAddPlottableToLegend(bool on) { mAutoAddPlottableToLegend = on; } /*! Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction enums. There are the following types of interactions: Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. For details how to control which axes the user may drag/zoom and in what orientations, see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, \ref QCPAxisRect::setRangeZoomAxes. Plottable selection is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific plottable. To find out whether a specific plottable is selected, call QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience function \ref selectedGraphs. Item selection is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of all currently selected items, call \ref selectedItems. Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for each axis. To retrieve a list of all axes that currently contain selected parts, call \ref selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may select the legend itself or individual items by clicking on them. What parts exactly are selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To find out which child items are selected, call \ref QCPLegend::selectedItems. All other selectable elements The selection of all other selectable objects (e.g. QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the user may select those objects by clicking on them. To find out which are currently selected, you need to check their selected state explicitly. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is emitted. Each selectable object additionally emits an individual selectionChanged signal whenever their selection state has changed, i.e. not only by user interaction. To allow multiple objects to be selected by holding the selection modifier (\ref setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. \note In addition to the selection mechanism presented here, QCustomPlot always emits corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and \ref plottableDoubleClick for example. \see setInteraction, setSelectionTolerance */ void QCustomPlot::setInteractions(const QCP::Interactions &interactions) { mInteractions = interactions; } /*! Sets the single \a interaction of this QCustomPlot to \a enabled. For details about the interaction system, see \ref setInteractions. \see setInteractions */ void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) { if (!enabled && mInteractions.testFlag(interaction)) mInteractions &= ~interaction; else if (enabled && !mInteractions.testFlag(interaction)) mInteractions |= interaction; } /*! Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or not. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a potential selection when the minimum distance between the click position and the graph line is smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks directly inside the area and ignore this selection tolerance. In other words, it only has meaning for parts of objects that are too thin to exactly hit with a click and thus need such a tolerance. \see setInteractions, QCPLayerable::selectTest */ void QCustomPlot::setSelectionTolerance(int pixels) { mSelectionTolerance = pixels; } /*! Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves performance during dragging. Thus it creates a more responsive user experience. As soon as the user stops dragging, the last replot is done with normal antialiasing, to restore high image quality. \see setAntialiasedElements, setNotAntialiasedElements */ void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) { mNoAntialiasingOnDrag = enabled; } /*! Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. \see setPlottingHint */ void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) { mPlottingHints = hints; } /*! Sets the specified plotting \a hint to \a enabled. \see setPlottingHints */ void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) { QCP::PlottingHints newHints = mPlottingHints; if (!enabled) newHints &= ~hint; else newHints |= hint; if (newHints != mPlottingHints) setPlottingHints(newHints); } /*! Sets the keyboard modifier that will be recognized as multi-select-modifier. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects by clicking on them one after the other while holding down \a modifier. By default the multi-select-modifier is set to Qt::ControlModifier. \see setInteractions */ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) { mMultiSelectModifier = modifier; } /*! Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref savePdf, etc. by temporarily changing the viewport size. */ void QCustomPlot::setViewport(const QRect &rect) { mViewport = rect; if (mPlotLayout) mPlotLayout->setOuterRect(mViewport); } /*! Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn below all other objects in the plot. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will first be filled with that brush, before drawing the background pixmap. This can be useful for background pixmaps with translucent areas. \see setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! Sets the background brush of the viewport (see \ref setViewport). Before drawing everything else, the background is filled with \a brush. If a background pixmap was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport before the background pixmap is drawn. This can be useful for background pixmaps with translucent areas. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be useful for exporting to image formats which support transparency, e.g. \ref savePng. \see setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the viewport, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is set to true, control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the viewport dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCustomPlot::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap is preserved. \see setBackground, setBackgroundScaled */ void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } /*! Returns the plottable with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last added plottable, see QCustomPlot::plottable() \see plottableCount, addPlottable */ QCPAbstractPlottable *QCustomPlot::plottable(int index) { if (index >= 0 && index < mPlottables.size()) { return mPlottables.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last plottable that was added with \ref addPlottable. If there are no plottables in the plot, returns 0. \see plottableCount, addPlottable */ QCPAbstractPlottable *QCustomPlot::plottable() { if (!mPlottables.isEmpty()) { return mPlottables.last(); } else return 0; } /*! Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable. Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the plottable's constructor). \see plottable, plottableCount, removePlottable, clearPlottables */ bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable) { if (mPlottables.contains(plottable)) { qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast(plottable); return false; } if (plottable->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(plottable); return false; } mPlottables.append(plottable); // possibly add plottable to legend: if (mAutoAddPlottableToLegend) plottable->addToLegend(); // special handling for QCPGraphs to maintain the simple graph interface: if (QCPGraph *graph = qobject_cast(plottable)) mGraphs.append(graph); if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) plottable->setLayer(currentLayer()); return true; } /*! Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend). Returns true on success. \see addPlottable, clearPlottables */ bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) { if (!mPlottables.contains(plottable)) { qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); return false; } // remove plottable from legend: plottable->removeFromLegend(); // special handling for QCPGraphs to maintain the simple graph interface: if (QCPGraph *graph = qobject_cast(plottable)) mGraphs.removeOne(graph); // remove plottable: delete plottable; mPlottables.removeOne(plottable); return true; } /*! \overload Removes the plottable by its \a index. */ bool QCustomPlot::removePlottable(int index) { if (index >= 0 && index < mPlottables.size()) return removePlottable(mPlottables[index]); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return false; } } /*! Removes all plottables from the plot (and the QCustomPlot::legend, if necessary). Returns the number of plottables removed. \see removePlottable */ int QCustomPlot::clearPlottables() { int c = mPlottables.size(); for (int i=c-1; i >= 0; --i) removePlottable(mPlottables[i]); return c; } /*! Returns the number of currently existing plottables in the plot \see plottable, addPlottable */ int QCustomPlot::plottableCount() const { return mPlottables.size(); } /*! Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected */ QList QCustomPlot::selectedPlottables() const { QList result; foreach (QCPAbstractPlottable *plottable, mPlottables) { if (plottable->selected()) result.append(plottable); } return result; } /*! Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a pos is returned. If \a onlySelectable is true, only plottables that are selectable (QCPAbstractPlottable::setSelectable) are considered. If there is no plottable at \a pos, the return value is 0. \see itemAt, layoutElementAt */ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const { QCPAbstractPlottable *resultPlottable = 0; double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value foreach (QCPAbstractPlottable *plottable, mPlottables) { if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable continue; if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes { double currentDistance = plottable->selectTest(pos, false); if (currentDistance >= 0 && currentDistance < resultDistance) { resultPlottable = plottable; resultDistance = currentDistance; } } } return resultPlottable; } /*! Returns whether this QCustomPlot instance contains the \a plottable. \see addPlottable */ bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const { return mPlottables.contains(plottable); } /*! Returns the graph with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last created graph, see QCustomPlot::graph() \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph(int index) const { if (index >= 0 && index < mGraphs.size()) { return mGraphs.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, returns 0. \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph() const { if (!mGraphs.isEmpty()) { return mGraphs.last(); } else return 0; } /*! Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a keyAxis and \a valueAxis must reside in this QCustomPlot. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically "y") for the graph. Returns a pointer to the newly created graph, or 0 if adding the graph failed. \see graph, graphCount, removeGraph, clearGraphs */ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) { if (!keyAxis) keyAxis = xAxis; if (!valueAxis) valueAxis = yAxis; if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; return 0; } if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; return 0; } QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); if (addPlottable(newGraph)) { newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size())); return newGraph; } else { delete newGraph; return 0; } } /*! Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If any other graphs in the plot have a channel fill set towards the removed graph, the channel fill property of those graphs is reset to zero (no channel fill). Returns true on success. \see clearGraphs */ bool QCustomPlot::removeGraph(QCPGraph *graph) { return removePlottable(graph); } /*! \overload Removes the graph by its \a index. */ bool QCustomPlot::removeGraph(int index) { if (index >= 0 && index < mGraphs.size()) return removeGraph(mGraphs[index]); else return false; } /*! Removes all graphs from the plot (and the QCustomPlot::legend, if necessary). Returns the number of graphs removed. \see removeGraph */ int QCustomPlot::clearGraphs() { int c = mGraphs.size(); for (int i=c-1; i >= 0; --i) removeGraph(mGraphs[i]); return c; } /*! Returns the number of currently existing graphs in the plot \see graph, addGraph */ int QCustomPlot::graphCount() const { return mGraphs.size(); } /*! Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars, etc., use \ref selectedPlottables. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected */ QList QCustomPlot::selectedGraphs() const { QList result; foreach (QCPGraph *graph, mGraphs) { if (graph->selected()) result.append(graph); } return result; } /*! Returns the item with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last added item, see QCustomPlot::item() \see itemCount, addItem */ QCPAbstractItem *QCustomPlot::item(int index) const { if (index >= 0 && index < mItems.size()) { return mItems.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last item, that was added with \ref addItem. If there are no items in the plot, returns 0. \see itemCount, addItem */ QCPAbstractItem *QCustomPlot::item() const { if (!mItems.isEmpty()) { return mItems.last(); } else return 0; } /*! Adds the specified item to the plot. QCustomPlot takes ownership of the item. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a item is this QCustomPlot. \see item, itemCount, removeItem, clearItems */ bool QCustomPlot::addItem(QCPAbstractItem *item) { if (!mItems.contains(item) && item->parentPlot() == this) { mItems.append(item); return true; } else { qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast(item); return false; } } /*! Removes the specified item from the plot. Returns true on success. \see addItem, clearItems */ bool QCustomPlot::removeItem(QCPAbstractItem *item) { if (mItems.contains(item)) { delete item; mItems.removeOne(item); return true; } else { qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); return false; } } /*! \overload Removes the item by its \a index. */ bool QCustomPlot::removeItem(int index) { if (index >= 0 && index < mItems.size()) return removeItem(mItems[index]); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return false; } } /*! Removes all items from the plot. Returns the number of items removed. \see removeItem */ int QCustomPlot::clearItems() { int c = mItems.size(); for (int i=c-1; i >= 0; --i) removeItem(mItems[i]); return c; } /*! Returns the number of currently existing items in the plot \see item, addItem */ int QCustomPlot::itemCount() const { return mItems.size(); } /*! Returns a list of the selected items. If no items are currently selected, the list is empty. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected */ QList QCustomPlot::selectedItems() const { QList result; foreach (QCPAbstractItem *item, mItems) { if (item->selected()) result.append(item); } return result; } /*! Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned. If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are considered. If there is no item at \a pos, the return value is 0. \see plottableAt, layoutElementAt */ QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { QCPAbstractItem *resultItem = 0; double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value foreach (QCPAbstractItem *item, mItems) { if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable continue; if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it { double currentDistance = item->selectTest(pos, false); if (currentDistance >= 0 && currentDistance < resultDistance) { resultItem = item; resultDistance = currentDistance; } } } return resultItem; } /*! Returns whether this QCustomPlot contains the \a item. \see addItem */ bool QCustomPlot::hasItem(QCPAbstractItem *item) const { return mItems.contains(item); } /*! Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is returned. Layer names are case-sensitive. \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(const QString &name) const { foreach (QCPLayer *layer, mLayers) { if (layer->name() == name) return layer; } return 0; } /*! \overload Returns the layer by \a index. If the index is invalid, 0 is returned. \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(int index) const { if (index >= 0 && index < mLayers.size()) { return mLayers.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! Returns the layer that is set as current layer (see \ref setCurrentLayer). */ QCPLayer *QCustomPlot::currentLayer() const { return mCurrentLayer; } /*! Sets the layer with the specified \a name to be the current layer. All layerables (\ref QCPLayerable), e.g. plottables and items, are created on the current layer. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. Layer names are case-sensitive. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer */ bool QCustomPlot::setCurrentLayer(const QString &name) { if (QCPLayer *newCurrentLayer = layer(name)) { return setCurrentLayer(newCurrentLayer); } else { qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; return false; } } /*! \overload Sets the provided \a layer to be the current layer. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. \see addLayer, moveLayer, removeLayer */ bool QCustomPlot::setCurrentLayer(QCPLayer *layer) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } mCurrentLayer = layer; return true; } /*! Returns the number of currently existing layers in the plot \see layer, addLayer */ int QCustomPlot::layerCount() const { return mLayers.size(); } /*! Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a valid layer inside this QCustomPlot. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. \see layer, moveLayer, removeLayer */ bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { if (!otherLayer) otherLayer = mLayers.last(); if (!mLayers.contains(otherLayer)) { qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); return false; } if (layer(name)) { qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; return false; } QCPLayer *newLayer = new QCPLayer(this, name); mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer); updateLayerIndices(); return true; } /*! Removes the specified \a layer and returns true on success. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both cases, the total rendering order of all layerables in the QCustomPlot is preserved. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom layer) becomes the new current layer. It is not possible to remove the last layer of the plot. \see layer, addLayer, moveLayer */ bool QCustomPlot::removeLayer(QCPLayer *layer) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } if (mLayers.size() < 2) { qDebug() << Q_FUNC_INFO << "can't remove last layer"; return false; } // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) int removedIndex = layer->index(); bool isFirstLayer = removedIndex==0; QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); QList children = layer->children(); if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same) { for (int i=children.size()-1; i>=0; --i) children.at(i)->moveToLayer(targetLayer, true); } else // append normally { for (int i=0; imoveToLayer(targetLayer, false); } // if removed layer is current layer, change current layer to layer below/above: if (layer == mCurrentLayer) setCurrentLayer(targetLayer); // remove layer: delete layer; mLayers.removeOne(layer); updateLayerIndices(); return true; } /*! Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or below is controlled with \a insertMode. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the QCustomPlot. \see layer, addLayer, moveLayer */ bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } if (!mLayers.contains(otherLayer)) { qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); return false; } mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0)); updateLayerIndices(); return true; } /*! Returns the number of axis rects in the plot. All axis rects can be accessed via QCustomPlot::axisRect(). Initially, only one axis rect exists in the plot. \see axisRect, axisRects */ int QCustomPlot::axisRectCount() const { return axisRects().size(); } /*! Returns the axis rect with \a index. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were added, all of them may be accessed with this function in a linear fashion (even when they are nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). \see axisRectCount, axisRects */ QCPAxisRect *QCustomPlot::axisRect(int index) const { const QList rectList = axisRects(); if (index >= 0 && index < rectList.size()) { return rectList.at(index); } else { qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; return 0; } } /*! Returns all axis rects in the plot. \see axisRectCount, axisRect */ QList QCustomPlot::axisRects() const { QList result; QStack elementStack; if (mPlotLayout) elementStack.push(mPlotLayout); while (!elementStack.isEmpty()) { foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) { if (element) { elementStack.push(element); if (QCPAxisRect *ar = qobject_cast(element)) result.append(ar); } } } return result; } /*! Returns the layout element at pixel position \a pos. If there is no element at that position, returns 0. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on any of its parent elements is set to false, it will not be considered. \see itemAt, plottableAt */ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const { QCPLayoutElement *currentElement = mPlotLayout; bool searchSubElements = true; while (searchSubElements && currentElement) { searchSubElements = false; foreach (QCPLayoutElement *subElement, currentElement->elements(false)) { if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) { currentElement = subElement; searchSubElements = true; break; } } } return currentElement; } /*! Returns the axes that currently have selected parts, i.e. whose selection state is not \ref QCPAxis::spNone. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, QCPAxis::setSelectableParts */ QList QCustomPlot::selectedAxes() const { QList result, allAxes; foreach (QCPAxisRect *rect, axisRects()) allAxes << rect->axes(); foreach (QCPAxis *axis, allAxes) { if (axis->selectedParts() != QCPAxis::spNone) result.append(axis); } return result; } /*! Returns the legends that currently have selected parts, i.e. whose selection state is not \ref QCPLegend::spNone. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, QCPLegend::setSelectableParts, QCPLegend::selectedItems */ QList QCustomPlot::selectedLegends() const { QList result; QStack elementStack; if (mPlotLayout) elementStack.push(mPlotLayout); while (!elementStack.isEmpty()) { foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) { if (subElement) { elementStack.push(subElement); if (QCPLegend *leg = qobject_cast(subElement)) { if (leg->selectedParts() != QCPLegend::spNone) result.append(leg); } } } } return result; } /*! Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. Since calling this function is not a user interaction, this does not emit the \ref selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the objects were previously selected. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends */ void QCustomPlot::deselectAll() { foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) layerable->deselectEvent(0); } } /*! Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the buffer on the QCustomPlot widget surface. This is the method that must be called to make changes, for example on the axis ranges or data points of graphs, visible. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the QCustomPlot widget and user interactions (object selection and range dragging/zooming). Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. */ void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) { if (mReplotting) // incase signals loop back to replot slot return; mReplotting = true; emit beforeReplot(); mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); QCPPainter painter; painter.begin(&mPaintBuffer); if (painter.isActive()) { painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) painter.fillRect(mViewport, mBackgroundBrush); draw(&painter); painter.end(); if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate) repaint(); else update(); } else // might happen if QCustomPlot has width or height zero qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer. This usually happens because QCustomPlot has width or height zero."; emit afterReplot(); mReplotting = false; } /*! Rescales the axes such that all plottables (like graphs) in the plot are fully visible. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true (QCPLayerable::setVisible), will be used to rescale the axes. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale */ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) { QList allAxes; foreach (QCPAxisRect *rect, axisRects()) allAxes << rect->axes(); foreach (QCPAxis *axis, allAxes) axis->rescale(onlyVisiblePlottables); } /*! Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale of texts and lines will be derived from the specified \a width and \a height. This means, the output will look like the normal on-screen output of a QCustomPlot widget with the corresponding pixel width and height. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter and QPen documentation. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. Returns true on success. \warning \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks). \li If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting PDF file. \note On Android systems, this method does nothing and issues an according qDebug warning message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set. \see savePng, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle) { bool success = false; #ifdef QT_NO_PRINTER Q_UNUSED(fileName) Q_UNUSED(noCosmeticPen) Q_UNUSED(width) Q_UNUSED(height) Q_UNUSED(pdfCreator) Q_UNUSED(pdfTitle) qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; #else int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } QPrinter printer(QPrinter::ScreenResolution); printer.setOutputFileName(fileName); printer.setOutputFormat(QPrinter::PdfFormat); printer.setColorMode(QPrinter::Color); printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0) printer.setFullPage(true); printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); #else QPageLayout pageLayout; pageLayout.setMode(QPageLayout::FullPageMode); pageLayout.setOrientation(QPageLayout::Portrait); pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); printer.setPageLayout(pageLayout); #endif QCPPainter printpainter; if (printpainter.begin(&printer)) { printpainter.setMode(QCPPainter::pmVectorized); printpainter.setMode(QCPPainter::pmNoCaching); printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen); printpainter.setWindow(mViewport); if (mBackgroundBrush.style() != Qt::NoBrush && mBackgroundBrush.color() != Qt::white && mBackgroundBrush.color() != Qt::transparent && mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent printpainter.fillRect(viewport(), mBackgroundBrush); draw(&printpainter); printpainter.end(); success = true; } setViewport(oldViewport); #endif // QT_NO_PRINTER return success; } /*! Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving. PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or -1 to use the default setting. Returns true on success. If this function fails, most likely the PNG format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality) { return saveRastered(fileName, width, height, scale, "PNG", quality); } /*! Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or -1 to use the default setting. Returns true on success. If this function fails, most likely the JPG format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, savePng, saveBmp, saveRastered */ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality) { return saveRastered(fileName, width, height, scale, "JPG", quality); } /*! Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. Returns true on success. If this function fails, most likely the BMP format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, savePng, saveJpg, saveRastered */ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale) { return saveRastered(fileName, width, height, scale, "BMP"); } /*! \internal Returns a minimum size hint that corresponds to the minimum size of the top level layout (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. This is especially important, when placed in a QLayout where other components try to take in as much space as possible (e.g. QMdiArea). */ QSize QCustomPlot::minimumSizeHint() const { return mPlotLayout->minimumSizeHint(); } /*! \internal Returns a size hint that is the same as \ref minimumSizeHint. */ QSize QCustomPlot::sizeHint() const { return mPlotLayout->minimumSizeHint(); } /*! \internal Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but draws the internal buffer on the widget surface. */ void QCustomPlot::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); painter.drawPixmap(0, 0, mPaintBuffer); } /*! \internal Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized appropriately. Finally a \ref replot is performed. */ void QCustomPlot::resizeEvent(QResizeEvent *event) { // resize and repaint the buffer: mPaintBuffer = QPixmap(event->size()); setViewport(rect()); replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts } /*! \internal Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to it. \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event) { emit mouseDoubleClick(event); QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // emit specialized object double click signals: if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) emit plottableDoubleClick(ap, event); else if (QCPAxis *ax = qobject_cast(clickedLayerable)) emit axisDoubleClick(ax, details.value(), event); else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) emit itemDoubleClick(ai, event); else if (QCPLegend *lg = qobject_cast(clickedLayerable)) emit legendDoubleClick(lg, 0, event); else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) emit legendDoubleClick(li->parentLegend(), li, event); else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) emit titleDoubleClick(event, pt); // call double click event of affected layout element: if (QCPLayoutElement *el = layoutElementAt(event->pos())) el->mouseDoubleClickEvent(event); // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case): if (mMouseEventElement) { mMouseEventElement->mouseReleaseEvent(event); mMouseEventElement = 0; } //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. } /*! \internal Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines the affected layout element and forwards the event to it. \see mouseMoveEvent, mouseReleaseEvent */ void QCustomPlot::mousePressEvent(QMouseEvent *event) { emit mousePress(event); mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release) // call event of affected layout element: mMouseEventElement = layoutElementAt(event->pos()); if (mMouseEventElement) mMouseEventElement->mousePressEvent(event); QWidget::mousePressEvent(event); } /*! \internal Event handler for when the cursor is moved. Emits the \ref mouseMove signal. If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout element before), the mouseMoveEvent is forwarded to that element. \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseMoveEvent(QMouseEvent *event) { emit mouseMove(event); // call event of affected layout element: if (mMouseEventElement) mMouseEventElement->mouseMoveEvent(event); QWidget::mouseMoveEvent(event); } /*! \internal Event handler for when a mouse button is released. Emits the \ref mouseRelease signal. If the mouse was moved less than a certain threshold in any direction since the \ref mousePressEvent, it is considered a click which causes the selection mechanism (if activated via \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.) If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout element before), the \ref mouseReleaseEvent is forwarded to that element. \see mousePressEvent, mouseMoveEvent */ void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) { emit mouseRelease(event); bool doReplot = false; if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation { if (event->button() == Qt::LeftButton) { // handle selection mechanism: QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details); bool selectionStateChanged = false; bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier); // deselect all other layerables if not additive selection: if (!additive) { foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) { if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory())) { bool selChanged = false; layerable->deselectEvent(&selChanged); selectionStateChanged |= selChanged; } } } } if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) { // a layerable was actually clicked, call its selectEvent: bool selChanged = false; clickedLayerable->selectEvent(event, additive, details, &selChanged); selectionStateChanged |= selChanged; } if (selectionStateChanged) { doReplot = true; emit selectionChangedByUser(); } } // emit specialized object click signals: QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) emit plottableClick(ap, event); else if (QCPAxis *ax = qobject_cast(clickedLayerable)) emit axisClick(ax, details.value(), event); else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) emit itemClick(ai, event); else if (QCPLegend *lg = qobject_cast(clickedLayerable)) emit legendClick(lg, 0, event); else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) emit legendClick(li->parentLegend(), li, event); else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) emit titleClick(event, pt); } // call event of affected layout element: if (mMouseEventElement) { mMouseEventElement->mouseReleaseEvent(event); mMouseEventElement = 0; } if (doReplot || noAntialiasingOnDrag()) replot(); QWidget::mouseReleaseEvent(event); } /*! \internal Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then determines the affected layout element and forwards the event to it. */ void QCustomPlot::wheelEvent(QWheelEvent *event) { emit mouseWheel(event); // call event of affected layout element: if (QCPLayoutElement *el = layoutElementAt(event->pos())) el->wheelEvent(event); QWidget::wheelEvent(event); } /*! \internal This is the main draw function. It draws the entire plot, including background pixmap, with the specified \a painter. Note that it does not fill the background with the background brush (as the user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter). */ void QCustomPlot::draw(QCPPainter *painter) { // run through layout phases: mPlotLayout->update(QCPLayoutElement::upPreparation); mPlotLayout->update(QCPLayoutElement::upMargins); mPlotLayout->update(QCPLayoutElement::upLayout); // draw viewport background pixmap: drawBackground(painter); // draw all layered objects (grid, axes, plottables, items, legend,...): foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *child, layer->children()) { if (child->realVisibility()) { painter->save(); painter->setClipRect(child->clipRect().translated(0, -1)); child->applyDefaultAntialiasingHint(painter); child->draw(painter); painter->restore(); } } } /* Debug code to draw all layout element rects foreach (QCPLayoutElement* el, findChildren()) { painter->setBrush(Qt::NoBrush); painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->rect()); painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->outerRect()); } */ } /*! \internal Draws the viewport background pixmap of the plot. If a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the viewport with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. Note that this function does not draw a fill with the background brush (\ref setBackground(const QBrush &brush)) beneath the pixmap. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::drawBackground(QCPPainter *painter) { // Note: background color is handled in individual replot/save functions // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mViewport.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); } } } /*! \internal This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. */ void QCustomPlot::axisRemoved(QCPAxis *axis) { if (xAxis == axis) xAxis = 0; if (xAxis2 == axis) xAxis2 = 0; if (yAxis == axis) yAxis = 0; if (yAxis2 == axis) yAxis2 = 0; // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers } /*! \internal This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so it may clear its QCustomPlot::legend member accordingly. */ void QCustomPlot::legendRemoved(QCPLegend *legend) { if (this->legend == legend) this->legend = 0; } /*! \internal Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called after every operation that changes the layer indices, like layer removal, layer creation, layer moving. */ void QCustomPlot::updateLayerIndices() const { for (int i=0; imIndex = i; } /*! \internal Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those layerables that are selectable will be considered. (Layerable subclasses communicate their selectability via the QCPLayerable::selectTest method, by returning -1.) \a selectionDetails is an output parameter that contains selection specifics of the affected layerable. This is useful if the respective layerable shall be given a subsequent QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains information about which part of the layerable was hit, in multi-part layerables (e.g. QCPAxis::SelectablePart). */ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const { for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) { const QList layerables = mLayers.at(layerIndex)->children(); double minimumDistance = selectionTolerance()*1.1; QCPLayerable *minimumDistanceLayerable = 0; for (int i=layerables.size()-1; i>=0; --i) { if (!layerables.at(i)->realVisibility()) continue; QVariant details; double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details); if (dist >= 0 && dist < minimumDistance) { minimumDistance = dist; minimumDistanceLayerable = layerables.at(i); if (selectionDetails) *selectionDetails = details; } } if (minimumDistance < selectionTolerance()) return minimumDistanceLayerable; } return 0; } /*! Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead to a full resolution file with width 200.) If the \a format supports compression, \a quality may be between 0 and 100 to control it. Returns true on success. If this function fails, most likely the given \a format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see saveBmp, saveJpg, savePng, savePdf */ bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality) { QPixmap buffer = toPixmap(width, height, scale); if (!buffer.isNull()) return buffer.save(fileName, format, quality); else return false; } /*! Renders the plot to a pixmap and returns it. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead to a full resolution pixmap with width 200.) \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf */ QPixmap QCustomPlot::toPixmap(int width, int height, double scale) { // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } int scaledWidth = qRound(scale*newWidth); int scaledHeight = qRound(scale*newHeight); QPixmap result(scaledWidth, scaledHeight); result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later QCPPainter painter; painter.begin(&result); if (painter.isActive()) { QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); painter.setMode(QCPPainter::pmNoCaching); if (!qFuzzyCompare(scale, 1.0)) { if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales painter.setMode(QCPPainter::pmNonCosmetic); painter.scale(scale, scale); } if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill painter.fillRect(mViewport, mBackgroundBrush); draw(&painter); setViewport(oldViewport); painter.end(); } else // might happen if pixmap has width or height zero { qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; return QPixmap(); } return result; } /*! Renders the plot using the passed \a painter. The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will appear scaled accordingly. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. \see toPixmap */ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) { // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } if (painter->isActive()) { QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); painter->setMode(QCPPainter::pmNoCaching); if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here painter->fillRect(mViewport, mBackgroundBrush); draw(painter); setViewport(oldViewport); } else qDebug() << Q_FUNC_INFO << "Passed painter is not active"; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorGradient //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorGradient \brief Defines a color gradient for use with e.g. \ref QCPColorMap This class describes a color gradient which can be used to encode data with color. For example, QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) with a \a position from 0 to 1. In between these defined color positions, the color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation. Alternatively, load one of the preset color gradients shown in the image below, with \ref loadPreset, or by directly specifying the preset in the constructor. \image html QCPColorGradient.png The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref GradientPreset to all the \a setGradient methods, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the color gradient shall be applied periodically (wrapping around) to data values that lie outside the data range specified on the plottable instance can be controlled with \ref setPeriodic. */ /*! Constructs a new QCPColorGradient initialized with the colors and color interpolation according to \a preset. The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient(GradientPreset preset) : mLevelCount(350), mColorInterpolation(ciRGB), mPeriodic(false), mColorBufferInvalidated(true) { mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); loadPreset(preset); } /* undocumented operator */ bool QCPColorGradient::operator==(const QCPColorGradient &other) const { return ((other.mLevelCount == this->mLevelCount) && (other.mColorInterpolation == this->mColorInterpolation) && (other.mPeriodic == this->mPeriodic) && (other.mColorStops == this->mColorStops)); } /*! Sets the number of discretization levels of the color gradient to \a n. The default is 350 which is typically enough to create a smooth appearance. \image html QCPColorGradient-levelcount.png */ void QCPColorGradient::setLevelCount(int n) { if (n < 2) { qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; n = 2; } if (n != mLevelCount) { mLevelCount = n; mColorBufferInvalidated = true; } } /*! Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the colors are the values of the passed QMap \a colorStops. In between these color stops, the color is interpolated according to \ref setColorInterpolation. A more convenient way to create a custom gradient may be to clear all color stops with \ref clearColorStops and then adding them one by one with \ref setColorStopAt. \see clearColorStops */ void QCPColorGradient::setColorStops(const QMap &colorStops) { mColorStops = colorStops; mColorBufferInvalidated = true; } /*! Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between these color stops, the color is interpolated according to \ref setColorInterpolation. \see setColorStops, clearColorStops */ void QCPColorGradient::setColorStopAt(double position, const QColor &color) { mColorStops.insert(position, color); mColorBufferInvalidated = true; } /*! Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be interpolated linearly in RGB or in HSV color space. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, whereas in HSV space the intermediate color is yellow. */ void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) { if (interpolation != mColorInterpolation) { mColorInterpolation = interpolation; mColorBufferInvalidated = true; } } /*! Sets whether data points that are outside the configured data range (e.g. \ref QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether they all have the same color, corresponding to the respective gradient boundary color. \image html QCPColorGradient-periodic.png As shown in the image above, gradients that have the same start and end color are especially suitable for a periodic gradient mapping, since they produce smooth color transitions throughout the color map. A preset that has this property is \ref gpHues. In practice, using periodic color gradients makes sense when the data corresponds to a periodic dimension, such as an angle or a phase. If this is not the case, the color encoding might become ambiguous, because multiple different data values are shown as the same color. */ void QCPColorGradient::setPeriodic(bool enabled) { mPeriodic = enabled; } /*! This method is used to quickly convert a \a data array to colors. The colors will be output in the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this function. The data range that shall be used for mapping the data value to the gradient is passed in \a range. \a logarithmic indicates whether the data values shall be mapped to colors logarithmically. if \a data actually contains 2D-data linearized via [row*columnCount + column], you can set \a dataIndexFactor to columnCount to convert a column instead of a row of the data array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data is addressed data[i*dataIndexFactor]. */ void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic) { // If you change something here, make sure to also adapt ::color() if (!data) { qDebug() << Q_FUNC_INFO << "null pointer given as data"; return; } if (!scanLine) { qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; return; } if (mColorBufferInvalidated) updateColorBuffer(); if (!logarithmic) { const double posToIndexFactor = (mLevelCount-1)/range.size(); if (mPeriodic) { for (int i=0; i= mLevelCount) index = mLevelCount-1; scanLine[i] = mColorBuffer.at(index); } } } else // logarithmic == true { if (mPeriodic) { for (int i=0; i= mLevelCount) index = mLevelCount-1; scanLine[i] = mColorBuffer.at(index); } } } } /*! \internal This method is used to colorize a single data value given in \a position, to colors. The data range that shall be used for mapping the data value to the gradient is passed in \a range. \a logarithmic indicates whether the data value shall be mapped to a color logarithmically. If an entire array of data values shall be converted, rather use \ref colorize, for better performance. */ QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic) { // If you change something here, make sure to also adapt ::colorize() if (mColorBufferInvalidated) updateColorBuffer(); int index = 0; if (!logarithmic) index = (position-range.lower)*(mLevelCount-1)/range.size(); else index = qLn(position/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1); if (mPeriodic) { index = index % mLevelCount; if (index < 0) index += mLevelCount; } else { if (index < 0) index = 0; else if (index >= mLevelCount) index = mLevelCount-1; } return mColorBuffer.at(index); } /*! Clears the current color stops and loads the specified \a preset. A preset consists of predefined color stops and the corresponding color interpolation method. The available presets are: \image html QCPColorGradient.png */ void QCPColorGradient::loadPreset(GradientPreset preset) { clearColorStops(); switch (preset) { case gpGrayscale: setColorInterpolation(ciRGB); setColorStopAt(0, Qt::black); setColorStopAt(1, Qt::white); break; case gpHot: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(50, 0, 0)); setColorStopAt(0.2, QColor(180, 10, 0)); setColorStopAt(0.4, QColor(245, 50, 0)); setColorStopAt(0.6, QColor(255, 150, 10)); setColorStopAt(0.8, QColor(255, 255, 50)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpCold: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 50)); setColorStopAt(0.2, QColor(0, 10, 180)); setColorStopAt(0.4, QColor(0, 50, 245)); setColorStopAt(0.6, QColor(10, 150, 255)); setColorStopAt(0.8, QColor(50, 255, 255)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpNight: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(10, 20, 30)); setColorStopAt(1, QColor(250, 255, 250)); break; case gpCandy: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(0, 0, 255)); setColorStopAt(1, QColor(255, 250, 250)); break; case gpGeography: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(70, 170, 210)); setColorStopAt(0.20, QColor(90, 160, 180)); setColorStopAt(0.25, QColor(45, 130, 175)); setColorStopAt(0.30, QColor(100, 140, 125)); setColorStopAt(0.5, QColor(100, 140, 100)); setColorStopAt(0.6, QColor(130, 145, 120)); setColorStopAt(0.7, QColor(140, 130, 120)); setColorStopAt(0.9, QColor(180, 190, 190)); setColorStopAt(1, QColor(210, 210, 230)); break; case gpIon: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(50, 10, 10)); setColorStopAt(0.45, QColor(0, 0, 255)); setColorStopAt(0.8, QColor(0, 255, 255)); setColorStopAt(1, QColor(0, 255, 0)); break; case gpThermal: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 50)); setColorStopAt(0.15, QColor(20, 0, 120)); setColorStopAt(0.33, QColor(200, 30, 140)); setColorStopAt(0.6, QColor(255, 100, 0)); setColorStopAt(0.85, QColor(255, 255, 40)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpPolar: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(50, 255, 255)); setColorStopAt(0.18, QColor(10, 70, 255)); setColorStopAt(0.28, QColor(10, 10, 190)); setColorStopAt(0.5, QColor(0, 0, 0)); setColorStopAt(0.72, QColor(190, 10, 10)); setColorStopAt(0.82, QColor(255, 70, 10)); setColorStopAt(1, QColor(255, 255, 50)); break; case gpSpectrum: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(50, 0, 50)); setColorStopAt(0.15, QColor(0, 0, 255)); setColorStopAt(0.35, QColor(0, 255, 255)); setColorStopAt(0.6, QColor(255, 255, 0)); setColorStopAt(0.75, QColor(255, 30, 0)); setColorStopAt(1, QColor(50, 0, 0)); break; case gpJet: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 100)); setColorStopAt(0.15, QColor(0, 50, 255)); setColorStopAt(0.35, QColor(0, 255, 255)); setColorStopAt(0.65, QColor(255, 255, 0)); setColorStopAt(0.85, QColor(255, 30, 0)); setColorStopAt(1, QColor(100, 0, 0)); break; case gpHues: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(255, 0, 0)); setColorStopAt(1.0/3.0, QColor(0, 0, 255)); setColorStopAt(2.0/3.0, QColor(0, 255, 0)); setColorStopAt(1, QColor(255, 0, 0)); break; } } /*! Clears all color stops. \see setColorStops, setColorStopAt */ void QCPColorGradient::clearColorStops() { mColorStops.clear(); mColorBufferInvalidated = true; } /*! Returns an inverted gradient. The inverted gradient has all properties as this \ref QCPColorGradient, but the order of the color stops is inverted. \see setColorStops, setColorStopAt */ QCPColorGradient QCPColorGradient::inverted() const { QCPColorGradient result(*this); result.clearColorStops(); for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) result.setColorStopAt(1.0-it.key(), it.value()); return result; } /*! \internal Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly convert positions to colors. This is where the interpolation between color stops is calculated. */ void QCPColorGradient::updateColorBuffer() { if (mColorBuffer.size() != mLevelCount) mColorBuffer.resize(mLevelCount); if (mColorStops.size() > 1) { double indexToPosFactor = 1.0/(double)(mLevelCount-1); for (int i=0; i::const_iterator it = mColorStops.lowerBound(position); if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop { mColorBuffer[i] = (it-1).value().rgb(); } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop { mColorBuffer[i] = it.value().rgb(); } else // position is in between stops (or on an intermediate stop), interpolate color { QMap::const_iterator high = it; QMap::const_iterator low = it-1; double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 switch (mColorInterpolation) { case ciRGB: { mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(), (1-t)*low.value().green() + t*high.value().green(), (1-t)*low.value().blue() + t*high.value().blue()); break; } case ciHSV: { QColor lowHsv = low.value().toHsv(); QColor highHsv = high.value().toHsv(); double hue = 0; double hueDiff = highHsv.hueF()-lowHsv.hueF(); if (hueDiff > 0.5) hue = lowHsv.hueF() - t*(1.0-hueDiff); else if (hueDiff < -0.5) hue = lowHsv.hueF() + t*(1.0+hueDiff); else hue = lowHsv.hueF() + t*hueDiff; if (hue < 0) hue += 1.0; else if (hue >= 1.0) hue -= 1.0; mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); break; } } } } } else if (mColorStops.size() == 1) { mColorBuffer.fill(mColorStops.constBegin().value().rgb()); } else // mColorStops is empty, fill color buffer with black { mColorBuffer.fill(qRgb(0, 0, 0)); } mColorBufferInvalidated = false; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisRect //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisRect \brief Holds multiple axes and arranges them in a rectangular shape. This class represents an axis rect, a rectangular area that is bounded on all sides with an arbitrary number of axes. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the layout system allows to have multiple axis rects, e.g. arranged in a grid layout (QCustomPlot::plotLayout). By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref addAxes. To remove an axis, use \ref removeAxis. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be placed on other layers, independently of the axis rect. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref insetLayout and can be used to have other layout elements (or even other layouts with multiple elements) hovering inside the axis rect. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed line on the far left indicates the viewport/widget border.
*/ /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. \see QCPLayoutInset */ /*! \fn int QCPAxisRect::left() const Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::right() const Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::top() const Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::bottom() const Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::width() const Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::height() const Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPAxisRect::size() const Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topLeft() const Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topRight() const Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomLeft() const Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomRight() const Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::center() const Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /* end documentation of inline functions */ /*! Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four sides, the top and right axes are set invisible initially. */ QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : QCPLayoutElement(parentPlot), mBackgroundBrush(Qt::NoBrush), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mInsetLayout(new QCPLayoutInset), mRangeDrag(Qt::Horizontal|Qt::Vertical), mRangeZoom(Qt::Horizontal|Qt::Vertical), mRangeZoomFactorHorz(0.85), mRangeZoomFactorVert(0.85), mDragging(false) { mInsetLayout->initializeParentPlot(mParentPlot); mInsetLayout->setParentLayerable(this); mInsetLayout->setParent(this); setMinimumSize(50, 50); setMinimumMargins(QMargins(15, 15, 15, 15)); mAxes.insert(QCPAxis::atLeft, QList()); mAxes.insert(QCPAxis::atRight, QList()); mAxes.insert(QCPAxis::atTop, QList()); mAxes.insert(QCPAxis::atBottom, QList()); if (setupDefaultAxes) { QCPAxis *xAxis = addAxis(QCPAxis::atBottom); QCPAxis *yAxis = addAxis(QCPAxis::atLeft); QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); setRangeDragAxes(xAxis, yAxis); setRangeZoomAxes(xAxis, yAxis); xAxis2->setVisible(false); yAxis2->setVisible(false); xAxis->grid()->setVisible(true); yAxis->grid()->setVisible(true); xAxis2->grid()->setVisible(false); yAxis2->grid()->setVisible(false); xAxis2->grid()->setZeroLinePen(Qt::NoPen); yAxis2->grid()->setZeroLinePen(Qt::NoPen); xAxis2->grid()->setVisible(false); yAxis2->grid()->setVisible(false); } } QCPAxisRect::~QCPAxisRect() { delete mInsetLayout; mInsetLayout = 0; QList axesList = axes(); for (int i=0; i ax(mAxes.value(type)); if (index >= 0 && index < ax.size()) { return ax.at(index); } else { qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; return 0; } } /*! Returns all axes on the axis rect sides specified with \a types. \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of multiple sides. \see axis */ QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const { QList result; if (types.testFlag(QCPAxis::atLeft)) result << mAxes.value(QCPAxis::atLeft); if (types.testFlag(QCPAxis::atRight)) result << mAxes.value(QCPAxis::atRight); if (types.testFlag(QCPAxis::atTop)) result << mAxes.value(QCPAxis::atTop); if (types.testFlag(QCPAxis::atBottom)) result << mAxes.value(QCPAxis::atBottom); return result; } /*! \overload Returns all axes of this axis rect. */ QList QCPAxisRect::axes() const { QList result; QHashIterator > it(mAxes); while (it.hasNext()) { it.next(); result << it.value(); } return result; } /*! Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a new QCPAxis instance is created internally. You may inject QCPAxis instances (or sublasses of QCPAxis) by setting \a axis to an axis that was previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership of the axis, so you may not delete it afterwards. Further, the \a axis must have been created with this axis rect as parent and with the same axis type as specified in \a type. If this is not the case, a debug output is generated, the axis is not added, and the method returns 0. This method can not be used to move \a axis between axis rects. The same \a axis instance must not be added multiple times to the same or different axis rects. If an axis rect side already contains one or more axes, the lower and upper endings of the new axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref QCPLineEnding::esHalfBar. \see addAxes, setupFullAxesBox */ QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis) { QCPAxis *newAxis = axis; if (!newAxis) { newAxis = new QCPAxis(this, type); } else // user provided existing axis instance, do some sanity checks { if (newAxis->axisType() != type) { qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; return 0; } if (newAxis->axisRect() != this) { qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; return 0; } if (axes().contains(newAxis)) { qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; return 0; } } if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset { bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); } mAxes[type].append(newAxis); return newAxis; } /*! Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. Returns a list of the added axes. \see addAxis, setupFullAxesBox */ QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) { QList result; if (types.testFlag(QCPAxis::atLeft)) result << addAxis(QCPAxis::atLeft); if (types.testFlag(QCPAxis::atRight)) result << addAxis(QCPAxis::atRight); if (types.testFlag(QCPAxis::atTop)) result << addAxis(QCPAxis::atTop); if (types.testFlag(QCPAxis::atBottom)) result << addAxis(QCPAxis::atBottom); return result; } /*! Removes the specified \a axis from the axis rect and deletes it. Returns true on success, i.e. if \a axis was a valid axis in this axis rect. \see addAxis */ bool QCPAxisRect::removeAxis(QCPAxis *axis) { // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: QHashIterator > it(mAxes); while (it.hasNext()) { it.next(); if (it.value().contains(axis)) { mAxes[it.key()].removeOne(axis); if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) parentPlot()->axisRemoved(axis); delete axis; return true; } } qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); return false; } /*! Convenience function to create an axis on each side that doesn't have any axes yet and set their visibility to true. Further, the top/right axes are assigned the following properties of the bottom/left axes: \li range (\ref QCPAxis::setRange) \li range reversed (\ref QCPAxis::setRangeReversed) \li scale type (\ref QCPAxis::setScaleType) \li scale log base (\ref QCPAxis::setScaleLogBase) \li ticks (\ref QCPAxis::setTicks) \li auto (major) tick count (\ref QCPAxis::setAutoTickCount) \li sub tick count (\ref QCPAxis::setSubTickCount) \li auto sub ticks (\ref QCPAxis::setAutoSubTicks) \li tick step (\ref QCPAxis::setTickStep) \li auto tick step (\ref QCPAxis::setAutoTickStep) \li number format (\ref QCPAxis::setNumberFormat) \li number precision (\ref QCPAxis::setNumberPrecision) \li tick label type (\ref QCPAxis::setTickLabelType) \li date time format (\ref QCPAxis::setDateTimeFormat) \li date time spec (\ref QCPAxis::setDateTimeSpec) Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes. */ void QCPAxisRect::setupFullAxesBox(bool connectRanges) { QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; if (axisCount(QCPAxis::atBottom) == 0) xAxis = addAxis(QCPAxis::atBottom); else xAxis = axis(QCPAxis::atBottom); if (axisCount(QCPAxis::atLeft) == 0) yAxis = addAxis(QCPAxis::atLeft); else yAxis = axis(QCPAxis::atLeft); if (axisCount(QCPAxis::atTop) == 0) xAxis2 = addAxis(QCPAxis::atTop); else xAxis2 = axis(QCPAxis::atTop); if (axisCount(QCPAxis::atRight) == 0) yAxis2 = addAxis(QCPAxis::atRight); else yAxis2 = axis(QCPAxis::atRight); xAxis->setVisible(true); yAxis->setVisible(true); xAxis2->setVisible(true); yAxis2->setVisible(true); xAxis2->setTickLabels(false); yAxis2->setTickLabels(false); xAxis2->setRange(xAxis->range()); xAxis2->setRangeReversed(xAxis->rangeReversed()); xAxis2->setScaleType(xAxis->scaleType()); xAxis2->setScaleLogBase(xAxis->scaleLogBase()); xAxis2->setTicks(xAxis->ticks()); xAxis2->setAutoTickCount(xAxis->autoTickCount()); xAxis2->setSubTickCount(xAxis->subTickCount()); xAxis2->setAutoSubTicks(xAxis->autoSubTicks()); xAxis2->setTickStep(xAxis->tickStep()); xAxis2->setAutoTickStep(xAxis->autoTickStep()); xAxis2->setNumberFormat(xAxis->numberFormat()); xAxis2->setNumberPrecision(xAxis->numberPrecision()); xAxis2->setTickLabelType(xAxis->tickLabelType()); xAxis2->setDateTimeFormat(xAxis->dateTimeFormat()); xAxis2->setDateTimeSpec(xAxis->dateTimeSpec()); yAxis2->setRange(yAxis->range()); yAxis2->setRangeReversed(yAxis->rangeReversed()); yAxis2->setScaleType(yAxis->scaleType()); yAxis2->setScaleLogBase(yAxis->scaleLogBase()); yAxis2->setTicks(yAxis->ticks()); yAxis2->setAutoTickCount(yAxis->autoTickCount()); yAxis2->setSubTickCount(yAxis->subTickCount()); yAxis2->setAutoSubTicks(yAxis->autoSubTicks()); yAxis2->setTickStep(yAxis->tickStep()); yAxis2->setAutoTickStep(yAxis->autoTickStep()); yAxis2->setNumberFormat(yAxis->numberFormat()); yAxis2->setNumberPrecision(yAxis->numberPrecision()); yAxis2->setTickLabelType(yAxis->tickLabelType()); yAxis2->setDateTimeFormat(yAxis->dateTimeFormat()); yAxis2->setDateTimeSpec(yAxis->dateTimeSpec()); if (connectRanges) { connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); } } /*! Returns a list of all the plottables that are associated with this axis rect. A plottable is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. \see graphs, items */ QList QCPAxisRect::plottables() const { // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries QList result; for (int i=0; imPlottables.size(); ++i) { if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) result.append(mParentPlot->mPlottables.at(i)); } return result; } /*! Returns a list of all the graphs that are associated with this axis rect. A graph is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. \see plottables, items */ QList QCPAxisRect::graphs() const { // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries QList result; for (int i=0; imGraphs.size(); ++i) { if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) result.append(mParentPlot->mGraphs.at(i)); } return result; } /*! Returns a list of all the items that are associated with this axis rect. An item is considered associated with an axis rect if any of its positions has key or value axis set to an axis that is in this axis rect, or if any of its positions has \ref QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref QCPAbstractItem::setClipAxisRect) is set to this axis rect. \see plottables, graphs */ QList QCPAxisRect::items() const { // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries // and miss those items that have this axis rect as clipAxisRect. QList result; for (int itemId=0; itemIdmItems.size(); ++itemId) { if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) { result.append(mParentPlot->mItems.at(itemId)); continue; } QList positions = mParentPlot->mItems.at(itemId)->positions(); for (int posId=0; posIdaxisRect() == this || positions.at(posId)->keyAxis()->axisRect() == this || positions.at(posId)->valueAxis()->axisRect() == this) { result.append(mParentPlot->mItems.at(itemId)); break; } } } return result; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPAxisRect. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update), and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its QCPInsetLayout::update function. */ void QCPAxisRect::update(UpdatePhase phase) { QCPLayoutElement::update(phase); switch (phase) { case upPreparation: { QList allAxes = axes(); for (int i=0; isetupTickVectors(); break; } case upLayout: { mInsetLayout->setOuterRect(rect()); break; } default: break; } // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): mInsetLayout->update(phase); } /* inherits documentation from base class */ QList QCPAxisRect::elements(bool recursive) const { QList result; if (mInsetLayout) { result << mInsetLayout; if (recursive) result << mInsetLayout->elements(recursive); } return result; } /* inherits documentation from base class */ void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const { painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPAxisRect::draw(QCPPainter *painter) { drawBackground(painter); } /*! Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! \overload Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. The brush will be drawn before (under) any background pixmap, which may be specified with \ref setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. \see setBackground(const QPixmap &pm) */ void QCPAxisRect::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCPAxisRect::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved. \see setBackground, setBackgroundScaled */ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } /*! Returns the range drag axis of the \a orientation provided. \see setRangeDragAxes */ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); } /*! Returns the range zoom axis of the \a orientation provided. \see setRangeZoomAxes */ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); } /*! Returns the range zoom factor of the \a orientation provided. \see setRangeZoomFactor */ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); } /*! Sets which axis orientation may be range dragged by the user with mouse interaction. What orientation corresponds to which specific axis can be set with \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag to enable the range dragging interaction. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag */ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) { mRangeDrag = orientations; } /*! Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeZoom to enable the range zooming interaction. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag */ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) { mRangeZoom = orientations; } /*! Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on the QCustomPlot widget. \see setRangeZoomAxes */ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) { mRangeDragHorzAxis = horizontal; mRangeDragVertAxis = vertical; } /*! Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor). \see setRangeDragAxes */ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) { mRangeZoomHorzAxis = horizontal; mRangeZoomVertAxis = vertical; } /*! Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal and which is vertical, can be set with \ref setRangeZoomAxes. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user) will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the same scrolling direction will zoom out. */ void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) { mRangeZoomFactorHorz = horizontalFactor; mRangeZoomFactorVert = verticalFactor; } /*! \overload Sets both the horizontal and vertical zoom \a factor. */ void QCPAxisRect::setRangeZoomFactor(double factor) { mRangeZoomFactorHorz = factor; mRangeZoomFactorVert = factor; } /*! \internal Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was set. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::drawBackground(QCPPainter *painter) { // draw background fill: if (mBackgroundBrush != Qt::NoBrush) painter->fillRect(mRect, mBackgroundBrush); // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mRect.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); } } } /*! \internal This function makes sure multiple axes on the side specified with \a type don't collide, but are distributed according to their respective space requirement (QCPAxis::calculateMargin). It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the one with index zero. This function is called by \ref calculateAutoMargin. */ void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) { const QList axesList = mAxes.value(type); if (axesList.isEmpty()) return; bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) { if (!isFirstVisible) offset += axesList.at(i)->tickLengthIn(); isFirstVisible = false; } axesList.at(i)->setOffset(offset); } } /* inherits documentation from base class */ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) { if (!mAutoMargins.testFlag(side)) qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; updateAxesOffset(QCPAxis::marginSideToAxisType(side)); // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); if (axesList.size() > 0) return axesList.last()->offset() + axesList.last()->calculateMargin(); else return 0; } /*! \internal Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is pressed, the range dragging interaction is initialized (the actual range manipulation happens in the \ref mouseMoveEvent). The mDragging flag is set to true and some anchor points are set that are needed to determine the distance the mouse was dragged in the mouse move/release events later. \see mouseMoveEvent, mouseReleaseEvent */ void QCPAxisRect::mousePressEvent(QMouseEvent *event) { mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release) if (event->buttons() & Qt::LeftButton) { mDragging = true; // initialize antialiasing backup in case we start dragging: if (mParentPlot->noAntialiasingOnDrag()) { mAADragBackup = mParentPlot->antialiasedElements(); mNotAADragBackup = mParentPlot->notAntialiasedElements(); } // Mouse range dragging interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { if (mRangeDragHorzAxis) mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); if (mRangeDragVertAxis) mDragStartVertRange = mRangeDragVertAxis.data()->range(); } } } /*! \internal Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. \see mousePressEvent, mouseReleaseEvent */ void QCPAxisRect::mouseMoveEvent(QMouseEvent *event) { // Mouse range dragging interaction: if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { if (mRangeDrag.testFlag(Qt::Horizontal)) { if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) { if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear) { double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x()); rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff); } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic) { double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x()); rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff); } } } if (mRangeDrag.testFlag(Qt::Vertical)) { if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) { if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear) { double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y()); rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff); } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic) { double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y()); rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff); } } } if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot { if (mParentPlot->noAntialiasingOnDrag()) mParentPlot->setNotAntialiasedElements(QCP::aeAll); mParentPlot->replot(); } } } /* inherits documentation from base class */ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event) { Q_UNUSED(event) mDragging = false; if (mParentPlot->noAntialiasingOnDrag()) { mParentPlot->setAntialiasedElements(mAADragBackup); mParentPlot->setNotAntialiasedElements(mNotAADragBackup); } } /*! \internal Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of the scaling operation is the current cursor position inside the axis rect. The scaling factor is dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of the range zoom factor. This takes care of the wheel direction automatically, by inverting the factor, when the wheel step is negative (f^-1 = 1/f). */ void QCPAxisRect::wheelEvent(QWheelEvent *event) { // Mouse range zooming interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { if (mRangeZoom != 0) { double factor; double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually if (mRangeZoom.testFlag(Qt::Horizontal)) { factor = qPow(mRangeZoomFactorHorz, wheelSteps); if (mRangeZoomHorzAxis.data()) mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x())); } if (mRangeZoom.testFlag(Qt::Vertical)) { factor = qPow(mRangeZoomFactorVert, wheelSteps); if (mRangeZoomVertAxis.data()) mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y())); } mParentPlot->replot(); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractLegendItem \brief The abstract base class for all entries in a QCPLegend. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the legend, the subclass \ref QCPPlottableLegendItem is more suitable. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry that's not even associated with a plottable). You must implement the following pure virtual functions: \li \ref draw (from QCPLayerable) You inherit the following members you may use:
QCPLegend *\b mParentLegend A pointer to the parent QCPLegend.
QFont \b mFont The generic font of the item. You should use this font for all or at least the most prominent text of the item.
*/ /* start of documentation of signals */ /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) This signal is emitted when the selection state of this legend item has changed, either by user interaction or by a direct call to \ref setSelected. */ /* end of documentation of signals */ /*! Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. */ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : QCPLayoutElement(parent->parentPlot()), mParentLegend(parent), mFont(parent->font()), mTextColor(parent->textColor()), mSelectedFont(parent->selectedFont()), mSelectedTextColor(parent->selectedTextColor()), mSelectable(true), mSelected(false) { setLayer(QLatin1String("legend")); setMargins(QMargins(8, 2, 8, 2)); } /*! Sets the default font of this specific legend item to \a font. \see setTextColor, QCPLegend::setFont */ void QCPAbstractLegendItem::setFont(const QFont &font) { mFont = font; } /*! Sets the default text color of this specific legend item to \a color. \see setFont, QCPLegend::setTextColor */ void QCPAbstractLegendItem::setTextColor(const QColor &color) { mTextColor = color; } /*! When this legend item is selected, \a font is used to draw generic text, instead of the normal font set with \ref setFont. \see setFont, QCPLegend::setSelectedFont */ void QCPAbstractLegendItem::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! When this legend item is selected, \a color is used to draw generic text, instead of the normal color set with \ref setTextColor. \see setTextColor, QCPLegend::setSelectedTextColor */ void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; } /*! Sets whether this specific legend item is selectable. \see setSelectedParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this specific legend item is selected. It is possible to set the selection state of this item by calling this function directly, even if setSelectable is set to false. \see setSelectableParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /* inherits documentation from base class */ double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (!mParentPlot) return -1; if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) return -1; if (mRect.contains(pos.toPoint())) return mParentPlot->selectionTolerance()*0.99; else return -1; } /* inherits documentation from base class */ void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); } /* inherits documentation from base class */ QRect QCPAbstractLegendItem::clipRect() const { return mOuterRect; } /* inherits documentation from base class */ void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) { if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPlottableLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlottableLegendItem \brief A legend item representing a plottable with an icon and the plottable name. This is the standard legend item for plottables. It displays an icon of the plottable next to the plottable name. The icon is drawn by the respective plottable itself (\ref QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the middle. Legend items of this type are always associated with one plottable (retrievable via the plottable() function and settable with the constructor). You may change the font of the plottable name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend creates/removes legend items of this type in the default implementation. However, these functions may be reimplemented such that a different kind of legend item (e.g a direct subclass of QCPAbstractLegendItem) is used for that plottable. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout interface, QCPLegend has specialized functions for handling legend items conveniently, see the documentation of \ref QCPLegend. */ /*! Creates a new legend item associated with \a plottable. Once it's created, it can be added to the legend via \ref QCPLegend::addItem. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. */ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : QCPAbstractLegendItem(parent), mPlottable(plottable) { } /*! \internal Returns the pen that shall be used to draw the icon border, taking into account the selection state of this item. */ QPen QCPPlottableLegendItem::getIconBorderPen() const { return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } /*! \internal Returns the text color that shall be used to draw text, taking into account the selection state of this item. */ QColor QCPPlottableLegendItem::getTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } /*! \internal Returns the font that shall be used to draw text, taking into account the selection state of this item. */ QFont QCPPlottableLegendItem::getFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Draws the item with \a painter. The size and position of the drawn legend item is defined by the parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint of this legend item. */ void QCPPlottableLegendItem::draw(QCPPainter *painter) { if (!mPlottable) return; painter->setFont(getFont()); painter->setPen(QPen(getTextColor())); QSizeF iconSize = mParentLegend->iconSize(); QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); QRectF iconRect(mRect.topLeft(), iconSize); int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); // draw icon: painter->save(); painter->setClipRect(iconRect, Qt::IntersectClip); mPlottable->drawLegendIcon(painter, iconRect); painter->restore(); // draw icon border: if (getIconBorderPen().style() != Qt::NoPen) { painter->setPen(getIconBorderPen()); painter->setBrush(Qt::NoBrush); painter->drawRect(iconRect); } } /*! \internal Calculates and returns the size of this item. This includes the icon, the text and the padding in between. */ QSize QCPPlottableLegendItem::minimumSizeHint() const { if (!mPlottable) return QSize(); QSize result(0, 0); QRect textRect; QFontMetrics fontMetrics(getFont()); QSize iconSize = mParentLegend->iconSize(); textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right()); result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom()); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLegend //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLegend \brief Manages a legend inside a QCustomPlot. A legend is a small box somewhere in the plot which lists plottables with their name and icon. Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc. The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are placed in the grid layout of the legend. QCPLegend only adds an interface specialized for handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface. However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will only return the number of items with QCPAbstractLegendItems type). By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface. */ /* start of documentation of signals */ /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); This signal is emitted when the selection state of this legend has changed. \see setSelectedParts, setSelectableParts */ /* end of documentation of signals */ /*! Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values. Note that by default, QCustomPlot already contains a legend ready to be used as QCustomPlot::legend */ QCPLegend::QCPLegend() { setRowSpacing(0); setColumnSpacing(10); setMargins(QMargins(2, 3, 2, 2)); setAntialiased(false); setIconSize(32, 18); setIconTextPadding(7); setSelectableParts(spLegendBox | spItems); setSelectedParts(spNone); setBorderPen(QPen(Qt::black)); setSelectedBorderPen(QPen(Qt::blue, 2)); setIconBorderPen(Qt::NoPen); setSelectedIconBorderPen(QPen(Qt::blue, 2)); setBrush(Qt::white); setSelectedBrush(Qt::white); setTextColor(Qt::black); setSelectedTextColor(Qt::blue); } QCPLegend::~QCPLegend() { clearItems(); if (qobject_cast(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) mParentPlot->legendRemoved(this); } /* no doc for getter, see setSelectedParts */ QCPLegend::SelectableParts QCPLegend::selectedParts() const { // check whether any legend elements selected, if yes, add spItems to return value bool hasSelectedItems = false; for (int i=0; iselected()) { hasSelectedItems = true; break; } } if (hasSelectedItems) return mSelectedParts | spItems; else return mSelectedParts & ~spItems; } /*! Sets the pen, the border of the entire legend is drawn with. */ void QCPLegend::setBorderPen(const QPen &pen) { mBorderPen = pen; } /*! Sets the brush of the legend background. */ void QCPLegend::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will use this font by default. However, a different font can be specified on a per-item-basis by accessing the specific legend item. This function will also set \a font on all already existing legend items. \see QCPAbstractLegendItem::setFont */ void QCPLegend::setFont(const QFont &font) { mFont = font; for (int i=0; isetFont(mFont); } } /*! Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) will use this color by default. However, a different colors can be specified on a per-item-basis by accessing the specific legend item. This function will also set \a color on all already existing legend items. \see QCPAbstractLegendItem::setTextColor */ void QCPLegend::setTextColor(const QColor &color) { mTextColor = color; for (int i=0; isetTextColor(color); } } /*! Sets the size of legend icons. Legend items that draw an icon (e.g. a visual representation of the graph) will use this size by default. */ void QCPLegend::setIconSize(const QSize &size) { mIconSize = size; } /*! \overload */ void QCPLegend::setIconSize(int width, int height) { mIconSize.setWidth(width); mIconSize.setHeight(height); } /*! Sets the horizontal space in pixels between the legend icon and the text next to it. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the name of the graph) will use this space by default. */ void QCPLegend::setIconTextPadding(int padding) { mIconTextPadding = padding; } /*! Sets the pen used to draw a border around each legend icon. Legend items that draw an icon (e.g. a visual representation of the graph) will use this pen by default. If no border is wanted, set this to \a Qt::NoPen. */ void QCPLegend::setIconBorderPen(const QPen &pen) { mIconBorderPen = pen; } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPLegend::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected doesn't contain \ref spItems, those items become deselected. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions contains iSelectLegend. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part even when \ref setSelectableParts was set to a value that actually excludes the part. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set before, because there's no way to specify which exact items to newly select. Do this by calling \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont */ void QCPLegend::setSelectedParts(const SelectableParts &selected) { SelectableParts newSelected = selected; mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed if (mSelectedParts != newSelected) { if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) { qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; newSelected &= ~spItems; } if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection { for (int i=0; isetSelected(false); } } mSelectedParts = newSelected; emit selectionChanged(mSelectedParts); } } /*! When the legend box is selected, this pen is used to draw the border instead of the normal pen set via \ref setBorderPen. \see setSelectedParts, setSelectableParts, setSelectedBrush */ void QCPLegend::setSelectedBorderPen(const QPen &pen) { mSelectedBorderPen = pen; } /*! Sets the pen legend items will use to draw their icon borders, when they are selected. \see setSelectedParts, setSelectableParts, setSelectedFont */ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) { mSelectedIconBorderPen = pen; } /*! When the legend box is selected, this brush is used to draw the legend background instead of the normal brush set via \ref setBrush. \see setSelectedParts, setSelectableParts, setSelectedBorderPen */ void QCPLegend::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the default font that is used by legend items when they are selected. This function will also set \a font on all already existing legend items. \see setFont, QCPAbstractLegendItem::setSelectedFont */ void QCPLegend::setSelectedFont(const QFont &font) { mSelectedFont = font; for (int i=0; isetSelectedFont(font); } } /*! Sets the default text color that is used by legend items when they are selected. This function will also set \a color on all already existing legend items. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor */ void QCPLegend::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; for (int i=0; isetSelectedTextColor(color); } } /*! Returns the item with index \a i. \see itemCount */ QCPAbstractLegendItem *QCPLegend::item(int index) const { return qobject_cast(elementAt(index)); } /*! Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns 0. \see hasItemWithPlottable */ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const { for (int i=0; i(item(i))) { if (pli->plottable() == plottable) return pli; } } return 0; } /*! Returns the number of items currently in the legend. \see item */ int QCPLegend::itemCount() const { return elementCount(); } /*! Returns whether the legend contains \a itm. */ bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const { for (int i=0; iitem(i)) return true; } return false; } /*! Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns false. \see itemWithPlottable */ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const { return itemWithPlottable(plottable); } /*! Adds \a item to the legend, if it's not present already. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added. The legend takes ownership of the item. */ bool QCPLegend::addItem(QCPAbstractLegendItem *item) { if (!hasItem(item)) { return addElement(rowCount(), 0, item); } else return false; } /*! Removes the item with index \a index from the legend. Returns true, if successful. \see itemCount, clearItems */ bool QCPLegend::removeItem(int index) { if (QCPAbstractLegendItem *ali = item(index)) { bool success = remove(ali); simplify(); return success; } else return false; } /*! \overload Removes \a item from the legend. Returns true, if successful. \see clearItems */ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) { bool success = remove(item); simplify(); return success; } /*! Removes all items from the legend. */ void QCPLegend::clearItems() { for (int i=itemCount()-1; i>=0; --i) removeItem(i); } /*! Returns the legend items that are currently selected. If no items are selected, the list is empty. \see QCPAbstractLegendItem::setSelected, setSelectable */ QList QCPLegend::selectedItems() const { QList result; for (int i=0; iselected()) result.append(ali); } } return result; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing main legend elements. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); } /*! \internal Returns the pen used to paint the border of the legend, taking into account the selection state of the legend box. */ QPen QCPLegend::getBorderPen() const { return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; } /*! \internal Returns the brush used to paint the background of the legend, taking into account the selection state of the legend box. */ QBrush QCPLegend::getBrush() const { return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; } /*! \internal Draws the legend box with the provided \a painter. The individual legend items are layerables themselves, thus are drawn independently. */ void QCPLegend::draw(QCPPainter *painter) { // draw background rect: painter->setBrush(getBrush()); painter->setPen(getBorderPen()); painter->drawRect(mOuterRect); } /* inherits documentation from base class */ double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) return -1; if (mOuterRect.contains(pos.toPoint())) { if (details) details->setValue(spLegendBox); return mParentPlot->selectionTolerance()*0.99; } return -1; } /* inherits documentation from base class */ void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) mSelectedParts = selectedParts(); // in case item selection has changed if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPLegend::deselectEvent(bool *selectionStateChanged) { mSelectedParts = selectedParts(); // in case item selection has changed if (mSelectableParts.testFlag(spLegendBox)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(selectedParts() & ~spLegendBox); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ QCP::Interaction QCPLegend::selectionCategory() const { return QCP::iSelectLegend; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const { return QCP::iSelectLegend; } /* inherits documentation from base class */ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) { Q_UNUSED(parentPlot) } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPlotTitle //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlotTitle \brief A layout element displaying a plot title text The text may be specified with \ref setText, theformatting can be controlled with \ref setFont and \ref setTextColor. A plot title can be added as follows: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpplottitle-creation Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref QCustomPlot::titleDoubleClick signal. */ /* start documentation of signals */ /*! \fn void QCPPlotTitle::selectionChanged(bool selected) This signal is emitted when the selection state has changed to \a selected, either by user interaction or by a direct call to \ref setSelected. \see setSelected, setSelectable */ /* end documentation of signals */ /*! Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText). To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text). */ QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mFont(QFont(QLatin1String("sans serif"), 13*1.5, QFont::Bold)), mTextColor(Qt::black), mSelectedFont(QFont(QLatin1String("sans serif"), 13*1.6, QFont::Bold)), mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { if (parentPlot) { setLayer(parentPlot->currentLayer()); mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold); mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold); } setMargins(QMargins(5, 5, 5, 0)); } /*! \overload Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text. */ QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) : QCPLayoutElement(parentPlot), mText(text), mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)), mTextColor(Qt::black), mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)), mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { setLayer(QLatin1String("axes")); setMargins(QMargins(5, 5, 5, 0)); } /*! Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n". \see setFont, setTextColor */ void QCPPlotTitle::setText(const QString &text) { mText = text; } /*! Sets the \a font of the title text. \see setTextColor, setSelectedFont */ void QCPPlotTitle::setFont(const QFont &font) { mFont = font; } /*! Sets the \a color of the title text. \see setFont, setSelectedTextColor */ void QCPPlotTitle::setTextColor(const QColor &color) { mTextColor = color; } /*! Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected). \see setFont */ void QCPPlotTitle::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected). \see setTextColor */ void QCPPlotTitle::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; } /*! Sets whether the user may select this plot title to \a selectable. Note that even when \a selectable is set to false, the selection state may be changed programmatically via \ref setSelected. */ void QCPPlotTitle::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets the selection state of this plot title to \a selected. If the selection has changed, \ref selectionChanged is emitted. Note that this function can change the selection state independently of the current \ref setSelectable state. */ void QCPPlotTitle::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /* inherits documentation from base class */ void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); } /* inherits documentation from base class */ void QCPPlotTitle::draw(QCPPainter *painter) { painter->setFont(mainFont()); painter->setPen(QPen(mainTextColor())); painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); } /* inherits documentation from base class */ QSize QCPPlotTitle::minimumSizeHint() const { QFontMetrics metrics(mFont); QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); result.rwidth() += mMargins.left() + mMargins.right(); result.rheight() += mMargins.top() + mMargins.bottom(); return result; } /* inherits documentation from base class */ QSize QCPPlotTitle::maximumSizeHint() const { QFontMetrics metrics(mFont); QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); result.rheight() += mMargins.top() + mMargins.bottom(); result.setWidth(QWIDGETSIZE_MAX); return result; } /* inherits documentation from base class */ void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPPlotTitle::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (mTextBoundingRect.contains(pos.toPoint())) return mParentPlot->selectionTolerance()*0.99; else return -1; } /*! \internal Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to true, else mFont is returned. */ QFont QCPPlotTitle::mainFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to true, else mTextColor is returned. */ QColor QCPPlotTitle::mainTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorScale //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorScale \brief A color scale for use with color coding data such as QCPColorMap This layout element can be placed on the plot to correlate a color gradient with data values. It is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". \image html QCPColorScale.png The color scale can be either horizontal or vertical, as shown in the image above. The orientation and the side where the numbers appear is controlled with \ref setType. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are connected, they share their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color scale, to make them all synchronize these properties. To have finer control over the number display and axis behaviour, you can directly access the \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if you want to change the number of automatically generated ticks, call \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-autotickcount Placing a color scale next to the main axis rect works like with any other layout element: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation In this case we have placed it to the right of the default axis rect, so it wasn't necessary to call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color scale can be set with \ref setLabel. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup Color scales are initialized with a non-zero minimum top and bottom margin (\ref setMinimumMargins), because vertical color scales are most common and the minimum top/bottom margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you might want to also change the minimum margins accordingly, e.g. setMinimumMargins(QMargins(6, 0, 6, 0)). */ /* start documentation of inline functions */ /*! \fn QCPAxis *QCPColorScale::axis() const Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on the QCPColorScale or on its QCPAxis. If the type of the color scale is changed with \ref setType, the axis returned by this method will change, too, to either the left, right, bottom or top axis, depending on which type was set. */ /* end documentation of signals */ /* start documentation of signals */ /*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange); This signal is emitted when the data range changes. \see setDataRange */ /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the data scale type changes. \see setDataScaleType */ /*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient); This signal is emitted when the gradient changes. \see setGradient */ /* end documentation of signals */ /*! Constructs a new QCPColorScale. */ QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight mDataScaleType(QCPAxis::stLinear), mBarWidth(20), mAxisRect(new QCPColorScaleAxisRectPrivate(this)) { setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) setType(QCPAxis::atRight); setDataRange(QCPRange(0, 6)); } QCPColorScale::~QCPColorScale() { delete mAxisRect; } /* undocumented getter */ QString QCPColorScale::label() const { if (!mColorAxis) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return QString(); } return mColorAxis.data()->label(); } /* undocumented getter */ bool QCPColorScale::rangeDrag() const { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return false; } return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /* undocumented getter */ bool QCPColorScale::rangeZoom() const { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return false; } return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /*! Sets at which side of the color scale the axis is placed, and thus also its orientation. Note that after setting \a type to a different value, the axis returned by \ref axis() will be a different one. The new axis will adopt the following properties from the previous axis: The range, scale type, log base and label. */ void QCPColorScale::setType(QCPAxis::AxisType type) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (mType != type) { mType = type; QCPRange rangeTransfer(0, 6); double logBaseTransfer = 10; QString labelTransfer; // revert some settings on old axis: if (mColorAxis) { rangeTransfer = mColorAxis.data()->range(); labelTransfer = mColorAxis.data()->label(); logBaseTransfer = mColorAxis.data()->scaleLogBase(); mColorAxis.data()->setLabel(QString()); disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; foreach (QCPAxis::AxisType atype, allAxisTypes) { mAxisRect.data()->axis(atype)->setTicks(atype == mType); mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); } // set new mColorAxis pointer: mColorAxis = mAxisRect.data()->axis(mType); // transfer settings to new axis: mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa) mColorAxis.data()->setLabel(labelTransfer); mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0, QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0); } } /*! Sets the range spanned by the color gradient and that is shown by the axis in the color scale. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its range with \ref QCPAxis::setRange. \see setDataScaleType, setGradient, rescaleDataRange */ void QCPColorScale::setDataRange(const QCPRange &dataRange) { if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { mDataRange = dataRange; if (mColorAxis) mColorAxis.data()->setRange(mDataRange); emit dataRangeChanged(mDataRange); } } /*! Sets the scale type of the color scale, i.e. whether values are linearly associated with colors or logarithmically. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its scale type with \ref QCPAxis::setScaleType. \see setDataRange, setGradient */ void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) { if (mDataScaleType != scaleType) { mDataScaleType = scaleType; if (mColorAxis) mColorAxis.data()->setScaleType(mDataScaleType); if (mDataScaleType == QCPAxis::stLogarithmic) setDataRange(mDataRange.sanitizedForLogScale()); emit dataScaleTypeChanged(mDataScaleType); } } /*! Sets the color gradient that will be used to represent data values. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. \see setDataRange, setDataScaleType */ void QCPColorScale::setGradient(const QCPColorGradient &gradient) { if (mGradient != gradient) { mGradient = gradient; if (mAxisRect) mAxisRect.data()->mGradientImageInvalidated = true; emit gradientChanged(mGradient); } } /*! Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on the internal \ref axis. */ void QCPColorScale::setLabel(const QString &str) { if (!mColorAxis) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return; } mColorAxis.data()->setLabel(str); } /*! Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed will have. */ void QCPColorScale::setBarWidth(int width) { mBarWidth = width; } /*! Sets whether the user can drag the data range (\ref setDataRange). Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeDrag(bool enabled) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (enabled) mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); else mAxisRect.data()->setRangeDrag(0); } /*! Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeZoom(bool enabled) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (enabled) mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); else mAxisRect.data()->setRangeZoom(0); } /*! Returns a list of all the color maps associated with this color scale. */ QList QCPColorScale::colorMaps() const { QList result; for (int i=0; iplottableCount(); ++i) { if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) if (cm->colorScale() == this) result.append(cm); } return result; } /*! Changes the data range such that all color maps associated with this color scale are fully mapped to the gradient in the data dimension. \see setDataRange */ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) { QList maps = colorMaps(); QCPRange newRange; bool haveRange = false; int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace) if (mDataScaleType == QCPAxis::stLogarithmic) sign = (mDataRange.upper < 0 ? -1 : 1); for (int i=0; irealVisibility() && onlyVisibleMaps) continue; QCPRange mapRange; if (maps.at(i)->colorScale() == this) { bool currentFoundRange = true; mapRange = maps.at(i)->data()->dataBounds(); if (sign == 1) { if (mapRange.lower <= 0 && mapRange.upper > 0) mapRange.lower = mapRange.upper*1e-3; else if (mapRange.lower <= 0 && mapRange.upper <= 0) currentFoundRange = false; } else if (sign == -1) { if (mapRange.upper >= 0 && mapRange.lower < 0) mapRange.upper = mapRange.lower*1e-3; else if (mapRange.upper >= 0 && mapRange.lower >= 0) currentFoundRange = false; } if (currentFoundRange) { if (!haveRange) newRange = mapRange; else newRange.expand(mapRange); haveRange = true; } } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mDataScaleType == QCPAxis::stLinear) { newRange.lower = center-mDataRange.size()/2.0; newRange.upper = center+mDataRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); } } setDataRange(newRange); } } /* inherits documentation from base class */ void QCPColorScale::update(UpdatePhase phase) { QCPLayoutElement::update(phase); if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->update(phase); switch (phase) { case upMargins: { if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) { setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); } else { setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX); setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0); } break; } case upLayout: { mAxisRect.data()->setOuterRect(rect()); break; } default: break; } } /* inherits documentation from base class */ void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const { painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPColorScale::mousePressEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mousePressEvent(event); } /* inherits documentation from base class */ void QCPColorScale::mouseMoveEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mouseMoveEvent(event); } /* inherits documentation from base class */ void QCPColorScale::mouseReleaseEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mouseReleaseEvent(event); } /* inherits documentation from base class */ void QCPColorScale::wheelEvent(QWheelEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->wheelEvent(event); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorScaleAxisRectPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorScaleAxisRectPrivate \internal \brief An axis rect subclass for use in a QCPColorScale This is a private class and not part of the public QCustomPlot interface. It provides the axis rect functionality for the QCPColorScale class. */ /*! Creates a new instance, as a child of \a parentColorScale. */ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : QCPAxisRect(parentColorScale->parentPlot(), true), mParentColorScale(parentColorScale), mGradientImageInvalidated(true) { setParentLayerable(parentColorScale); setMinimumMargins(QMargins(0, 0, 0, 0)); QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { axis(type)->setVisible(true); axis(type)->grid()->setVisible(false); axis(type)->setPadding(0); connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); } connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); // make layer transfers of color scale transfer to axis rect and axes // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); foreach (QCPAxis::AxisType type, allAxisTypes) connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); } /*! \internal Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation. */ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) { if (mGradientImageInvalidated) updateGradientImage(); bool mirrorHorz = false; bool mirrorVert = false; if (mParentColorScale->mColorAxis) { mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); } painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); QCPAxisRect::draw(painter); } /*! \internal Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to generate a gradient image. This gradient image will be used in the \ref draw method. */ void QCPColorScaleAxisRectPrivate::updateGradientImage() { if (rect().isEmpty()) return; int n = mParentColorScale->mGradient.levelCount(); int w, h; QVector data(n); for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) { w = n; h = rect().height(); mGradientImage = QImage(w, h, QImage::Format_RGB32); QVector pixels; for (int y=0; y(mGradientImage.scanLine(y))); mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); for (int y=1; y(mGradientImage.scanLine(y)); const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); for (int x=0; x allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { if (QCPAxis *senderAxis = qobject_cast(sender())) if (senderAxis->axisType() == type) continue; if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { if (selectedParts.testFlag(QCPAxis::spAxis)) axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); else axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); } } } /*! \internal This slot is connected to the selectableChanged signals of the four axes in the constructor. It synchronizes the selectability of the axes. */ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) { // synchronize axis base selectability: QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; foreach (QCPAxis::AxisType type, allAxisTypes) { if (QCPAxis *senderAxis = qobject_cast(sender())) if (senderAxis->axisType() == type) continue; if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { if (selectableParts.testFlag(QCPAxis::spAxis)) axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); else axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPData \brief Holds the data of one single data point for QCPGraph. The container for storing multiple data points is \ref QCPDataMap. The stored data is: \li \a key: coordinate on the key axis of this data point \li \a value: coordinate on the value axis of this data point \li \a keyErrorMinus: negative error in the key dimension (for error bars) \li \a keyErrorPlus: positive error in the key dimension (for error bars) \li \a valueErrorMinus: negative error in the value dimension (for error bars) \li \a valueErrorPlus: positive error in the value dimension (for error bars) \see QCPDataMap */ /*! Constructs a data point with key, value and all errors set to zero. */ QCPData::QCPData() : key(0), value(0), keyErrorPlus(0), keyErrorMinus(0), valueErrorPlus(0), valueErrorMinus(0) { } /*! Constructs a data point with the specified \a key and \a value. All errors are set to zero. */ QCPData::QCPData(double key, double value) : key(key), value(value), keyErrorPlus(0), keyErrorMinus(0), valueErrorPlus(0), valueErrorMinus(0) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGraph //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGraph \brief A plottable representing a graph in a plot. \image html QCPGraph.png Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting instance is accessed via QCustomPlot::graph. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. Graphs are used to display single-valued data. Single-valued means that there should only be one data point per unique key coordinate. In other words, the graph can't have \a loops. If you do want to plot non-single-valued curves, rather use the QCPCurve plottable. Gaps in the graph line can be created by adding data points with NaN as value (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be separated. \section appearance Changing the appearance The appearance of the graph is mainly determined by the line style, scatter style, brush and pen of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen). \subsection filling Filling under or between graphs QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill between this graph and another one, call \ref setChannelFillGraph with the other graph as parameter. \see QCustomPlot::addGraph, QCustomPlot::graph */ /* start of documentation of inline functions */ /*! \fn QCPDataMap *QCPGraph::data() const Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods, in certain situations. */ /* end of documentation of inline functions */ /*! Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the graph. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function. */ QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis) { mData = new QCPDataMap; setPen(QPen(Qt::blue, 0)); setErrorPen(QPen(Qt::black)); setBrush(Qt::NoBrush); setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); setSelectedBrush(Qt::NoBrush); setLineStyle(lsLine); setErrorType(etNone); setErrorBarSize(6); setErrorBarSkipSymbol(true); setChannelFillGraph(0); setAdaptiveSampling(true); } QCPGraph::~QCPGraph() { delete mData; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the graph takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. */ void QCPGraph::setData(QCPDataMap *data, bool copy) { if (mData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); return; } if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setData(const QVector &key, const QVector &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPData newData; for (int i=0; iinsertMulti(newData.key, newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical value error of the data points are set to the values in \a valueError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueError.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative value error of the data points are set to the values in \a valueErrorMinus, the positive value error to \a valueErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueErrorMinus.size()); n = qMin(n, valueErrorPlus.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical key error of the data points are set to the values in \a keyError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, keyError.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative key error of the data points are set to the values in \a keyErrorMinus, the positive key error to \a keyErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, keyErrorMinus.size()); n = qMin(n, keyErrorPlus.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueError.size()); n = qMin(n, keyError.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueErrorMinus.size()); n = qMin(n, valueErrorPlus.size()); n = qMin(n, keyErrorMinus.size()); n = qMin(n, keyErrorPlus.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPGraph::setLineStyle(LineStyle ls) { mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } /*! Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data point. If you set \a errorType to something other than \ref etNone, make sure to actually pass error data via the specific setData functions along with the data points (e.g. \ref setDataValueError, \ref setDataKeyError, \ref setDataBothError). \see ErrorType */ void QCPGraph::setErrorType(ErrorType errorType) { mErrorType = errorType; } /*! Sets the pen with which the error bars will be drawn. \see setErrorBarSize, setErrorType */ void QCPGraph::setErrorPen(const QPen &pen) { mErrorPen = pen; } /*! Sets the width of the handles at both ends of an error bar in pixels. */ void QCPGraph::setErrorBarSize(double size) { mErrorBarSize = size; } /*! If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but leave some free space around the symbol. This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size of the area to leave blank. So when drawing Pixmaps as scatter points (\ref QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the size of the Pixmap, if the error bars should leave gaps to its boundaries. \ref setErrorType, setErrorBarSize, setScatterStyle */ void QCPGraph::setErrorBarSkipSymbol(bool enabled) { mErrorBarSkipSymbol = enabled; } /*! Sets the target graph for filling the area between this graph and \a targetGraph with the current brush (\ref setBrush). When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To disable any filling, set the brush to Qt::NoBrush. \see setBrush */ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) { // prevent setting channel target to this graph itself: if (targetGraph == this) { qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; mChannelFillGraph = 0; return; } // prevent setting channel target to a graph not in the plot: if (targetGraph && targetGraph->mParentPlot != mParentPlot) { qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; mChannelFillGraph = 0; return; } mChannelFillGraph = targetGraph; } /*! Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive sampling technique can drastically improve the replot performance for graphs with a larger number of points (e.g. above 10,000), without notably changing the appearance of the graph. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no disadvantage in almost all cases. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are reproduced reliably, as well as the overall shape of the data set. The replot time reduces dramatically though. This allows QCustomPlot to display large amounts of data in realtime. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" Care must be taken when using high-density scatter plots in combination with adaptive sampling. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still gives a significant reduction of replot times, but not quite as much as for line plots. This is because scatter plots inherently need more data points to be preserved in order to still resemble the original, non-adaptive-sampling plot. As shown above, the results still aren't quite identical, as banding occurs for the outer data points. This is in fact intentional, such that the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, depends on the point density, i.e. the number of points in the plot. For some situations with scatter plots it might thus be desirable to manually turn adaptive sampling off. For example, when saving the plot to disk. This can be achieved by setting \a enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled back to true afterwards. */ void QCPGraph::setAdaptiveSampling(bool enabled) { mAdaptiveSampling = enabled; } /*! Adds the provided data points in \a dataMap to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QCPDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QCPData &data) { mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point as \a key and \a value pair to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(double key, double value) { QCPData newData; newData.key = key; newData.value = value; mData->insertMulti(newData.key, newData); } /*! \overload Adds the provided data points as \a key and \a value pairs to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QVector &keys, const QVector &values) { int n = qMin(keys.size(), values.size()); QCPData newData; for (int i=0; iinsertMulti(newData.key, newData); } } /*! Removes all data points with keys smaller than \a key. \see addData, clearData */ void QCPGraph::removeDataBefore(double key) { QCPDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < key) it = mData->erase(it); } /*! Removes all data points with keys greater than \a key. \see addData, clearData */ void QCPGraph::removeDataAfter(double key) { if (mData->isEmpty()) return; QCPDataMap::iterator it = mData->upperBound(key); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove a single data point with known key, use \ref removeData(double key). \see addData, clearData */ void QCPGraph::removeData(double fromKey, double toKey) { if (fromKey >= toKey || mData->isEmpty()) return; QCPDataMap::iterator it = mData->upperBound(fromKey); QCPDataMap::iterator itEnd = mData->upperBound(toKey); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at \a key. If the position is not known with absolute precision, consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around the suspected position, depeding on the precision with which the key is known. \see addData, clearData */ void QCPGraph::removeData(double key) { mData->remove(key); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPGraph::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && !mSelectable) || mData->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) return pointDistance(pos); else return -1; } /*! \overload Allows to define whether error bars are taken into consideration when determining the new axis range. \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const { rescaleKeyAxis(onlyEnlarge, includeErrorBars); rescaleValueAxis(onlyEnlarge, includeErrorBars); } /*! \overload Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration when determining the new axis range. \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis */ void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const { // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change // that getKeyRange is passed the includeErrorBars value. if (mData->isEmpty()) return; QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } SignDomain signDomain = sdBoth; if (keyAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars); if (foundRange) { if (onlyEnlarge) { if (keyAxis->range().lower < newRange.lower) newRange.lower = keyAxis->range().lower; if (keyAxis->range().upper > newRange.upper) newRange.upper = keyAxis->range().upper; } keyAxis->setRange(newRange); } } /*! \overload Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration when determining the new axis range. \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis */ void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const { // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change // is that getValueRange is passed the includeErrorBars value. if (mData->isEmpty()) return; QCPAxis *valueAxis = mValueAxis.data(); if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } SignDomain signDomain = sdBoth; if (valueAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars); if (foundRange) { if (onlyEnlarge) { if (valueAxis->range().lower < newRange.lower) newRange.lower = valueAxis->range().lower; if (valueAxis->range().upper > newRange.upper) newRange.upper = valueAxis->range().upper; } valueAxis->setRange(newRange); } } /* inherits documentation from base class */ void QCPGraph::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return; if (mLineStyle == lsNone && mScatterStyle.isNone()) return; // allocate line and (if necessary) point vectors: QVector *lineData = new QVector; QVector *scatterData = 0; if (!mScatterStyle.isNone()) scatterData = new QVector; // fill vectors with data appropriate to plot style: getPlotData(lineData, scatterData); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPDataMap::const_iterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { if (QCP::isInvalidData(it.value().key, it.value().value) || QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) || QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); } #endif // draw fill of graph: drawFill(painter, lineData); // draw line: if (mLineStyle == lsImpulse) drawImpulsePlot(painter, lineData); else if (mLineStyle != lsNone) drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot // draw scatters: if (scatterData) drawScatterPlot(painter, scatterData); // free allocated line and point vectors: delete lineData; if (scatterData) delete scatterData; } /* inherits documentation from base class */ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw fill: if (mBrush.style() != Qt::NoBrush) { applyFillAntialiasingHint(painter); painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } /*! \internal This function branches out to the line style specific "get(...)PlotData" functions, according to the line style of the graph. \a lineData will be filled with raw points that will be drawn with the according draw functions, e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data points, since for step plots for example, additional points are needed for drawing lines that make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left untouched. \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped. \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData, getStepCenterPlotData, getImpulsePlotData */ void QCPGraph::getPlotData(QVector *lineData, QVector *scatterData) const { switch(mLineStyle) { case lsNone: getScatterPlotData(scatterData); break; case lsLine: getLinePlotData(lineData, scatterData); break; case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break; case lsStepRight: getStepRightPlotData(lineData, scatterData); break; case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break; case lsImpulse: getImpulsePlotData(lineData, scatterData); break; } } /*! \internal If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone, this function serves at providing the visible data points in \a scatterData, so the \ref drawScatterPlot function can draw the scatter points accordingly. If line style is not \ref lsNone, this function is not called and the data for the scatter points are (if needed) calculated inside the corresponding other "get(...)PlotData" functions. \see drawScatterPlot */ void QCPGraph::getScatterPlotData(QVector *scatterData) const { getPreparedData(0, scatterData); } /*! \internal Places the raw data points needed for a normal linearly connected graph in \a linePixelData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getLinePlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()); // transform lineData points to pixels: if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; icoordToPixel(lineData.at(i).value)); (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); } } else // key axis is horizontal { for (int i=0; icoordToPixel(lineData.at(i).key)); (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); } } } /*! \internal Places the raw data points needed for a step plot with left oriented steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; for (int i=0; icoordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(lastValue); (*linePixelData)[i*2+0].setY(key); lastValue = valueAxis->coordToPixel(lineData.at(i).value); (*linePixelData)[i*2+1].setX(lastValue); (*linePixelData)[i*2+1].setY(key); } } else // key axis is horizontal { double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; for (int i=0; icoordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(lastValue); lastValue = valueAxis->coordToPixel(lineData.at(i).value); (*linePixelData)[i*2+1].setX(key); (*linePixelData)[i*2+1].setY(lastValue); } } } /*! \internal Places the raw data points needed for a step plot with right oriented steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastKey = keyAxis->coordToPixel(lineData.first().key); double value; for (int i=0; icoordToPixel(lineData.at(i).value); (*linePixelData)[i*2+0].setX(value); (*linePixelData)[i*2+0].setY(lastKey); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+1].setX(value); (*linePixelData)[i*2+1].setY(lastKey); } } else // key axis is horizontal { double lastKey = keyAxis->coordToPixel(lineData.first().key); double value; for (int i=0; icoordToPixel(lineData.at(i).value); (*linePixelData)[i*2+0].setX(lastKey); (*linePixelData)[i*2+0].setY(value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+1].setX(lastKey); (*linePixelData)[i*2+1].setY(value); } } } /*! \internal Places the raw data points needed for a step plot with centered steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastKey = keyAxis->coordToPixel(lineData.first().key); double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; (*linePixelData)[0].setX(lastValue); (*linePixelData)[0].setY(lastKey); for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; (*linePixelData)[i*2-1].setX(lastValue); (*linePixelData)[i*2-1].setY(key); lastValue = valueAxis->coordToPixel(lineData.at(i).value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(lastValue); (*linePixelData)[i*2+0].setY(key); } (*linePixelData)[lineData.size()*2-1].setX(lastValue); (*linePixelData)[lineData.size()*2-1].setY(lastKey); } else // key axis is horizontal { double lastKey = keyAxis->coordToPixel(lineData.first().key); double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; (*linePixelData)[0].setX(lastKey); (*linePixelData)[0].setY(lastValue); for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; (*linePixelData)[i*2-1].setX(key); (*linePixelData)[i*2-1].setY(lastValue); lastValue = valueAxis->coordToPixel(lineData.at(i).value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(lastValue); } (*linePixelData)[lineData.size()*2-1].setX(lastKey); (*linePixelData)[lineData.size()*2-1].setY(lastValue); } } /*! \internal Places the raw data points needed for an impulse plot in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawImpulsePlot */ void QCPGraph::getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill // transform lineData points to pixels: if (keyAxis->orientation() == Qt::Vertical) { double zeroPointX = valueAxis->coordToPixel(0); double key; for (int i=0; icoordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(zeroPointX); (*linePixelData)[i*2+0].setY(key); (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value)); (*linePixelData)[i*2+1].setY(key); } } else // key axis is horizontal { double zeroPointY = valueAxis->coordToPixel(0); double key; for (int i=0; icoordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(zeroPointY); (*linePixelData)[i*2+1].setX(key); (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value)); } } } /*! \internal Draws the fill of the graph with the specified brush. If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by \ref removeFillBasePoints after the fill drawing is done). If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the more complex polygon is calculated with the \ref getChannelFillPolygon function. \see drawLinePlot */ void QCPGraph::drawFill(QCPPainter *painter, QVector *lineData) const { if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return; applyFillAntialiasingHint(painter); if (!mChannelFillGraph) { // draw base fill under graph, fill goes all the way to the zero-value-line: addFillBasePoints(lineData); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(QPolygonF(*lineData)); removeFillBasePoints(lineData); } else { // draw channel fill between this graph and mChannelFillGraph: painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(getChannelFillPolygon(lineData)); } } /*! \internal Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent of the line style and are always drawn if the scatter style's shape is not \ref QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData" functions, together with the (line style dependent) line data. \see drawLinePlot, drawImpulsePlot */ void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // draw error bars: if (mErrorType != etNone) { applyErrorBarsAntialiasingHint(painter); painter->setPen(mErrorPen); if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; isize(); ++i) drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i)); } else { for (int i=0; isize(); ++i) drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i)); } } // draw scatter point symbols: applyScattersAntialiasingHint(painter); mScatterStyle.applyTo(painter, mPen); if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; isize(); ++i) if (!qIsNaN(scatterData->at(i).value)) mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key)); } else { for (int i=0; isize(); ++i) if (!qIsNaN(scatterData->at(i).value)) mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value)); } } /*! \internal Draws line graphs from the provided data. It connects all points in \a lineData, which was created by one of the "get(...)PlotData" functions for line styles that require simple line connections between the point vector they create. These are for example \ref getLinePlotData, \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData. \see drawScatterPlot, drawImpulsePlot */ void QCPGraph::drawLinePlot(QCPPainter *painter, QVector *lineData) const { // draw line of graph: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); /* Draws polyline in batches, currently not used: int p = 0; while (p < lineData->size()) { int batch = qMin(25, lineData->size()-p); if (p != 0) { ++batch; --p; // to draw the connection lines between two batches } painter->drawPolyline(lineData->constData()+p, batch); p += batch; } */ // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && painter->pen().style() == Qt::SolidLine && !painter->modes().testFlag(QCPPainter::pmVectorized) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { int i = 0; bool lastIsNan = false; const int lineDataSize = lineData->size(); while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN ++i; ++i; // because drawing works in 1 point retrospect while (i < lineDataSize) { if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line { if (!lastIsNan) painter->drawLine(lineData->at(i-1), lineData->at(i)); else lastIsNan = false; } else lastIsNan = true; ++i; } } else { int segmentStart = 0; int i = 0; const int lineDataSize = lineData->size(); while (i < lineDataSize) { if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line { painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point segmentStart = i+1; } ++i; } // draw last segment: painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); } } } /*! \internal Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was created by \ref getImpulsePlotData. \see drawScatterPlot, drawLinePlot */ void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector *lineData) const { // draw impulses: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); QPen pen = mainPen(); pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line painter->setPen(pen); painter->setBrush(Qt::NoBrush); painter->drawLines(*lineData); } } /*! \internal Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point densities. 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a scatterData should be 0 to prevent unnecessary calculations. This method is used by the various "get(...)PlotData" methods to get the basic working set of data. */ void QCPGraph::getPreparedData(QVector *lineData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // get visible data range: QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point getVisibleDataBounds(lower, upper); if (lower == mData->constEnd() || upper == mData->constEnd()) return; // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling: int maxCount = std::numeric_limits::max(); if (mAdaptiveSampling) { int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key())); maxCount = 2*keyPixelSpan+2; } int dataCount = countDataInBounds(lower, upper, maxCount); if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average { if (lineData) { QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; double minValue = it.value().value; double maxValue = it.value().value; QCPDataMap::const_iterator currentIntervalFirstPoint = it; int reversedFactor = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction int reversedRound = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); double lastIntervalEndKey = currentIntervalStartKey; double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) int intervalDataCount = 1; ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect while (it != upperEnd) { if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary { if (it.value().value < minValue) minValue = it.value().value; else if (it.value().value > maxValue) maxValue = it.value().value; ++intervalDataCount; } else // new pixel interval started { if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster { if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); if (it.key() > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value)); } else lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); lastIntervalEndKey = (it-1).value().key; minValue = it.value().value; maxValue = it.value().value; currentIntervalFirstPoint = it; currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); if (keyEpsilonVariable) keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); intervalDataCount = 1; } ++it; } // handle last interval: if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster { if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); } else lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); } if (scatterData) { double valueMaxRange = valueAxis->range().upper; double valueMinRange = valueAxis->range().lower; QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; double minValue = it.value().value; double maxValue = it.value().value; QCPDataMap::const_iterator minValueIt = it; QCPDataMap::const_iterator maxValueIt = it; QCPDataMap::const_iterator currentIntervalStart = it; int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) int intervalDataCount = 1; ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect while (it != upperEnd) { if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary { if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) { minValue = it.value().value; minValueIt = it; } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) { maxValue = it.value().value; maxValueIt = it; } ++intervalDataCount; } else // new pixel started { if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them { // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average QCPDataMap::const_iterator intervalIt = currentIntervalStart; int c = 0; while (intervalIt != it) { if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) scatterData->append(intervalIt.value()); ++c; ++intervalIt; } } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) scatterData->append(currentIntervalStart.value()); minValue = it.value().value; maxValue = it.value().value; currentIntervalStart = it; currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); if (keyEpsilonVariable) keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); intervalDataCount = 1; } ++it; } // handle last interval: if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them { // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average QCPDataMap::const_iterator intervalIt = currentIntervalStart; int c = 0; while (intervalIt != it) { if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) scatterData->append(intervalIt.value()); ++c; ++intervalIt; } } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) scatterData->append(currentIntervalStart.value()); } } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters { QVector *dataVector = 0; if (lineData) dataVector = lineData; else if (scatterData) dataVector = scatterData; if (dataVector) { QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; dataVector->reserve(dataCount+2); // +2 for possible fill end points while (it != upperEnd) { dataVector->append(it.value()); ++it; } } if (lineData && scatterData) *scatterData = *dataVector; } } /*! \internal called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data point. \a x and \a y pixel positions of the data point are passed since they are already known in pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a data is therefore only used for the errors, not key and value. */ void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const { if (qIsNaN(data.value)) return; QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } double a, b; // positions of error bar bounds in pixels double barWidthHalf = mErrorBarSize*0.5; double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true if (keyAxis->orientation() == Qt::Vertical) { // draw key error vertically and value error horizontally if (mErrorType == etKey || mErrorType == etBoth) { a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); if (keyAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); if (y-b > skipSymbolMargin) painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); } else painter->drawLine(QLineF(x, a, x, b)); // draw handles: painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); } if (mErrorType == etValue || mErrorType == etBoth) { a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); if (valueAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); if (b-x > skipSymbolMargin) painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); } else painter->drawLine(QLineF(a, y, b, y)); // draw handles: painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); } } else // mKeyAxis->orientation() is Qt::Horizontal { // draw value error vertically and key error horizontally if (mErrorType == etKey || mErrorType == etBoth) { a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); if (keyAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); if (b-x > skipSymbolMargin) painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); } else painter->drawLine(QLineF(a, y, b, y)); // draw handles: painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); } if (mErrorType == etValue || mErrorType == etBoth) { a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); if (valueAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); if (y-b > skipSymbolMargin) painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); } else painter->drawLine(QLineF(x, a, x, b)); // draw handles: painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); } } } /*! \internal called by \ref getPreparedData to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. \a lower returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie just outside of the visible range. if the graph contains no data, both \a lower and \a upper point to constEnd. */ void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } if (mData->isEmpty()) { lower = mData->constEnd(); upper = mData->constEnd(); return; } // get visible data range as QMap iterators QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn } /*! \internal Counts the number of data points between \a lower and \a upper (including them), up to a maximum of \a maxCount. This function is used by \ref getPreparedData to determine whether adaptive sampling shall be used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points only needs to be done until \a maxCount is reached, which should be set to the number of data points at which adaptive sampling sets in. */ int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const { if (upper == mData->constEnd() && lower == mData->constEnd()) return 0; QCPDataMap::const_iterator it = lower; int count = 1; while (it != upper && count < maxCount) { ++it; ++count; } return count; } /*! \internal The line data vector generated by e.g. getLinePlotData contains only the line that connects the data points. If the graph needs to be filled, two additional points need to be added at the value-zero-line in the lower and upper key positions of the graph. This function calculates these points and adds them to the end of \a lineData. Since the fill is typically drawn before the line stroke, these added points need to be removed again after the fill is done, with the removeFillBasePoints function. The expanding of \a lineData by two points will not cause unnecessary memory reallocations, because the data vector generation functions (getLinePlotData etc.) reserve two extra points when they allocate memory for \a lineData. \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ void QCPGraph::addFillBasePoints(QVector *lineData) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } // append points that close the polygon fill at the key axis: if (mKeyAxis.data()->orientation() == Qt::Vertical) { *lineData << upperFillBasePoint(lineData->last().y()); *lineData << lowerFillBasePoint(lineData->first().y()); } else { *lineData << upperFillBasePoint(lineData->last().x()); *lineData << lowerFillBasePoint(lineData->first().x()); } } /*! \internal removes the two points from \a lineData that were added by \ref addFillBasePoints. \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ void QCPGraph::removeFillBasePoints(QVector *lineData) const { lineData->remove(lineData->size()-2, 2); } /*! \internal called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill polygon on the axis which lies in the direction towards the zero value. \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned point, respectively. \see upperFillBasePoint, addFillBasePoints */ QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } QPointF point; if (valueAxis->scaleType() == QCPAxis::stLinear) { if (keyAxis->axisType() == QCPAxis::atLeft) { point.setX(valueAxis->coordToPixel(0)); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atRight) { point.setX(valueAxis->coordToPixel(0)); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atTop) { point.setX(lowerKey); point.setY(valueAxis->coordToPixel(0)); } else if (keyAxis->axisType() == QCPAxis::atBottom) { point.setX(lowerKey); point.setY(valueAxis->coordToPixel(0)); } } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { // In logarithmic scaling we can't just draw to value zero so we just fill all the way // to the axis which is in the direction towards zero if (keyAxis->orientation() == Qt::Vertical) { if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setX(keyAxis->axisRect()->right()); else point.setX(keyAxis->axisRect()->left()); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { point.setX(lowerKey); if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setY(keyAxis->axisRect()->top()); else point.setY(keyAxis->axisRect()->bottom()); } } return point; } /*! \internal called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill polygon on the axis which lies in the direction towards the zero value. \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned point, respectively. \see lowerFillBasePoint, addFillBasePoints */ QPointF QCPGraph::upperFillBasePoint(double upperKey) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } QPointF point; if (valueAxis->scaleType() == QCPAxis::stLinear) { if (keyAxis->axisType() == QCPAxis::atLeft) { point.setX(valueAxis->coordToPixel(0)); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atRight) { point.setX(valueAxis->coordToPixel(0)); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atTop) { point.setX(upperKey); point.setY(valueAxis->coordToPixel(0)); } else if (keyAxis->axisType() == QCPAxis::atBottom) { point.setX(upperKey); point.setY(valueAxis->coordToPixel(0)); } } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { // In logarithmic scaling we can't just draw to value 0 so we just fill all the way // to the axis which is in the direction towards 0 if (keyAxis->orientation() == Qt::Vertical) { if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setX(keyAxis->axisRect()->right()); else point.setX(keyAxis->axisRect()->left()); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { point.setX(upperKey); if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setY(keyAxis->axisRect()->top()); else point.setY(keyAxis->axisRect()->bottom()); } } return point; } /*! \internal Generates the polygon needed for drawing channel fills between this graph (data passed via \a lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref getPlotData function). May return an empty polygon if the key ranges have no overlap or fill target graph and this graph don't have same orientation (i.e. both key axes horizontal or both key axes vertical). For increased performance (due to implicit sharing), keep the returned QPolygonF const. */ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lineData) const { if (!mChannelFillGraph) return QPolygonF(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation()) return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis) if (lineData->isEmpty()) return QPolygonF(); QVector otherData; mChannelFillGraph.data()->getPlotData(&otherData, 0); if (otherData.isEmpty()) return QPolygonF(); QVector thisData; thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function for (int i=0; isize(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve() thisData << lineData->at(i); // pointers to be able to swap them, depending which data range needs cropping: QVector *staticData = &thisData; QVector *croppedData = &otherData; // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): if (keyAxis->orientation() == Qt::Horizontal) { // x is key // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: if (staticData->first().x() > staticData->last().x()) { int size = staticData->size(); for (int i=0; ifirst().x() > croppedData->last().x()) { int size = croppedData->size(); for (int i=0; ifirst().x() < croppedData->first().x()) // other one must be cropped qSwap(staticData, croppedData); int lowBound = findIndexBelowX(croppedData, staticData->first().x()); if (lowBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(0, lowBound); // set lowest point of cropped data to fit exactly key position of first static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation double slope; if (croppedData->at(1).x()-croppedData->at(0).x() != 0) slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); else slope = 0; (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); (*croppedData)[0].setX(staticData->first().x()); // crop upper bound: if (staticData->last().x() > croppedData->last().x()) // other one must be cropped qSwap(staticData, croppedData); int highBound = findIndexAboveX(croppedData, staticData->last().x()); if (highBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); // set highest point of cropped data to fit exactly key position of last static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation int li = croppedData->size()-1; // last index if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0) slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); else slope = 0; (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); (*croppedData)[li].setX(staticData->last().x()); } else // mKeyAxis->orientation() == Qt::Vertical { // y is key // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x, // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate. // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: if (staticData->first().y() < staticData->last().y()) { int size = staticData->size(); for (int i=0; ifirst().y() < croppedData->last().y()) { int size = croppedData->size(); for (int i=0; ifirst().y() > croppedData->first().y()) // other one must be cropped qSwap(staticData, croppedData); int lowBound = findIndexAboveY(croppedData, staticData->first().y()); if (lowBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(0, lowBound); // set lowest point of cropped data to fit exactly key position of first static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation double slope; if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); else slope = 0; (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); (*croppedData)[0].setY(staticData->first().y()); // crop upper bound: if (staticData->last().y() < croppedData->last().y()) // other one must be cropped qSwap(staticData, croppedData); int highBound = findIndexBelowY(croppedData, staticData->last().y()); if (highBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); // set highest point of cropped data to fit exactly key position of last static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation int li = croppedData->size()-1; // last index if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); else slope = 0; (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); (*croppedData)[li].setY(staticData->last().y()); } // return joined: for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted thisData << otherData.at(i); return QPolygonF(thisData); } /*! \internal Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in \a data points are ordered ascending, as is the case when plotting with horizontal key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveX(const QVector *data, double x) const { for (int i=data->size()-1; i>=0; --i) { if (data->at(i).x() < x) { if (isize()-1) return i+1; else return data->size()-1; } } return -1; } /*! \internal Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in \a data points are ordered ascending, as is the case when plotting with horizontal key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowX(const QVector *data, double x) const { for (int i=0; isize(); ++i) { if (data->at(i).x() > x) { if (i>0) return i-1; else return 0; } } return -1; } /*! \internal Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in \a data points are ordered descending, as is the case when plotting with vertical key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveY(const QVector *data, double y) const { for (int i=0; isize(); ++i) { if (data->at(i).y() < y) { if (i>0) return i-1; else return 0; } } return -1; } /*! \internal Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in \ref selectTest. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0. */ double QCPGraph::pointDistance(const QPointF &pixelPoint) const { if (mData->isEmpty()) return -1.0; if (mLineStyle == lsNone && mScatterStyle.isNone()) return -1.0; // calculate minimum distances to graph representation: if (mLineStyle == lsNone) { // no line displayed, only calculate distance to scatter points: QVector scatterData; getScatterPlotData(&scatterData); if (scatterData.size() > 0) { double minDistSqr = std::numeric_limits::max(); for (int i=0; i lineData; getPlotData(&lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here if (lineData.size() > 1) // at least one line segment, compare distance to line segments { double minDistSqr = std::numeric_limits::max(); if (mLineStyle == lsImpulse) { // impulse plot differs from other line styles in that the lineData points are only pairwise connected: for (int i=0; i 0) // only single data point, calculate distance to that point { return QVector2D(lineData.at(0)-pixelPoint).length(); } else // no data available in view to calculate distance to return -1.0; } } /*! \internal Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in \a data points are ordered descending, as is the case when plotting with vertical key axis (since keys are ordered ascending). Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowY(const QVector *data, double y) const { for (int i=data->size()-1; i>=0; --i) { if (data->at(i).y() > y) { if (isize()-1) return i+1; else return data->size()-1; } } return -1; } /* inherits documentation from base class */ QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { // just call the specialized version which takes an additional argument whether error bars // should also be taken into consideration for range calculation. We set this to true here. return getKeyRange(foundRange, inSignDomain, true); } /* inherits documentation from base class */ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const { // just call the specialized version which takes an additional argument whether error bars // should also be taken into consideration for range calculation. We set this to true here. return getValueRange(foundRange, inSignDomain, true); } /*! \overload Allows to specify whether the error bars should be included in the range calculation. \see getKeyRange(bool &foundRange, SignDomain inSignDomain) */ QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current, currentErrorMinus, currentErrorPlus; if (inSignDomain == sdBoth) // range may be anywhere { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { if (!qIsNaN(it.value().value)) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if (current-currentErrorMinus < range.lower || !haveLower) { range.lower = current-currentErrorMinus; haveLower = true; } if (current+currentErrorPlus > range.upper || !haveUpper) { range.upper = current+currentErrorPlus; haveUpper = true; } } ++it; } } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { if (!qIsNaN(it.value().value)) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. { if ((current < range.lower || !haveLower) && current < 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current < 0) { range.upper = current; haveUpper = true; } } } ++it; } } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { if (!qIsNaN(it.value().value)) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. { if ((current < range.lower || !haveLower) && current > 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current > 0) { range.upper = current; haveUpper = true; } } } ++it; } } foundRange = haveLower && haveUpper; return range; } /*! \overload Allows to specify whether the error bars should be included in the range calculation. \see getValueRange(bool &foundRange, SignDomain inSignDomain) */ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current, currentErrorMinus, currentErrorPlus; if (inSignDomain == sdBoth) // range may be anywhere { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (!qIsNaN(current)) { currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if (current-currentErrorMinus < range.lower || !haveLower) { range.lower = current-currentErrorMinus; haveLower = true; } if (current+currentErrorPlus > range.upper || !haveUpper) { range.upper = current+currentErrorPlus; haveUpper = true; } } ++it; } } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (!qIsNaN(current)) { currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. { if ((current < range.lower || !haveLower) && current < 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current < 0) { range.upper = current; haveUpper = true; } } } ++it; } } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (!qIsNaN(current)) { currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. { if ((current < range.lower || !haveLower) && current > 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current > 0) { range.upper = current; haveUpper = true; } } } ++it; } } foundRange = haveLower && haveUpper; return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurveData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPCurveData \brief Holds the data of one single data point for QCPCurve. The container for storing multiple data points is \ref QCPCurveDataMap. The stored data is: \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector (x(t), y(t))) \li \a key: coordinate on the key axis of this curve point \li \a value: coordinate on the value axis of this curve point \see QCPCurveDataMap */ /*! Constructs a curve data point with t, key and value set to zero. */ QCPCurveData::QCPCurveData() : t(0), key(0), value(0) { } /*! Constructs a curve data point with the specified \a t, \a key and \a value. */ QCPCurveData::QCPCurveData(double t, double key, double value) : t(t), key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurve //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPCurve \brief A plottable representing a parametric curve in a plot. \image html QCPCurve.png Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, so their visual representation can have \a loops. This is realized by introducing a third coordinate \a t, which defines the order of the points described by the other two coordinates \a x and \a y. To plot data, assign it with the \ref setData or \ref addData functions. Gaps in the curve can be created by adding data points with NaN as key and value (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be separated. \section appearance Changing the appearance The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). \section usage Usage Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance and add it to the customPlot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1 and then modify the properties of the newly created plottable, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2 */ /*! Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the graph. */ QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis) { mData = new QCPCurveDataMap; mPen.setColor(Qt::blue); mPen.setStyle(Qt::SolidLine); mBrush.setColor(Qt::blue); mBrush.setStyle(Qt::NoBrush); mSelectedPen = mPen; mSelectedPen.setWidthF(2.5); mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen mSelectedBrush = mBrush; setScatterStyle(QCPScatterStyle()); setLineStyle(lsLine); } QCPCurve::~QCPCurve() { delete mData; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ void QCPCurve::setData(QCPCurveDataMap *data, bool copy) { if (mData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); return; } if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a t, \a key and \a value tuples. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPCurve::setData(const QVector &t, const QVector &key, const QVector &value) { mData->clear(); int n = t.size(); n = qMin(n, key.size()); n = qMin(n, value.size()); QCPCurveData newData; for (int i=0; iinsertMulti(newData.t, newData); } } /*! \overload Replaces the current data with the provided \a key and \a value pairs. The t parameter of each data point will be set to the integer index of the respective key/value pair. */ void QCPCurve::setData(const QVector &key, const QVector &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPCurveData newData; for (int i=0; iinsertMulti(newData.t, newData); } } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } /*! Sets how the single data points are connected in the plot or how they are represented visually apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) { mLineStyle = style; } /*! Adds the provided data points in \a dataMap to the current data. \see removeData */ void QCPCurve::addData(const QCPCurveDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. \see removeData */ void QCPCurve::addData(const QCPCurveData &data) { mData->insertMulti(data.t, data); } /*! \overload Adds the provided single data point as \a t, \a key and \a value tuple to the current data \see removeData */ void QCPCurve::addData(double t, double key, double value) { QCPCurveData newData; newData.t = t; newData.key = key; newData.value = value; mData->insertMulti(newData.t, newData); } /*! \overload Adds the provided single data point as \a key and \a value pair to the current data The t parameter of the data point is set to the t of the last data point plus 1. If there is no last data point, t will be set to 0. \see removeData */ void QCPCurve::addData(double key, double value) { QCPCurveData newData; if (!mData->isEmpty()) newData.t = (mData->constEnd()-1).key()+1; else newData.t = 0; newData.key = key; newData.value = value; mData->insertMulti(newData.t, newData); } /*! \overload Adds the provided data points as \a t, \a key and \a value tuples to the current data. \see removeData */ void QCPCurve::addData(const QVector &ts, const QVector &keys, const QVector &values) { int n = ts.size(); n = qMin(n, keys.size()); n = qMin(n, values.size()); QCPCurveData newData; for (int i=0; iinsertMulti(newData.t, newData); } } /*! Removes all data points with curve parameter t smaller than \a t. \see addData, clearData */ void QCPCurve::removeDataBefore(double t) { QCPCurveDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < t) it = mData->erase(it); } /*! Removes all data points with curve parameter t greater than \a t. \see addData, clearData */ void QCPCurve::removeDataAfter(double t) { if (mData->isEmpty()) return; QCPCurveDataMap::iterator it = mData->upperBound(t); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is greater or equal to \a tot, the function does nothing. To remove a single data point with known t, use \ref removeData(double t). \see addData, clearData */ void QCPCurve::removeData(double fromt, double tot) { if (fromt >= tot || mData->isEmpty()) return; QCPCurveDataMap::iterator it = mData->upperBound(fromt); QCPCurveDataMap::iterator itEnd = mData->upperBound(tot); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at curve parameter \a t. If the position is not known with absolute precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness interval around the suspected position, depeding on the precision with which the curve parameter is known. \see addData, clearData */ void QCPCurve::removeData(double t) { mData->remove(t); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPCurve::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && !mSelectable) || mData->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) return pointDistance(pos); else return -1; } /* inherits documentation from base class */ void QCPCurve::draw(QCPPainter *painter) { if (mData->isEmpty()) return; // allocate line vector: QVector *lineData = new QVector; // fill with curve data: getCurveData(lineData); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPCurveDataMap::const_iterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { if (QCP::isInvalidData(it.value().t) || QCP::isInvalidData(it.value().key, it.value().value)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); } #endif // draw curve fill: if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) { applyFillAntialiasingHint(painter); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(QPolygonF(*lineData)); } // draw curve line: if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && painter->pen().style() == Qt::SolidLine && !painter->modes().testFlag(QCPPainter::pmVectorized) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { int i = 0; bool lastIsNan = false; const int lineDataSize = lineData->size(); while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN ++i; ++i; // because drawing works in 1 point retrospect while (i < lineDataSize) { if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line { if (!lastIsNan) painter->drawLine(lineData->at(i-1), lineData->at(i)); else lastIsNan = false; } else lastIsNan = true; ++i; } } else { int segmentStart = 0; int i = 0; const int lineDataSize = lineData->size(); while (i < lineDataSize) { if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line { painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point segmentStart = i+1; } ++i; } // draw last segment: painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); } } // draw scatters: if (!mScatterStyle.isNone()) drawScatterPlot(painter, lineData); // free allocated line data: delete lineData; } /* inherits documentation from base class */ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw fill: if (mBrush.style() != Qt::NoBrush) { applyFillAntialiasingHint(painter); painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } /*! \internal Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone. */ void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector *pointData) const { // draw scatter point symbols: applyScattersAntialiasingHint(painter); mScatterStyle.applyTo(painter, mPen); for (int i=0; isize(); ++i) if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y())) mScatterStyle.drawShape(painter, pointData->at(i)); } /*! \internal called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the line of the curve. Line segments that aren't visible in the current axis rect are handled in an optimized way. They are projected onto a rectangle slightly larger than the visible axis rect and simplified regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside the visible axis rect by generating new temporary points on the outer rect if necessary. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints. */ void QCPCurve::getCurveData(QVector *lineData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // add margins to rect to compensate for stroke width double strokeMargin = qMax(qreal(1.0), qreal(mainPen().widthF()*0.75)); // stroke radius + 50% safety if (!mScatterStyle.isNone()) strokeMargin = qMax(strokeMargin, mScatterStyle.size()); double rectLeft = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1)); double rectRight = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1)); double rectBottom = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)+strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1)); double rectTop = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)-strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1)); int currentRegion; QCPCurveDataMap::const_iterator it = mData->constBegin(); QCPCurveDataMap::const_iterator prevIt = mData->constEnd()-1; int prevRegion = getRegion(prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom); QVector trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right) while (it != mData->constEnd()) { currentRegion = getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R { if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal { QPointF crossA, crossB; if (prevRegion == 5) // we're coming from R, so add this point optimized { lineData->append(getOptimizedPoint(currentRegion, it.value().key, it.value().value, prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom)); // in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); } else if (mayTraverse(prevRegion, currentRegion) && getTraverse(prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom, crossA, crossB)) { // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point: QVector beforeTraverseCornerPoints, afterTraverseCornerPoints; getTraverseCornerPoints(prevRegion, currentRegion, rectLeft, rectTop, rectRight, rectBottom, beforeTraverseCornerPoints, afterTraverseCornerPoints); if (it != mData->constBegin()) { *lineData << beforeTraverseCornerPoints; lineData->append(crossA); lineData->append(crossB); *lineData << afterTraverseCornerPoints; } else { lineData->append(crossB); *lineData << afterTraverseCornerPoints; trailingPoints << beforeTraverseCornerPoints << crossA ; } } else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s) { *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); } } else // segment does end in R, so we add previous point optimized and this point at original position { if (it == mData->constBegin()) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end trailingPoints << getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); else lineData->append(getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom)); lineData->append(coordsToPixels(it.value().key, it.value().value)); } } else // region didn't change { if (currentRegion == 5) // still in R, keep adding original points { lineData->append(coordsToPixels(it.value().key, it.value().value)); } else // still outside R, no need to add anything { // see how this is not doing anything? That's the main optimization... } } prevIt = it; prevRegion = currentRegion; ++it; } *lineData << trailingPoints; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. It returns the region of the given point (\a x, \a y) with respect to a rectangle defined by \a rectLeft, \a rectTop, \a rectRight, and \a rectBottom. The regions are enumerated from top to bottom and left to right:
147
258
369
With the rectangle being region 5, and the outer regions extending infinitely outwards. In the curve optimization algorithm, region 5 is considered to be the visible portion of the plot. */ int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const { if (x < rectLeft) // region 123 { if (y > rectTop) return 1; else if (y < rectBottom) return 3; else return 2; } else if (x > rectRight) // region 789 { if (y > rectTop) return 7; else if (y < rectBottom) return 9; else return 8; } else // region 456 { if (y > rectTop) return 4; else if (y < rectBottom) return 6; else return 5; } } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. This method is used in case the current segment passes from inside the visible rect (region 5, see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by the line connecting (\a key, \a value) with (\a otherKey, \a otherValue). It returns the intersection point of the segment with the border of region 5. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or leaving it. It is important though that \a otherRegion correctly identifies the other region not equal to 5. */ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const { double intersectKey = rectLeft; // initial value is just fail-safe double intersectValue = rectTop; // initial value is just fail-safe switch (otherRegion) { case 1: // top and left edge { intersectValue = rectTop; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: { intersectKey = rectLeft; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 2: // left edge { intersectKey = rectLeft; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); break; } case 3: // bottom and left edge { intersectValue = rectBottom; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: { intersectKey = rectLeft; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 4: // top edge { intersectValue = rectTop; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); break; } case 5: { break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table } case 6: // bottom edge { intersectValue = rectBottom; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); break; } case 7: // top and right edge { intersectValue = rectTop; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: { intersectKey = rectRight; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 8: // right edge { intersectKey = rectRight; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); break; } case 9: // bottom and right edge { intersectValue = rectBottom; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: { intersectKey = rectRight; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } } return coordsToPixels(intersectKey, intersectValue); } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. In situations where a single segment skips over multiple regions it might become necessary to add extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts. This method provides these points that must be added, assuming the original segment doesn't start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by \ref getTraverseCornerPoints.) For example, consider a segment which directly goes from region 4 to 2 but originally is far out to the top left such that it doesn't cross region 5. Naively optimizing these points by projecting them on the top and left borders of region 5 will create a segment that surely crosses 5, creating a visual artifact in the plot. This method prevents this by providing extra points at the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without traversing 5. */ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const { QVector result; switch (prevRegion) { case 1: { switch (currentRegion) { case 2: { result << coordsToPixels(rectLeft, rectTop); break; } case 4: { result << coordsToPixels(rectLeft, rectTop); break; } case 3: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); break; } case 7: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); break; } case 6: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } case 8: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } else { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } break; } } break; } case 2: { switch (currentRegion) { case 1: { result << coordsToPixels(rectLeft, rectTop); break; } case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } case 4: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } case 6: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } case 7: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } case 9: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } } break; } case 3: { switch (currentRegion) { case 2: { result << coordsToPixels(rectLeft, rectBottom); break; } case 6: { result << coordsToPixels(rectLeft, rectBottom); break; } case 1: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); break; } case 9: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); break; } case 4: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } case 8: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } else { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } break; } } break; } case 4: { switch (currentRegion) { case 1: { result << coordsToPixels(rectLeft, rectTop); break; } case 7: { result << coordsToPixels(rectRight, rectTop); break; } case 2: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } case 8: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } case 3: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } case 9: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } } break; } case 5: { switch (currentRegion) { case 1: { result << coordsToPixels(rectLeft, rectTop); break; } case 7: { result << coordsToPixels(rectRight, rectTop); break; } case 9: { result << coordsToPixels(rectRight, rectBottom); break; } case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } } break; } case 6: { switch (currentRegion) { case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } case 9: { result << coordsToPixels(rectRight, rectBottom); break; } case 2: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } case 8: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } case 1: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } case 7: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } } break; } case 7: { switch (currentRegion) { case 4: { result << coordsToPixels(rectRight, rectTop); break; } case 8: { result << coordsToPixels(rectRight, rectTop); break; } case 1: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); break; } case 9: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); break; } case 2: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } case 6: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } else { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } break; } } break; } case 8: { switch (currentRegion) { case 7: { result << coordsToPixels(rectRight, rectTop); break; } case 9: { result << coordsToPixels(rectRight, rectBottom); break; } case 4: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } case 6: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } case 1: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } case 3: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } } break; } case 9: { switch (currentRegion) { case 6: { result << coordsToPixels(rectRight, rectBottom); break; } case 8: { result << coordsToPixels(rectRight, rectBottom); break; } case 3: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); break; } case 7: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); break; } case 2: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } case 4: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } else { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } break; } } break; } } return result; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion nor \a currentRegion is 5 itself. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref getTraverse). */ bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const { switch (prevRegion) { case 1: { switch (currentRegion) { case 4: case 7: case 2: case 3: return false; default: return true; } } case 2: { switch (currentRegion) { case 1: case 3: return false; default: return true; } } case 3: { switch (currentRegion) { case 1: case 2: case 6: case 9: return false; default: return true; } } case 4: { switch (currentRegion) { case 1: case 7: return false; default: return true; } } case 5: return false; // should never occur case 6: { switch (currentRegion) { case 3: case 9: return false; default: return true; } } case 7: { switch (currentRegion) { case 1: case 4: case 8: case 9: return false; default: return true; } } case 8: { switch (currentRegion) { case 7: case 9: return false; default: return true; } } case 9: { switch (currentRegion) { case 3: case 6: case 8: case 7: return false; default: return true; } } default: return true; } } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible region 5. The return value of this method indicates whether the segment actually traverses region 5 or not. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and exit points of region 5. They will become the optimized points for that segment. */ bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const { QList intersections; // x of QPointF corresponds to key and y to value if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis { // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here intersections.append(QPointF(key, rectBottom)); // direction will be taken care of at end of method intersections.append(QPointF(key, rectTop)); } else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis { // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here intersections.append(QPointF(rectLeft, value)); // direction will be taken care of at end of method intersections.append(QPointF(rectRight, value)); } else // line is skewed { double gamma; double keyPerValue = (key-prevKey)/(value-prevValue); // check top of rect: gamma = prevKey + (rectTop-prevValue)*keyPerValue; if (gamma >= rectLeft && gamma <= rectRight) intersections.append(QPointF(gamma, rectTop)); // check bottom of rect: gamma = prevKey + (rectBottom-prevValue)*keyPerValue; if (gamma >= rectLeft && gamma <= rectRight) intersections.append(QPointF(gamma, rectBottom)); double valuePerKey = 1.0/keyPerValue; // check left of rect: gamma = prevValue + (rectLeft-prevKey)*valuePerKey; if (gamma >= rectBottom && gamma <= rectTop) intersections.append(QPointF(rectLeft, gamma)); // check right of rect: gamma = prevValue + (rectRight-prevKey)*valuePerKey; if (gamma >= rectBottom && gamma <= rectTop) intersections.append(QPointF(rectRight, gamma)); } // handle cases where found points isn't exactly 2: if (intersections.size() > 2) { // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: double distSqrMax = 0; QPointF pv1, pv2; for (int i=0; i distSqrMax) { pv1 = intersections.at(i); pv2 = intersections.at(k); distSqrMax = distSqr; } } } intersections = QList() << pv1 << pv2; } else if (intersections.size() != 2) { // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment return false; } // possibly re-sort points so optimized point segment has same direction as original segment: if ((key-prevKey)*(intersections.at(1).x()-intersections.at(0).x()) + (value-prevValue)*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction intersections.move(0, 1); crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y()); crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y()); return true; } /*! \internal This function is part of the curve optimization algorithm of \ref getCurveData. This method assumes that the \ref getTraverse test has returned true, so the segment definitely traverses the visible region 5 when going from \a prevRegion to \a currentRegion. In certain situations it is not sufficient to merely generate the entry and exit points of the segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in addition to traversing region 5, skips another region outside of region 5, which makes it necessary to add an optimized corner point there (very similar to the job \ref getOptimizedCornerPoints does for segments that are completely in outside regions and don't traverse 5). As an example, consider a segment going from region 1 to region 6, traversing the lower left corner of region 5. In this configuration, the segment additionally crosses the border between region 1 and 2 before entering region 5. This makes it necessary to add an additional point in the top left corner, before adding the optimized traverse points. So in this case, the output parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be empty. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse return the respective corner points. */ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector &beforeTraverse, QVector &afterTraverse) const { switch (prevRegion) { case 1: { switch (currentRegion) { case 6: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } case 9: { beforeTraverse << coordsToPixels(rectLeft, rectTop); afterTraverse << coordsToPixels(rectRight, rectBottom); break; } case 8: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } } break; } case 2: { switch (currentRegion) { case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } } break; } case 3: { switch (currentRegion) { case 4: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } case 7: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); afterTraverse << coordsToPixels(rectRight, rectTop); break; } case 8: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } } break; } case 4: { switch (currentRegion) { case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } } break; } case 5: { break; } // shouldn't happen because this method only handles full traverses case 6: { switch (currentRegion) { case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } } break; } case 7: { switch (currentRegion) { case 2: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } case 3: { beforeTraverse << coordsToPixels(rectRight, rectTop); afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } case 6: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } } break; } case 8: { switch (currentRegion) { case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } } break; } case 9: { switch (currentRegion) { case 2: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } case 1: { beforeTraverse << coordsToPixels(rectRight, rectBottom); afterTraverse << coordsToPixels(rectLeft, rectTop); break; } case 4: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } } break; } } } /*! \internal Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in \ref selectTest. */ double QCPCurve::pointDistance(const QPointF &pixelPoint) const { if (mData->isEmpty()) { qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data"; return 500; } if (mData->size() == 1) { QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); return QVector2D(dataPoint-pixelPoint).length(); } // calculate minimum distance to line segments: QVector *lineData = new QVector; getCurveData(lineData); double minDistSqr = std::numeric_limits::max(); for (int i=0; isize()-1; ++i) { double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } delete lineData; return qSqrt(minDistSqr); } /* inherits documentation from base class */ QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPCurveDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; if (!qIsNaN(current) && !qIsNaN(it.value().value)) { if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } } ++it; } foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPCurveDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (!qIsNaN(current) && !qIsNaN(it.value().key)) { if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } } ++it; } foundRange = haveLower && haveUpper; return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBarsGroup //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBarsGroup \brief Groups multiple QCPBars together so they appear side by side \image html QCPBarsGroup.png When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable to have them appearing next to each other at each key. This is what adding the respective QCPBars plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each other, see \ref QCPBars::moveAbove.) \section qcpbarsgroup-usage Usage To add a QCPBars plottable to the group, create a new group and then add the respective bars intances: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation Alternatively to appending to the group like shown above, you can also set the group on the QCPBars plottable via \ref QCPBars::setBarsGroup. The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The bars in this group appear in the plot in the order they were appended. To insert a bars plottable at a certain index position, or to reposition a bars plottable which is already in the group, use \ref insert. To remove specific bars from the group, use either \ref remove or call \ref QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable. To clear the entire group, call \ref clear, or simply delete the group. \section qcpbarsgroup-example Example The image above is generated with the following code: \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example */ /* start of documentation of inline functions */ /*! \fn QList QCPBarsGroup::bars() const Returns all bars currently in this group. \see bars(int index) */ /*! \fn int QCPBarsGroup::size() const Returns the number of QCPBars plottables that are part of this group. */ /*! \fn bool QCPBarsGroup::isEmpty() const Returns whether this bars group is empty. \see size */ /*! \fn bool QCPBarsGroup::contains(QCPBars *bars) Returns whether the specified \a bars plottable is part of this group. */ /* end of documentation of inline functions */ /*! Constructs a new bars group for the specified QCustomPlot instance. */ QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) : QObject(parentPlot), mParentPlot(parentPlot), mSpacingType(stAbsolute), mSpacing(4) { } QCPBarsGroup::~QCPBarsGroup() { clear(); } /*! Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType. The actual spacing can then be specified with \ref setSpacing. \see setSpacing */ void QCPBarsGroup::setSpacingType(SpacingType spacingType) { mSpacingType = spacingType; } /*! Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is defined by the current \ref SpacingType, which can be set with \ref setSpacingType. \see setSpacingType */ void QCPBarsGroup::setSpacing(double spacing) { mSpacing = spacing; } /*! Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars exists, returns 0. \see bars(), size */ QCPBars *QCPBarsGroup::bars(int index) const { if (index >= 0 && index < mBars.size()) { return mBars.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! Removes all QCPBars plottables from this group. \see isEmpty */ void QCPBarsGroup::clear() { foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay bars->setBarsGroup(0); // removes itself via removeBars } /*! Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref QCPBars::setBarsGroup on the \a bars instance. \see insert, remove */ void QCPBarsGroup::append(QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } if (!mBars.contains(bars)) bars->setBarsGroup(this); else qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); } /*! Inserts the specified \a bars plottable into this group at the specified index position \a i. This gives you full control over the ordering of the bars. \a bars may already be part of this group. In that case, \a bars is just moved to the new index position. \see append, remove */ void QCPBarsGroup::insert(int i, QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } // first append to bars list normally: if (!mBars.contains(bars)) bars->setBarsGroup(this); // then move to according position: mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1)); } /*! Removes the specified \a bars plottable from this group. \see contains, clear */ void QCPBarsGroup::remove(QCPBars *bars) { if (!bars) { qDebug() << Q_FUNC_INFO << "bars is 0"; return; } if (mBars.contains(bars)) bars->setBarsGroup(0); else qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); } /*! \internal Adds the specified \a bars to the internal mBars list of bars. This method does not change the barsGroup property on \a bars. \see unregisterBars */ void QCPBarsGroup::registerBars(QCPBars *bars) { if (!mBars.contains(bars)) mBars.append(bars); } /*! \internal Removes the specified \a bars from the internal mBars list of bars. This method does not change the barsGroup property on \a bars. \see registerBars */ void QCPBarsGroup::unregisterBars(QCPBars *bars) { mBars.removeOne(bars); } /*! \internal Returns the pixel offset in the key dimension the specified \a bars plottable should have at the given key coordinate \a keyCoord. The offset is relative to the pixel position of the key coordinate \a keyCoord. */ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) { // find list of all base bars in case some mBars are stacked: QList baseBars; foreach (const QCPBars *b, mBars) { while (b->barBelow()) b = b->barBelow(); if (!baseBars.contains(b)) baseBars.append(b); } // find base bar this "bars" is stacked on: const QCPBars *thisBase = bars; while (thisBase->barBelow()) thisBase = thisBase->barBelow(); // determine key pixel offset of this base bars considering all other base bars in this barsgroup: double result = 0; int index = baseBars.indexOf(thisBase); if (index >= 0) { int startIndex; double lowerPixelWidth, upperPixelWidth; if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose) { return result; } else if (index < (baseBars.size()-1)/2.0) // bar is to the left of center { if (baseBars.size() % 2 == 0) // even number of bars { startIndex = baseBars.size()/2-1; result -= getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing } else // uneven number of bars { startIndex = (baseBars.size()-1)/2-1; baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar result -= getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing } for (int i=startIndex; i>index; --i) // add widths and spacings of bars in between center and our bars { baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result -= qAbs(upperPixelWidth-lowerPixelWidth); result -= getPixelSpacing(baseBars.at(i), keyCoord); } // finally half of our bars width: baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; } else // bar is to the right of center { if (baseBars.size() % 2 == 0) // even number of bars { startIndex = baseBars.size()/2; result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing } else // uneven number of bars { startIndex = (baseBars.size()-1)/2+1; baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing } for (int i=startIndex; igetPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth); result += getPixelSpacing(baseBars.at(i), keyCoord); } // finally half of our bars width: baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; } } return result; } /*! \internal Returns the spacing in pixels which is between this \a bars and the following one, both at the key coordinate \a keyCoord. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only needed to get acces to the key axis transformation and axis rect for the modes \ref stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in \ref stPlotCoords on a logarithmic axis. */ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) { switch (mSpacingType) { case stAbsolute: { return mSpacing; } case stAxisRectRatio: { if (bars->keyAxis()->orientation() == Qt::Horizontal) return bars->keyAxis()->axisRect()->width()*mSpacing; else return bars->keyAxis()->axisRect()->height()*mSpacing; } case stPlotCoords: { double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); return bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel; } } return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBarData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBarData \brief Holds the data of one single data point (one bar) for QCPBars. The container for storing multiple data points is \ref QCPBarDataMap. The stored data is: \li \a key: coordinate on the key axis of this bar \li \a value: height coordinate on the value axis of this bar \see QCPBarDataaMap */ /*! Constructs a bar data point with key and value set to zero. */ QCPBarData::QCPBarData() : key(0), value(0) { } /*! Constructs a bar data point with the specified \a key and \a value. */ QCPBarData::QCPBarData(double key, double value) : key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBars //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBars \brief A plottable representing a bar chart in a plot. \image html QCPBars.png To plot data, assign it with the \ref setData or \ref addData functions. \section appearance Changing the appearance The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear stacked. If you would like to group multiple QCPBars plottables together so they appear side by side as shown below, use QCPBarsGroup. \image html QCPBarsGroup.png \section usage Usage Like all data representing objects in QCustomPlot, the QCPBars is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1 add it to the customPlot with QCustomPlot::addPlottable: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2 and then modify the properties of the newly created plottable, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-3 */ /* start of documentation of inline functions */ /*! \fn QCPBars *QCPBars::barBelow() const Returns the bars plottable that is directly below this bars plottable. If there is no such plottable, returns 0. \see barAbove, moveBelow, moveAbove */ /*! \fn QCPBars *QCPBars::barAbove() const Returns the bars plottable that is directly above this bars plottable. If there is no such plottable, returns 0. \see barBelow, moveBelow, moveAbove */ /* end of documentation of inline functions */ /*! Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the bar chart. */ QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mData(new QCPBarDataMap), mWidth(0.75), mWidthType(wtPlotCoords), mBarsGroup(0), mBaseValue(0) { // modify inherited properties from abstract plottable: mPen.setColor(Qt::blue); mPen.setStyle(Qt::SolidLine); mBrush.setColor(QColor(40, 50, 255, 30)); mBrush.setStyle(Qt::SolidPattern); mSelectedPen = mPen; mSelectedPen.setWidthF(2.5); mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen mSelectedBrush = mBrush; } QCPBars::~QCPBars() { setBarsGroup(0); if (mBarBelow || mBarAbove) connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking delete mData; } /*! Sets the width of the bars. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...), depends on the currently set width type, see \ref setWidthType and \ref WidthType. */ void QCPBars::setWidth(double width) { mWidth = width; } /*! Sets how the width of the bars is defined. See the documentation of \ref WidthType for an explanation of the possible values for \a widthType. The default value is \ref wtPlotCoords. \see setWidth */ void QCPBars::setWidthType(QCPBars::WidthType widthType) { mWidthType = widthType; } /*! Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref QCPBarsGroup::append. To remove this QCPBars from any group, set \a barsGroup to 0. */ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) { // deregister at old group: if (mBarsGroup) mBarsGroup->unregisterBars(this); mBarsGroup = barsGroup; // register at new group: if (mBarsGroup) mBarsGroup->registerBars(this); } /*! Sets the base value of this bars plottable. The base value defines where on the value coordinate the bars start. How far the bars extend from the base value is given by their individual value data. For example, if the base value is set to 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at 3. For stacked bars, only the base value of the bottom-most QCPBars has meaning. The default base value is 0. */ void QCPBars::setBaseValue(double baseValue) { mBaseValue = baseValue; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ void QCPBars::setData(QCPBarDataMap *data, bool copy) { if (mData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); return; } if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a key and \a value tuples. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPBars::setData(const QVector &key, const QVector &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPBarData newData; for (int i=0; iinsertMulti(newData.key, newData); } } /*! Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear below the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already has a bars object below itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. To remove this bars plottable from any stacking, set \a bars to 0. \see moveBelow, barAbove, barBelow */ void QCPBars::moveBelow(QCPBars *bars) { if (bars == this) return; if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; return; } // remove from stacking: connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 // if new bar given, insert this bar below it: if (bars) { if (bars->mBarBelow) connectBars(bars->mBarBelow.data(), this); connectBars(this, bars); } } /*! Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear above the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already has a bars object below itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. To remove this bars plottable from any stacking, set \a bars to 0. \see moveBelow, barBelow, barAbove */ void QCPBars::moveAbove(QCPBars *bars) { if (bars == this) return; if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; return; } // remove from stacking: connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 // if new bar given, insert this bar above it: if (bars) { if (bars->mBarAbove) connectBars(this, bars->mBarAbove.data()); connectBars(bars, this); } } /*! Adds the provided data points in \a dataMap to the current data. \see removeData */ void QCPBars::addData(const QCPBarDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. \see removeData */ void QCPBars::addData(const QCPBarData &data) { mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point as \a key and \a value tuple to the current data \see removeData */ void QCPBars::addData(double key, double value) { QCPBarData newData; newData.key = key; newData.value = value; mData->insertMulti(newData.key, newData); } /*! \overload Adds the provided data points as \a key and \a value tuples to the current data. \see removeData */ void QCPBars::addData(const QVector &keys, const QVector &values) { int n = keys.size(); n = qMin(n, values.size()); QCPBarData newData; for (int i=0; iinsertMulti(newData.key, newData); } } /*! Removes all data points with key smaller than \a key. \see addData, clearData */ void QCPBars::removeDataBefore(double key) { QCPBarDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < key) it = mData->erase(it); } /*! Removes all data points with key greater than \a key. \see addData, clearData */ void QCPBars::removeDataAfter(double key) { if (mData->isEmpty()) return; QCPBarDataMap::iterator it = mData->upperBound(key); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove a single data point with known key, use \ref removeData(double key). \see addData, clearData */ void QCPBars::removeData(double fromKey, double toKey) { if (fromKey >= toKey || mData->isEmpty()) return; QCPBarDataMap::iterator it = mData->upperBound(fromKey); QCPBarDataMap::iterator itEnd = mData->upperBound(toKey); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at \a key. If the position is not known with absolute precision, consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around the suspected position, depeding on the precision with which the key is known. \see addData, clearData */ void QCPBars::removeData(double key) { mData->remove(key); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPBars::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { QCPBarDataMap::ConstIterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos)) return mParentPlot->selectionTolerance()*0.99; } } return -1; } /* inherits documentation from base class */ void QCPBars::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mData->isEmpty()) return; QCPBarDataMap::const_iterator it, lower, upperEnd; getVisibleDataBounds(lower, upperEnd); for (it = lower; it != upperEnd; ++it) { // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA if (QCP::isInvalidData(it.value().key, it.value().value)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name(); #endif QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value); // draw bar fill: if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) { applyFillAntialiasingHint(painter); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(barPolygon); } // draw bar line: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); painter->drawPolyline(barPolygon); } } } /* inherits documentation from base class */ void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw filled rect: applyDefaultAntialiasingHint(painter); painter->setBrush(mBrush); painter->setPen(mPen); QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); r.moveCenter(rect.center()); painter->drawRect(r); } /*! \internal called by \ref draw to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. It also takes into account the bar width. \a lower returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a upperEnd returns an iterator one higher than the highest visible data point. Same as before, \a upperEnd may also lie just outside of the visible range. if the bars plottable contains no data, both \a lower and \a upperEnd point to constEnd. */ void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } if (mData->isEmpty()) { lower = mData->constEnd(); upperEnd = mData->constEnd(); return; } // get visible data range as QMap iterators lower = mData->lowerBound(mKeyAxis.data()->range().lower); upperEnd = mData->upperBound(mKeyAxis.data()->range().upper); double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower); double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper); bool isVisible = false; // walk left from lbound to find lower bar that actually is completely outside visible pixel range: QCPBarDataMap::const_iterator it = lower; while (it != mData->constBegin()) { --it; QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect(); if (mKeyAxis.data()->orientation() == Qt::Horizontal) isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound)); else // keyaxis is vertical isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound)); if (isVisible) lower = it; else break; } // walk right from ubound to find upper bar that actually is completely outside visible pixel range: it = upperEnd; while (it != mData->constEnd()) { QRectF barBounds = getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect(); if (mKeyAxis.data()->orientation() == Qt::Horizontal) isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound)); else // keyaxis is vertical isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound)); if (isVisible) upperEnd = it+1; else break; ++it; } } /*! \internal Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom and shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref setBaseValue). */ QPolygonF QCPBars::getBarPolygon(double key, double value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } QPolygonF result; double lowerPixelWidth, upperPixelWidth; getPixelWidth(key, lowerPixelWidth, upperPixelWidth); double base = getStackedBaseValue(key, value >= 0); double basePixel = valueAxis->coordToPixel(base); double valuePixel = valueAxis->coordToPixel(base+value); double keyPixel = keyAxis->coordToPixel(key); if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, key); if (keyAxis->orientation() == Qt::Horizontal) { result << QPointF(keyPixel+lowerPixelWidth, basePixel); result << QPointF(keyPixel+lowerPixelWidth, valuePixel); result << QPointF(keyPixel+upperPixelWidth, valuePixel); result << QPointF(keyPixel+upperPixelWidth, basePixel); } else { result << QPointF(basePixel, keyPixel+lowerPixelWidth); result << QPointF(valuePixel, keyPixel+lowerPixelWidth); result << QPointF(valuePixel, keyPixel+upperPixelWidth); result << QPointF(basePixel, keyPixel+upperPixelWidth); } return result; } /*! \internal This function is used to determine the width of the bar at coordinate \a key, according to the specified width (\ref setWidth) and width type (\ref setWidthType). The output parameters \a lower and \a upper return the number of pixels the bar extends to lower and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a lower is negative and \a upper positive). */ void QCPBars::getPixelWidth(double key, double &lower, double &upper) const { switch (mWidthType) { case wtAbsolute: { upper = mWidth*0.5; lower = -upper; if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) qSwap(lower, upper); break; } case wtAxisRectRatio: { if (mKeyAxis && mKeyAxis.data()->axisRect()) { if (mKeyAxis.data()->orientation() == Qt::Horizontal) upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5; else upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5; lower = -upper; if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) qSwap(lower, upper); } else qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; break; } case wtPlotCoords: { if (mKeyAxis) { double keyPixel = mKeyAxis.data()->coordToPixel(key); upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel; // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by // coordinate transform which includes range direction } else qDebug() << Q_FUNC_INFO << "No key axis defined"; break; } } } /*! \internal This function is called to find at which value to start drawing the base of a bar at \a key, when it is stacked on top of another QCPBars (e.g. with \ref moveAbove). positive and negative bars are separated per stack (positive are stacked above baseValue upwards, negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the bar for which we need the base value is negative, set \a positive to false. */ double QCPBars::getStackedBaseValue(double key, bool positive) const { if (mBarBelow) { double max = 0; // don't use mBaseValue here because only base value of bottom-most bar has meaning in a bar stack // find bars of mBarBelow that are approximately at key and find largest one: double epsilon = qAbs(key)*1e-6; // should be safe even when changed to use float at some point if (key == 0) epsilon = 1e-6; QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-epsilon); QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+epsilon); while (it != itEnd) { if ((positive && it.value().value > max) || (!positive && it.value().value < max)) max = it.value().value; ++it; } // recurse down the bar-stack to find the total height: return max + mBarBelow.data()->getStackedBaseValue(key, positive); } else return mBaseValue; } /*! \internal Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) currently above lower and below upper will become disconnected to lower/upper. If lower is zero, upper will be disconnected at the bottom. If upper is zero, lower will be disconnected at the top. */ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) { if (!lower && !upper) return; if (!lower) // disconnect upper at bottom { // disconnect old bar below upper: if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) upper->mBarBelow.data()->mBarAbove = 0; upper->mBarBelow = 0; } else if (!upper) // disconnect lower at top { // disconnect old bar above lower: if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) lower->mBarAbove.data()->mBarBelow = 0; lower->mBarAbove = 0; } else // connect lower and upper { // disconnect old bar above lower: if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) lower->mBarAbove.data()->mBarBelow = 0; // disconnect old bar below upper: if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) upper->mBarBelow.data()->mBarAbove = 0; lower->mBarAbove = upper; upper->mBarBelow = lower; } } /* inherits documentation from base class */ QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPBarDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } // determine exact range of bars by including bar width and barsgroup offset: if (haveLower && mKeyAxis) { double lowerPixelWidth, upperPixelWidth, keyPixel; getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth); keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth; if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, range.lower); range.lower = mKeyAxis.data()->pixelToCoord(keyPixel); } if (haveUpper && mKeyAxis) { double lowerPixelWidth, upperPixelWidth, keyPixel; getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth); keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth; if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, range.upper); range.upper = mKeyAxis.data()->pixelToCoord(keyPixel); } foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; range.lower = mBaseValue; range.upper = mBaseValue; bool haveLower = true; // set to true, because baseValue should always be visible in bar charts bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts double current; QCPBarDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value + getStackedBaseValue(it.value().key, it.value().value >= 0); if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } foundRange = true; // return true because bar charts always have the 0-line visible return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPStatisticalBox //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPStatisticalBox \brief A plottable representing a single statistical box in a plot. \image html QCPStatisticalBox.png To plot data, assign it with the individual parameter functions or use \ref setData to set all parameters at once. The individual functions are: \li \ref setMinimum \li \ref setLowerQuartile \li \ref setMedian \li \ref setUpperQuartile \li \ref setMaximum Additionally you can define a list of outliers, drawn as scatter datapoints: \li \ref setOutliers \section appearance Changing the appearance The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change the width of the box with \ref setWidth in plot coordinates (not pixels). Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top (maximum) and bottom (minimum). The median indicator line has its own pen, \ref setMedianPen. If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the backbone line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat. The Outlier data points are drawn as normal scatter points. Their look can be controlled with \ref setOutlierStyle \section usage Usage Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable. Usually, you first create an instance and add it to the customPlot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1 and then modify the properties of the newly created plottable, e.g.: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2 */ /*! Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed statistical box can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the statistical box. */ QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mKey(0), mMinimum(0), mLowerQuartile(0), mMedian(0), mUpperQuartile(0), mMaximum(0) { setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)); setWhiskerWidth(0.2); setWidth(0.5); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2.5)); setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap)); setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap)); setWhiskerBarPen(QPen(Qt::black)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } /*! Sets the key coordinate of the statistical box. */ void QCPStatisticalBox::setKey(double key) { mKey = key; } /*! Sets the parameter "minimum" of the statistical box plot. This is the position of the lower whisker, typically the minimum measurement of the sample that's not considered an outlier. \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth */ void QCPStatisticalBox::setMinimum(double value) { mMinimum = value; } /*! Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the box. The lower and the upper quartiles are the two statistical quartiles around the median of the sample, they contain 50% of the sample data. \see setUpperQuartile, setPen, setBrush, setWidth */ void QCPStatisticalBox::setLowerQuartile(double value) { mLowerQuartile = value; } /*! Sets the parameter "median" of the statistical box plot. This is the value of the median mark inside the quartile box. The median separates the sample data in half (50% of the sample data is below/above the median). \see setMedianPen */ void QCPStatisticalBox::setMedian(double value) { mMedian = value; } /*! Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the box. The lower and the upper quartiles are the two statistical quartiles around the median of the sample, they contain 50% of the sample data. \see setLowerQuartile, setPen, setBrush, setWidth */ void QCPStatisticalBox::setUpperQuartile(double value) { mUpperQuartile = value; } /*! Sets the parameter "maximum" of the statistical box plot. This is the position of the upper whisker, typically the maximum measurement of the sample that's not considered an outlier. \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth */ void QCPStatisticalBox::setMaximum(double value) { mMaximum = value; } /*! Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers and displayed as such. \see setOutlierStyle */ void QCPStatisticalBox::setOutliers(const QVector &values) { mOutliers = values; } /*! Sets all parameters of the statistical box plot at once. \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum */ void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) { setKey(key); setMinimum(minimum); setLowerQuartile(lowerQuartile); setMedian(median); setUpperQuartile(upperQuartile); setMaximum(maximum); } /*! Sets the width of the box in key coordinates. \see setWhiskerWidth */ void QCPStatisticalBox::setWidth(double width) { mWidth = width; } /*! Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. \see setWidth */ void QCPStatisticalBox::setWhiskerWidth(double width) { mWhiskerWidth = width; } /*! Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching a few pixels past the whisker bars, when using a non-zero pen width. \see setWhiskerBarPen */ void QCPStatisticalBox::setWhiskerPen(const QPen &pen) { mWhiskerPen = pen; } /*! Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at each end of the whisker backbone). \see setWhiskerPen */ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) { mWhiskerBarPen = pen; } /*! Sets the pen used for drawing the median indicator line inside the statistical box. */ void QCPStatisticalBox::setMedianPen(const QPen &pen) { mMedianPen = pen; } /*! Sets the appearance of the outlier data points. \see setOutliers */ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) { mOutlierStyle = style; } /* inherits documentation from base class */ void QCPStatisticalBox::clearData() { setOutliers(QVector()); setKey(0); setMinimum(0); setLowerQuartile(0); setMedian(0); setUpperQuartile(0); setMaximum(0); } /* inherits documentation from base class */ double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { double posKey, posValue; pixelsToCoords(pos, posKey, posValue); // quartile box: QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5); QCPRange valueRange(mLowerQuartile, mUpperQuartile); if (keyRange.contains(posKey) && valueRange.contains(posValue)) return mParentPlot->selectionTolerance()*0.99; // min/max whiskers: if (QCPRange(mMinimum, mMaximum).contains(posValue)) return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey)); } return -1; } /* inherits documentation from base class */ void QCPStatisticalBox::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA if (QCP::isInvalidData(mKey, mMedian) || QCP::isInvalidData(mLowerQuartile, mUpperQuartile) || QCP::isInvalidData(mMinimum, mMaximum)) qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name(); for (int i=0; isave(); painter->setClipRect(quartileBox, Qt::IntersectClip); drawMedian(painter); painter->restore(); drawWhiskers(painter); drawOutliers(painter); } /* inherits documentation from base class */ void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw filled rect: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->setBrush(mBrush); QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); r.moveCenter(rect.center()); painter->drawRect(r); } /*! \internal Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so the median doesn't draw outside the quartile box). */ void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const { QRectF box; box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile)); box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile)); applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(box); if (quartileBox) *quartileBox = box; } /*! \internal Draws the median line inside the quartile box. */ void QCPStatisticalBox::drawMedian(QCPPainter *painter) const { QLineF medianLine; medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian)); medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian)); applyDefaultAntialiasingHint(painter); painter->setPen(mMedianPen); painter->drawLine(medianLine); } /*! \internal Draws both whisker backbones and bars. */ void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const { QLineF backboneMin, backboneMax, barMin, barMax; backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum)); backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum)); barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum)); barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum)); applyErrorBarsAntialiasingHint(painter); painter->setPen(mWhiskerPen); painter->drawLine(backboneMin); painter->drawLine(backboneMax); painter->setPen(mWhiskerBarPen); painter->drawLine(barMin); painter->drawLine(barMax); } /*! \internal Draws the outlier scatter points. */ void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const { applyScattersAntialiasingHint(painter); mOutlierStyle.applyTo(painter, mPen); for (int i=0; i 0) return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); else if (mKey > 0) return QCPRange(mKey, mKey+mWidth*0.5); else { foundRange = false; return QCPRange(); } } foundRange = false; return QCPRange(); } /* inherits documentation from base class */ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QVector values; // values that must be considered (i.e. all outliers and the five box-parameters) values.reserve(mOutliers.size() + 5); values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum; values << mOutliers; // go through values and find the ones in legal range: bool haveUpper = false; bool haveLower = false; double upper = 0; double lower = 0; for (int i=0; i 0) || (inSignDomain == sdBoth)) { if (values.at(i) > upper || !haveUpper) { upper = values.at(i); haveUpper = true; } if (values.at(i) < lower || !haveLower) { lower = values.at(i); haveLower = true; } } } // return the bounds if we found some sensible values: if (haveLower && haveUpper) { foundRange = true; return QCPRange(lower, upper); } else // might happen if all values are in other sign domain { foundRange = false; return QCPRange(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorMapData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorMapData \brief Holds the two-dimensional data of a QCPColorMap plottable. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a color, depending on the value. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref setKeyRange, \ref setValueRange). The data cells can be accessed in two ways: They can be directly addressed by an integer index with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are provided by the functions \ref coordToCell and \ref cellToCoord. This class also buffers the minimum and maximum values that are in the data set, to provide QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value that is greater than the current maximum increases this maximum to the new value. However, setting the cell that currently holds the maximum value to a smaller value doesn't decrease the maximum again, because finding the true new maximum would require going through the entire data array, which might be time consuming. The same holds for the data minimum. This functionality is given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience parameter \a recalculateDataBounds which may be set to true to automatically call \ref recalculateDataBounds internally. */ /* start of documentation of inline functions */ /*! \fn bool QCPColorMapData::isEmpty() const Returns whether this instance carries no data. This is equivalent to having a size where at least one of the dimensions is 0 (see \ref setSize). */ /* end of documentation of inline functions */ /*! Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap at the coordinates \a keyRange and \a valueRange. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange */ QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : mKeySize(0), mValueSize(0), mKeyRange(keyRange), mValueRange(valueRange), mIsEmpty(true), mData(0), mDataModified(true) { setSize(keySize, valueSize); fill(0); } QCPColorMapData::~QCPColorMapData() { if (mData) delete[] mData; } /*! Constructs a new QCPColorMapData instance copying the data and range of \a other. */ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : mKeySize(0), mValueSize(0), mIsEmpty(true), mData(0), mDataModified(true) { *this = other; } /*! Overwrites this color map data instance with the data stored in \a other. */ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { if (&other != this) { const int keySize = other.keySize(); const int valueSize = other.valueSize(); setSize(keySize, valueSize); setRange(other.keyRange(), other.valueRange()); if (!mIsEmpty) memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); mDataBounds = other.mDataBounds; mDataModified = true; } return *this; } /* undocumented getter */ double QCPColorMapData::data(double key, double value) { int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) return mData[valueCell*mKeySize + keyCell]; else return 0; } /* undocumented getter */ double QCPColorMapData::cell(int keyIndex, int valueIndex) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) return mData[valueIndex*mKeySize + keyIndex]; else return 0; } /*! Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in the value dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setRange, setKeySize, setValueSize */ void QCPColorMapData::setSize(int keySize, int valueSize) { if (keySize != mKeySize || valueSize != mValueSize) { mKeySize = keySize; mValueSize = valueSize; if (mData) delete[] mData; mIsEmpty = mKeySize == 0 || mValueSize == 0; if (!mIsEmpty) { #ifdef __EXCEPTIONS try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message #endif mData = new double[mKeySize*mValueSize]; #ifdef __EXCEPTIONS } catch (...) { mData = 0; } #endif if (mData) fill(0); else qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; } else mData = 0; mDataModified = true; } } /*! Resizes the data array to have \a keySize cells in the key dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. \see setKeyRange, setSize, setValueSize */ void QCPColorMapData::setKeySize(int keySize) { setSize(keySize, mValueSize); } /*! Resizes the data array to have \a valueSize cells in the value dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setValueRange, setSize, setKeySize */ void QCPColorMapData::setValueSize(int valueSize) { setSize(mKeySize, valueSize); } /*! Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. \see setSize */ void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) { setKeyRange(keyRange); setValueRange(valueRange); } /*! Sets the coordinate range the data shall be distributed over in the key dimension. Together with the value range, This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. \see setRange, setValueRange, setSize */ void QCPColorMapData::setKeyRange(const QCPRange &keyRange) { mKeyRange = keyRange; } /*! Sets the coordinate range the data shall be distributed over in the value dimension. Together with the key range, This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there will be cells centered on the value coordinates 2, 2.5 and 3. \see setRange, setKeyRange, setSize */ void QCPColorMapData::setValueRange(const QCPRange &valueRange) { mValueRange = valueRange; } /*! Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a z. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to determine the cell index. Rather directly access the cell index with \ref QCPColorMapData::setCell. \see setCell, setRange */ void QCPColorMapData::setData(double key, double value, double z) { int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { mData[valueCell*mKeySize + keyCell] = z; if (z < mDataBounds.lower) mDataBounds.lower = z; if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; } } /*! Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see \ref setSize). In the standard plot configuration (horizontal key axis and vertical value axis, both not range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with indices (keySize-1, valueSize-1) is in the top right corner of the color map. \see setData, setSize */ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { mData[valueIndex*mKeySize + keyIndex] = z; if (z < mDataBounds.lower) mDataBounds.lower = z; if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; } } /*! Goes through the data and updates the buffered minimum and maximum data values. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten with a smaller or larger value respectively, since the buffered maximum/minimum values have been updated the last time. Why this is the case is explained in the class description (\ref QCPColorMapData). Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a recalculateDataBounds for convenience. Setting this to true will call this method for you, before doing the rescale. */ void QCPColorMapData::recalculateDataBounds() { if (mKeySize > 0 && mValueSize > 0) { double minHeight = mData[0]; double maxHeight = mData[0]; const int dataCount = mValueSize*mKeySize; for (int i=0; i maxHeight) maxHeight = mData[i]; if (mData[i] < minHeight) minHeight = mData[i]; } mDataBounds.lower = minHeight; mDataBounds.upper = maxHeight; } } /*! Frees the internal data memory. This is equivalent to calling \ref setSize "setSize(0, 0)". */ void QCPColorMapData::clear() { setSize(0, 0); } /*! Sets all cells to the value \a z. */ void QCPColorMapData::fill(double z) { const int dataCount = mValueSize*mKeySize; for (int i=0; i(data); return; } if (copy) { *mMapData = *data; } else { delete mMapData; mMapData = data; } mMapImageInvalidated = true; } /*! Sets the data range of this color map to \a dataRange. The data range defines which data values are mapped to the color gradient. To make the data range span the full range of the data set, use \ref rescaleDataRange. \see QCPColorScale::setDataRange */ void QCPColorMap::setDataRange(const QCPRange &dataRange) { if (!QCPRange::validRange(dataRange)) return; if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { if (mDataScaleType == QCPAxis::stLogarithmic) mDataRange = dataRange.sanitizedForLogScale(); else mDataRange = dataRange.sanitizedForLinScale(); mMapImageInvalidated = true; emit dataRangeChanged(mDataRange); } } /*! Sets whether the data is correlated with the color gradient linearly or logarithmically. \see QCPColorScale::setDataScaleType */ void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) { if (mDataScaleType != scaleType) { mDataScaleType = scaleType; mMapImageInvalidated = true; emit dataScaleTypeChanged(mDataScaleType); if (mDataScaleType == QCPAxis::stLogarithmic) setDataRange(mDataRange.sanitizedForLogScale()); } } /*! Sets the color gradient that is used to represent the data. For more details on how to create an own gradient or use one of the preset gradients, see \ref QCPColorGradient. The colors defined by the gradient will be used to represent data values in the currently set data range, see \ref setDataRange. Data points that are outside this data range will either be colored uniformly with the respective gradient boundary color, or the gradient will repeat, depending on \ref QCPColorGradient::setPeriodic. \see QCPColorScale::setGradient */ void QCPColorMap::setGradient(const QCPColorGradient &gradient) { if (mGradient != gradient) { mGradient = gradient; mMapImageInvalidated = true; emit gradientChanged(mGradient); } } /*! Sets whether the color map image shall use bicubic interpolation when displaying the color map shrinked or expanded, and not at a 1:1 pixel-to-data scale. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" */ void QCPColorMap::setInterpolate(bool enabled) { mInterpolate = enabled; mMapImageInvalidated = true; // because oversampling factors might need to change } /*! Sets whether the outer most data rows and columns are clipped to the specified key and value range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). if \a enabled is set to false, the data points at the border of the color map are drawn with the same width and height as all other data points. Since the data points are represented by rectangles of one color centered on the data coordinate, this means that the shown color map extends by half a data point over the specified key/value range in each direction. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" */ void QCPColorMap::setTightBoundary(bool enabled) { mTightBoundary = enabled; } /*! Associates the color scale \a colorScale with this color map. This means that both the color scale and the color map synchronize their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps can be associated with one single color scale. This causes the color maps to also synchronize those properties, via the mutual color scale. This function causes the color map to adopt the current color gradient, data range and data scale type of \a colorScale. After this call, you may change these properties at either the color map or the color scale, and the setting will be applied to both. Pass 0 as \a colorScale to disconnect the color scale from this color map again. */ void QCPColorMap::setColorScale(QCPColorScale *colorScale) { if (mColorScale) // unconnect signals from old color scale { disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } mColorScale = colorScale; if (mColorScale) // connect signals to new color scale { setGradient(mColorScale.data()->gradient()); setDataRange(mColorScale.data()->dataRange()); setDataScaleType(mColorScale.data()->dataScaleType()); connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } } /*! Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, only for the third data dimension of the color map. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For performance reasons, however, they are only updated in an expanding fashion. So the buffered maximum can only increase and the buffered minimum can only decrease. In consequence, changes to the data that actually lower the maximum of the data set (by overwriting the cell holding the current maximum with a smaller value), aren't recognized and the buffered maximum overestimates the true maximum of the data set. The same happens for the buffered minimum. To recalculate the true minimum and maximum by explicitly looking at each cell, the method QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a recalculateDataBounds calls this method before setting the data range to the buffered minimum and maximum. \see setDataRange */ void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) { if (recalculateDataBounds) mMapData->recalculateDataBounds(); setDataRange(mMapData->dataBounds()); } /*! Takes the current appearance of the color map and updates the legend icon, which is used to represent this color map in the legend (see \ref QCPLegend). The \a transformMode specifies whether the rescaling is done by a faster, low quality image scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm (Qt::SmoothTransformation). The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured legend icon size, the thumb will be rescaled during drawing of the legend item. \see setDataRange */ void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) { if (mMapImage.isNull() && !data()->isEmpty()) updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again { bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); } } /*! Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also resizes the map to 0x0 cells. */ void QCPColorMap::clearData() { mMapData->clear(); } /* inherits documentation from base class */ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue)) return mParentPlot->selectionTolerance()*0.99; } return -1; } /*! \internal Updates the internal map image buffer by going through the internal \ref QCPColorMapData and turning the data values into color pixels with \ref QCPColorGradient::colorize. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image has been invalidated for a different reason (e.g. a change of the data range with \ref setDataRange). If the map cell count is low, the image created will be oversampled in order to avoid a QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images without smooth transform enabled. Accordingly, oversampling isn't performed if \ref setInterpolate is true. */ void QCPColorMap::updateMapImage() { QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) return; if (mMapData->isEmpty()) return; const int keySize = mMapData->keySize(); const int valueSize = mMapData->valueSize(); int keyOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)keySize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation: if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor)) mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), QImage::Format_RGB32); else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor)) mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), QImage::Format_RGB32); QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { // resize undersampled map image to actual key/value cell sizes: if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize)) mUndersampledMapImage = QImage(QSize(keySize, valueSize), QImage::Format_RGB32); else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) mUndersampledMapImage = QImage(QSize(valueSize, keySize), QImage::Format_RGB32); localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image } else if (!mUndersampledMapImage.isNull()) mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it const double *rawData = mMapData->mData; if (keyAxis->orientation() == Qt::Horizontal) { const int lineCount = valueSize; const int rowCount = keySize; for (int line=0; line(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); } } else // keyAxis->orientation() == Qt::Vertical { const int lineCount = keySize; const int rowCount = valueSize; for (int line=0; line(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); } } if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { if (keyAxis->orientation() == Qt::Horizontal) mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); else mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); } mMapData->mDataModified = false; mMapImageInvalidated = false; } /* inherits documentation from base class */ void QCPColorMap::draw(QCPPainter *painter) { if (mMapData->isEmpty()) return; if (!mKeyAxis || !mValueAxis) return; applyDefaultAntialiasingHint(painter); if (mMapData->mDataModified || mMapImageInvalidated) updateMapImage(); // use buffer if painting vectorized (PDF): bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized); QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in QPixmap mapBuffer; double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps if (useBuffer) { mapBufferTarget = painter->clipRegion().boundingRect(); mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize()); mapBuffer.fill(Qt::transparent); localPainter = new QCPPainter(&mapBuffer); localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); localPainter->translate(-mapBufferTarget.topLeft()); } QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): double halfCellWidth = 0; // in pixels double halfCellHeight = 0; // in pixels if (keyAxis()->orientation() == Qt::Horizontal) { if (mMapData->keySize() > 1) halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->keySize()-1); if (mMapData->valueSize() > 1) halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->valueSize()-1); } else // keyAxis orientation is Qt::Vertical { if (mMapData->keySize() > 1) halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->keySize()-1); if (mMapData->valueSize() > 1) halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->valueSize()-1); } imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform); localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); QRegion clipBackup; if (mTightBoundary) { clipBackup = localPainter->clipRegion(); QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); localPainter->setClipRect(tightClipRect, Qt::IntersectClip); } localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); if (mTightBoundary) localPainter->setClipRegion(clipBackup); localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter { delete localPainter; painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); } } /* inherits documentation from base class */ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { applyDefaultAntialiasingHint(painter); // draw map thumbnail: if (!mLegendIcon.isNull()) { QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); iconRect.moveCenter(rect.center()); painter->drawPixmap(iconRect.topLeft(), scaledIcon); } /* // draw frame: painter->setBrush(Qt::NoBrush); painter->setPen(Qt::black); painter->drawRect(rect.adjusted(1, 1, 0, 0)); */ } /* inherits documentation from base class */ QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { foundRange = true; QCPRange result = mMapData->keyRange(); result.normalize(); if (inSignDomain == QCPAbstractPlottable::sdPositive) { if (result.lower <= 0 && result.upper > 0) result.lower = result.upper*1e-3; else if (result.lower <= 0 && result.upper <= 0) foundRange = false; } else if (inSignDomain == QCPAbstractPlottable::sdNegative) { if (result.upper >= 0 && result.lower < 0) result.upper = result.lower*1e-3; else if (result.upper >= 0 && result.lower >= 0) foundRange = false; } return result; } /* inherits documentation from base class */ QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const { foundRange = true; QCPRange result = mMapData->valueRange(); result.normalize(); if (inSignDomain == QCPAbstractPlottable::sdPositive) { if (result.lower <= 0 && result.upper > 0) result.lower = result.upper*1e-3; else if (result.lower <= 0 && result.upper <= 0) foundRange = false; } else if (inSignDomain == QCPAbstractPlottable::sdNegative) { if (result.upper >= 0 && result.lower < 0) result.upper = result.lower*1e-3; else if (result.upper >= 0 && result.lower >= 0) foundRange = false; } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPFinancialData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPFinancialData \brief Holds the data of one single data point for QCPFinancial. The container for storing multiple data points is \ref QCPFinancialDataMap. The stored data is: \li \a key: coordinate on the key axis of this data point \li \a open: The opening value at the data point \li \a high: The high/maximum value at the data point \li \a low: The low/minimum value at the data point \li \a close: The closing value at the data point \see QCPFinancialDataMap */ /*! Constructs a data point with key and all values set to zero. */ QCPFinancialData::QCPFinancialData() : key(0), open(0), high(0), low(0), close(0) { } /*! Constructs a data point with the specified \a key and OHLC values. */ QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) : key(key), open(open), high(high), low(low), close(close) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPFinancial //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPFinancial \brief A plottable representing a financial stock chart \image html QCPFinancial.png This plottable represents time series data binned to certain intervals, mainly used for stock charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be set via \ref setChartStyle. The data is passed via \ref setData as a set of open/high/low/close values at certain keys (typically times). This means the data must be already binned appropriately. If data is only available as a series of values (e.g. \a price against \a time), you can use the static convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed to \ref setData. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and is given in plot key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width. \section appearance Changing the appearance Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored, lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush). If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are represented with a different pen and brush than negative changes (\a close < \a open). These can be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection however, the normal selected pen/brush (\ref setSelectedPen, \ref setSelectedBrush) is used, irrespective of whether the chart is single- or two-colored. */ /* start of documentation of inline functions */ /*! \fn QCPFinancialDataMap *QCPFinancial::data() const Returns a pointer to the internal data storage of type \ref QCPFinancialDataMap. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods, in certain situations. */ /* end of documentation of inline functions */ /*! Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPFinancial can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the financial chart. */ QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mData(0), mChartStyle(csOhlc), mWidth(0.5), mTwoColored(false), mBrushPositive(QBrush(QColor(210, 210, 255))), mBrushNegative(QBrush(QColor(255, 210, 210))), mPenPositive(QPen(QColor(10, 40, 180))), mPenNegative(QPen(QColor(180, 40, 10))) { mData = new QCPFinancialDataMap; setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); setSelectedBrush(QBrush(QColor(80, 80, 255))); } QCPFinancial::~QCPFinancial() { delete mData; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. Alternatively, you can also access and modify the plottable's data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialDataMap. \see timeSeriesToOhlc */ void QCPFinancial::setData(QCPFinancialDataMap *data, bool copy) { if (mData == data) { qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); return; } if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided open/high/low/close data. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. \see timeSeriesToOhlc */ void QCPFinancial::setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) { mData->clear(); int n = key.size(); n = qMin(n, open.size()); n = qMin(n, high.size()); n = qMin(n, low.size()); n = qMin(n, close.size()); for (int i=0; iinsertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); } } /*! Sets which representation style shall be used to display the OHLC data. */ void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style) { mChartStyle = style; } /*! Sets the width of the individual bars/candlesticks to \a width in plot key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width. */ void QCPFinancial::setWidth(double width) { mWidth = width; } /*! Sets whether this chart shall contrast positive from negative trends per data point by using two separate colors to draw the respective bars/candlesticks. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setTwoColored(bool twoColored) { mTwoColored = twoColored; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a positive trend (i.e. bars/candlesticks with close >= open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setBrushNegative, setPenPositive, setPenNegative */ void QCPFinancial::setBrushPositive(const QBrush &brush) { mBrushPositive = brush; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a negative trend (i.e. bars/candlesticks with close < open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setBrushPositive, setPenNegative, setPenPositive */ void QCPFinancial::setBrushNegative(const QBrush &brush) { mBrushNegative = brush; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setPenPositive(const QPen &pen) { mPenPositive = pen; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a negative trend (i.e. bars/candlesticks with close < open). If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). \see setPenPositive, setBrushNegative, setBrushPositive */ void QCPFinancial::setPenNegative(const QPen &pen) { mPenNegative = pen; } /*! Adds the provided data points in \a dataMap to the current data. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialDataMap. \see removeData */ void QCPFinancial::addData(const QCPFinancialDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialData. \see removeData */ void QCPFinancial::addData(const QCPFinancialData &data) { mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point given by \a key, \a open, \a high, \a low, and \a close to the current data. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialData. \see removeData */ void QCPFinancial::addData(double key, double open, double high, double low, double close) { mData->insertMulti(key, QCPFinancialData(key, open, high, low, close)); } /*! \overload Adds the provided open/high/low/close data to the current data. Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialData. \see removeData */ void QCPFinancial::addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) { int n = key.size(); n = qMin(n, open.size()); n = qMin(n, high.size()); n = qMin(n, low.size()); n = qMin(n, close.size()); for (int i=0; iinsertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); } } /*! Removes all data points with keys smaller than \a key. \see addData, clearData */ void QCPFinancial::removeDataBefore(double key) { QCPFinancialDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < key) it = mData->erase(it); } /*! Removes all data points with keys greater than \a key. \see addData, clearData */ void QCPFinancial::removeDataAfter(double key) { if (mData->isEmpty()) return; QCPFinancialDataMap::iterator it = mData->upperBound(key); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove a single data point with known key, use \ref removeData(double key). \see addData, clearData */ void QCPFinancial::removeData(double fromKey, double toKey) { if (fromKey >= toKey || mData->isEmpty()) return; QCPFinancialDataMap::iterator it = mData->upperBound(fromKey); QCPFinancialDataMap::iterator itEnd = mData->upperBound(toKey); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at \a key. If the position is not known with absolute precision, consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around the suspected position, depeding on the precision with which the key is known. \see addData, clearData */ void QCPFinancial::removeData(double key) { mData->remove(key); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPFinancial::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { // get visible data range: QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point getVisibleDataBounds(lower, upper); if (lower == mData->constEnd() || upper == mData->constEnd()) return -1; // perform select test according to configured style: switch (mChartStyle) { case QCPFinancial::csOhlc: return ohlcSelectTest(pos, lower, upper+1); break; case QCPFinancial::csCandlestick: return candlestickSelectTest(pos, lower, upper+1); break; } } return -1; } /*! A convenience function that converts time series data (\a value against \a time) to OHLC binned data points. The return value can then be passed on to \ref setData. The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour each, set \a timeBinSize to 3600. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys. It merely defines the mathematical offset/phase of the bins that will be used to process the data. */ QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) { QCPFinancialDataMap map; int count = qMin(time.size(), value.size()); if (count == 0) return QCPFinancialDataMap(); QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); for (int i=0; i currentBinData.high) currentBinData.high = value.at(i); if (i == count-1) // last data point is in current bin, finalize bin: { currentBinData.close = value.at(i); currentBinData.key = timeBinOffset+(index)*timeBinSize; map.insert(currentBinData.key, currentBinData); } } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map: { // finalize current bin: currentBinData.close = value.at(i-1); currentBinData.key = timeBinOffset+(index-1)*timeBinSize; map.insert(currentBinData.key, currentBinData); // start next bin: currentBinIndex = index; currentBinData.open = value.at(i); currentBinData.high = value.at(i); currentBinData.low = value.at(i); } } return map; } /* inherits documentation from base class */ void QCPFinancial::draw(QCPPainter *painter) { // get visible data range: QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point getVisibleDataBounds(lower, upper); if (lower == mData->constEnd() || upper == mData->constEnd()) return; // draw visible data range according to configured style: switch (mChartStyle) { case QCPFinancial::csOhlc: drawOhlcPlot(painter, lower, upper+1); break; case QCPFinancial::csCandlestick: drawCandlestickPlot(painter, lower, upper+1); break; } } /* inherits documentation from base class */ void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing if (mChartStyle == csOhlc) { if (mTwoColored) { // draw upper left half icon with positive color: painter->setBrush(mBrushPositive); painter->setPen(mPenPositive); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); // draw bottom right hald icon with negative color: painter->setBrush(mBrushNegative); painter->setPen(mPenNegative); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); } else { painter->setBrush(mBrush); painter->setPen(mPen); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); } } else if (mChartStyle == csCandlestick) { if (mTwoColored) { // draw upper left half icon with positive color: painter->setBrush(mBrushPositive); painter->setPen(mPenPositive); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); // draw bottom right hald icon with negative color: painter->setBrush(mBrushNegative); painter->setPen(mPenNegative); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); } else { painter->setBrush(mBrush); painter->setPen(mPen); painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); } } } /* inherits documentation from base class */ QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPFinancialDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } // determine exact range by including width of bars/flags: if (haveLower && mKeyAxis) range.lower = range.lower-mWidth*0.5; if (haveUpper && mKeyAxis) range.upper = range.upper+mWidth*0.5; foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPFinancial::getValueRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; QCPFinancialDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { // high: if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().high < 0) || (inSignDomain == sdPositive && it.value().high > 0)) { if (it.value().high < range.lower || !haveLower) { range.lower = it.value().high; haveLower = true; } if (it.value().high > range.upper || !haveUpper) { range.upper = it.value().high; haveUpper = true; } } // low: if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().low < 0) || (inSignDomain == sdPositive && it.value().low > 0)) { if (it.value().low < range.lower || !haveLower) { range.lower = it.value().low; haveLower = true; } if (it.value().low > range.upper || !haveUpper) { range.upper = it.value().low; haveUpper = true; } } ++it; } foundRange = haveLower && haveUpper; return range; } /*! \internal Draws the data from \a begin to \a end as OHLC bars with the provided \a painter. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc. */ void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QPen linePen; if (keyAxis->orientation() == Qt::Horizontal) { for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { if (mSelected) linePen = mSelectedPen; else if (mTwoColored) linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; else linePen = mPen; painter->setPen(linePen); double keyPixel = keyAxis->coordToPixel(it.value().key); double openPixel = valueAxis->coordToPixel(it.value().open); double closePixel = valueAxis->coordToPixel(it.value().close); // draw backbone: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low))); // draw open: double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides painter->drawLine(QPointF(keyPixel-keyWidthPixels, openPixel), QPointF(keyPixel, openPixel)); // draw close: painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+keyWidthPixels, closePixel)); } } else { for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { if (mSelected) linePen = mSelectedPen; else if (mTwoColored) linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; else linePen = mPen; painter->setPen(linePen); double keyPixel = keyAxis->coordToPixel(it.value().key); double openPixel = valueAxis->coordToPixel(it.value().open); double closePixel = valueAxis->coordToPixel(it.value().close); // draw backbone: painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel)); // draw open: double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides painter->drawLine(QPointF(openPixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel)); // draw close: painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+keyWidthPixels)); } } } /*! \internal Draws the data from \a begin to \a end as Candlesticks with the provided \a painter. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick. */ void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QPen linePen; QBrush boxBrush; if (keyAxis->orientation() == Qt::Horizontal) { for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { if (mSelected) { linePen = mSelectedPen; boxBrush = mSelectedBrush; } else if (mTwoColored) { if (it.value().close >= it.value().open) { linePen = mPenPositive; boxBrush = mBrushPositive; } else { linePen = mPenNegative; boxBrush = mBrushNegative; } } else { linePen = mPen; boxBrush = mBrush; } painter->setPen(linePen); painter->setBrush(boxBrush); double keyPixel = keyAxis->coordToPixel(it.value().key); double openPixel = valueAxis->coordToPixel(it.value().open); double closePixel = valueAxis->coordToPixel(it.value().close); // draw high: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close)))); // draw low: painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close)))); // draw open-close box: double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); painter->drawRect(QRectF(QPointF(keyPixel-keyWidthPixels, closePixel), QPointF(keyPixel+keyWidthPixels, openPixel))); } } else // keyAxis->orientation() == Qt::Vertical { for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { if (mSelected) { linePen = mSelectedPen; boxBrush = mSelectedBrush; } else if (mTwoColored) { if (it.value().close >= it.value().open) { linePen = mPenPositive; boxBrush = mBrushPositive; } else { linePen = mPenNegative; boxBrush = mBrushNegative; } } else { linePen = mPen; boxBrush = mBrush; } painter->setPen(linePen); painter->setBrush(boxBrush); double keyPixel = keyAxis->coordToPixel(it.value().key); double openPixel = valueAxis->coordToPixel(it.value().open); double closePixel = valueAxis->coordToPixel(it.value().close); // draw high: painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel)); // draw low: painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel)); // draw open-close box: double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); painter->drawRect(QRectF(QPointF(closePixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel+keyWidthPixels))); } } } /*! \internal This method is a helper function for \ref selectTest. It is used to test for selection when the chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end. */ double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } double minDistSqr = std::numeric_limits::max(); QCPFinancialDataMap::const_iterator it; if (keyAxis->orientation() == Qt::Horizontal) { for (it = begin; it != end; ++it) { double keyPixel = keyAxis->coordToPixel(it.value().key); // calculate distance to backbone: double currentDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } else // keyAxis->orientation() == Qt::Vertical { for (it = begin; it != end; ++it) { double keyPixel = keyAxis->coordToPixel(it.value().key); // calculate distance to backbone: double currentDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } return qSqrt(minDistSqr); } /*! \internal This method is a helper function for \ref selectTest. It is used to test for selection when the chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a end. */ double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } double minDistSqr = std::numeric_limits::max(); QCPFinancialDataMap::const_iterator it; if (keyAxis->orientation() == Qt::Horizontal) { for (it = begin; it != end; ++it) { double currentDistSqr; // determine whether pos is in open-close-box: QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); QCPRange boxValueRange(it.value().close, it.value().open); double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box { currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; } else { // calculate distance to high/low lines: double keyPixel = keyAxis->coordToPixel(it.value().key); double highLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close))), pos); double lowLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close))), pos); currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); } if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } else // keyAxis->orientation() == Qt::Vertical { for (it = begin; it != end; ++it) { double currentDistSqr; // determine whether pos is in open-close-box: QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); QCPRange boxValueRange(it.value().close, it.value().open); double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box { currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; } else { // calculate distance to high/low lines: double keyPixel = keyAxis->coordToPixel(it.value().key); double highLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel), pos); double lowLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel), pos); currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); } if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } return qSqrt(minDistSqr); } /*! \internal called by the drawing methods to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. \a lower returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie just outside of the visible range. if the plottable contains no data, both \a lower and \a upper point to constEnd. \see QCPGraph::getVisibleDataBounds */ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } if (mData->isEmpty()) { lower = mData->constEnd(); upper = mData->constEnd(); return; } // get visible data range as QMap iterators QCPFinancialDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); QCPFinancialDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemStraightLine //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemStraightLine \brief A straight line that spans infinitely in both directions \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a point1 and \a point2, which define the straight line. */ /*! Creates a straight line item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), point1(createPosition(QLatin1String("point1"))), point2(createPosition(QLatin1String("point2"))) { point1->setCoords(0, 0); point2->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemStraightLine::~QCPItemStraightLine() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemStraightLine::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemStraightLine::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); } /* inherits documentation from base class */ void QCPItemStraightLine::draw(QCPPainter *painter) { QVector2D start(point1->pixelPoint()); QVector2D end(point2->pixelPoint()); // get visible segment of straight line inside clipRect: double clipPad = mainPen().widthF(); QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); // paint visible segment, if existent: if (!line.isNull()) { painter->setPen(mainPen()); painter->drawLine(line); } } /*! \internal finds the shortest distance of \a point to the straight line defined by the base point \a base and the direction vector \a vec. This is a helper function for \ref selectTest. */ double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const { return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length(); } /*! \internal Returns the section of the straight line defined by \a base and direction vector \a vec, that is visible in the specified \a rect. This is a helper function for \ref draw. */ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const { double bx, by; double gamma; QLineF result; if (vec.x() == 0 && vec.y() == 0) return result; if (qFuzzyIsNull(vec.x())) // line is vertical { // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical } else if (qFuzzyIsNull(vec.y())) // line is horizontal { // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal } else // line is skewed { QList pointVectors; // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); // check bottom of rect: bx = rect.left(); by = rect.bottom(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); // check right of rect: bx = rect.right(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); // evaluate points: if (pointVectors.size() == 2) { result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); } else if (pointVectors.size() > 2) { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; QVector2D pv1, pv2; for (int i=0; i distSqrMax) { pv1 = pointVectors.at(i); pv2 = pointVectors.at(k); distSqrMax = distSqr; } } } result.setPoints(pv1.toPointF(), pv2.toPointF()); } } return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemStraightLine::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemLine //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemLine \brief A line from one point to another \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a start and \a end, which define the end points of the line. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. */ /*! Creates a line item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), start(createPosition(QLatin1String("start"))), end(createPosition(QLatin1String("end"))) { start->setCoords(0, 0); end->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemLine::~QCPItemLine() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemLine::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemLine::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode \see setTail */ void QCPItemLine::setHead(const QCPLineEnding &head) { mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode \see setHead */ void QCPItemLine::setTail(const QCPLineEnding &tail) { mTail = tail; } /* inherits documentation from base class */ double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); } /* inherits documentation from base class */ void QCPItemLine::draw(QCPPainter *painter) { QVector2D startVec(start->pixelPoint()); QVector2D endVec(end->pixelPoint()); if (startVec.toPoint() == endVec.toPoint()) return; // get visible segment of straight line inside clipRect: double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); clipPad = qMax(clipPad, (double)mainPen().widthF()); QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); // paint visible segment, if existent: if (!line.isNull()) { painter->setPen(mainPen()); painter->drawLine(line); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) mTail.draw(painter, startVec, startVec-endVec); if (mHead.style() != QCPLineEnding::esNone) mHead.draw(painter, endVec, endVec-startVec); } } /*! \internal Returns the section of the line defined by \a start and \a end, that is visible in the specified \a rect. This is a helper function for \ref draw. */ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const { bool containsStart = rect.contains(start.x(), start.y()); bool containsEnd = rect.contains(end.x(), end.y()); if (containsStart && containsEnd) return QLineF(start.toPointF(), end.toPointF()); QVector2D base = start; QVector2D vec = end-start; double bx, by; double gamma, mu; QLineF result; QList pointVectors; if (!qFuzzyIsNull(vec.y())) // line is not horizontal { // check top of rect: bx = rect.left(); by = rect.top(); mu = (by-base.y())/vec.y(); if (mu >= 0 && mu <= 1) { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); } // check bottom of rect: bx = rect.left(); by = rect.bottom(); mu = (by-base.y())/vec.y(); if (mu >= 0 && mu <= 1) { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); } } if (!qFuzzyIsNull(vec.x())) // line is not vertical { // check left of rect: bx = rect.left(); by = rect.top(); mu = (bx-base.x())/vec.x(); if (mu >= 0 && mu <= 1) { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); } // check right of rect: bx = rect.right(); by = rect.top(); mu = (bx-base.x())/vec.x(); if (mu >= 0 && mu <= 1) { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); } } if (containsStart) pointVectors.append(start); if (containsEnd) pointVectors.append(end); // evaluate points: if (pointVectors.size() == 2) { result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); } else if (pointVectors.size() > 2) { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; QVector2D pv1, pv2; for (int i=0; i distSqrMax) { pv1 = pointVectors.at(i); pv2 = pointVectors.at(k); distSqrMax = distSqr; } } } result.setPoints(pv1.toPointF(), pv2.toPointF()); } return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemLine::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemCurve //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemCurve \brief A curved line from one point to another \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions." It has four positions, \a start and \a end, which define the end points of the line, and two control points which define the direction the line exits from the start and the direction from which it approaches the end: \a startDir and \a endDir. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. Often it is desirable for the control points to stay at fixed relative positions to the start/end point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. */ /*! Creates a curve item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), start(createPosition(QLatin1String("start"))), startDir(createPosition(QLatin1String("startDir"))), endDir(createPosition(QLatin1String("endDir"))), end(createPosition(QLatin1String("end"))) { start->setCoords(0, 0); startDir->setCoords(0.5, 0); endDir->setCoords(0, 0.5); end->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemCurve::~QCPItemCurve() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemCurve::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemCurve::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode \see setTail */ void QCPItemCurve::setHead(const QCPLineEnding &head) { mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode \see setHead */ void QCPItemCurve::setTail(const QCPLineEnding &tail) { mTail = tail; } /* inherits documentation from base class */ double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF startVec(start->pixelPoint()); QPointF startDirVec(startDir->pixelPoint()); QPointF endDirVec(endDir->pixelPoint()); QPointF endVec(end->pixelPoint()); QPainterPath cubicPath(startVec); cubicPath.cubicTo(startDirVec, endDirVec, endVec); QPolygonF polygon = cubicPath.toSubpathPolygons().first(); double minDistSqr = std::numeric_limits::max(); for (int i=1; ipixelPoint()); QPointF startDirVec(startDir->pixelPoint()); QPointF endDirVec(endDir->pixelPoint()); QPointF endVec(end->pixelPoint()); if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash return; QPainterPath cubicPath(startVec); cubicPath.cubicTo(startDirVec, endDirVec, endVec); // paint visible segment, if existent: QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); QRect cubicRect = cubicPath.controlPointRect().toRect(); if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position cubicRect.adjust(0, 0, 1, 1); if (clip.intersects(cubicRect)) { painter->setPen(mainPen()); painter->drawPath(cubicPath); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); if (mHead.style() != QCPLineEnding::esNone) mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI); } } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemCurve::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemRect //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemRect \brief A rectangle \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rectangle. */ /*! Creates a rectangle item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } QCPItemRect::~QCPItemRect() { } /*! Sets the pen that will be used to draw the line of the rectangle \see setSelectedPen, setBrush */ void QCPItemRect::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the rectangle when selected \see setPen, setSelected */ void QCPItemRect::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen */ void QCPItemRect::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemRect::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; return rectSelectTest(rect, pos, filledRect); } /* inherits documentation from base class */ void QCPItemRect::draw(QCPPainter *painter) { QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); if (p1.toPoint() == p2.toPoint()) return; QRectF rect = QRectF(p1, p2).normalized(); double clipPad = mainPen().widthF(); QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect { painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(rect); } } /* inherits documentation from base class */ QPointF QCPItemRect::anchorPixelPoint(int anchorId) const { QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRight: return rect.topRight(); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeft: return rect.bottomLeft(); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemRect::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemRect::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemText //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemText \brief A text label \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions." Its position is defined by the member \a position and the setting of \ref setPositionAlignment. The latter controls which part of the text rect shall be aligned with \a position. The text alignment itself (i.e. left, center, right) can be controlled with \ref setTextAlignment. The text may be rotated around the \a position point with \ref setRotation. */ /*! Creates a text item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemText::QCPItemText(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition(QLatin1String("position"))), topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)) { position->setCoords(0, 0); setRotation(0); setTextAlignment(Qt::AlignTop|Qt::AlignHCenter); setPositionAlignment(Qt::AlignCenter); setText(QLatin1String("text")); setPen(Qt::NoPen); setSelectedPen(Qt::NoPen); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); setColor(Qt::black); setSelectedColor(Qt::blue); } QCPItemText::~QCPItemText() { } /*! Sets the color of the text. */ void QCPItemText::setColor(const QColor &color) { mColor = color; } /*! Sets the color of the text that will be used when the item is selected. */ void QCPItemText::setSelectedColor(const QColor &color) { mSelectedColor = color; } /*! Sets the pen that will be used do draw a rectangular border around the text. To disable the border, set \a pen to Qt::NoPen. \see setSelectedPen, setBrush, setPadding */ void QCPItemText::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used do draw a rectangular border around the text, when the item is selected. To disable the border, set \a pen to Qt::NoPen. \see setPen */ void QCPItemText::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used do fill the background of the text. To disable the background, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen, setPadding */ void QCPItemText::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the background, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemText::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the font of the text. \see setSelectedFont, setColor */ void QCPItemText::setFont(const QFont &font) { mFont = font; } /*! Sets the font of the text that will be used when the item is selected. \see setFont */ void QCPItemText::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! Sets the text that will be displayed. Multi-line texts are supported by inserting a line break character, e.g. '\n'. \see setFont, setColor, setTextAlignment */ void QCPItemText::setText(const QString &text) { mText = text; } /*! Sets which point of the text rect shall be aligned with \a position. Examples: \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such that the top of the text rect will be horizontally centered on \a position. \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the bottom left corner of the text rect. If you want to control the alignment of (multi-lined) text within the text rect, use \ref setTextAlignment. */ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) { mPositionAlignment = alignment; } /*! Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight). */ void QCPItemText::setTextAlignment(Qt::Alignment alignment) { mTextAlignment = alignment; } /*! Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated around \a position. */ void QCPItemText::setRotation(double degrees) { mRotation = degrees; } /*! Sets the distance between the border of the text rectangle and the text. The appearance (and visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush. */ void QCPItemText::setPadding(const QMargins &padding) { mPadding = padding; } /* inherits documentation from base class */ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; // The rect may be rotated, so we transform the actual clicked pos to the rotated // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects: QPointF positionPixels(position->pixelPoint()); QTransform inputTransform; inputTransform.translate(positionPixels.x(), positionPixels.y()); inputTransform.rotate(-mRotation); inputTransform.translate(-positionPixels.x(), -positionPixels.y()); QPointF rotatedPos = inputTransform.map(pos); QFontMetrics fontMetrics(mFont); QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); textBoxRect.moveTopLeft(textPos.toPoint()); return rectSelectTest(textBoxRect, rotatedPos, true); } /* inherits documentation from base class */ void QCPItemText::draw(QCPPainter *painter) { QPointF pos(position->pixelPoint()); QTransform transform = painter->transform(); transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) transform.rotate(mRotation); painter->setFont(mainFont()); QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); textBoxRect.moveTopLeft(textPos.toPoint()); double clipPad = mainPen().widthF(); QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) { painter->setTransform(transform); if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) { painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(textBoxRect); } painter->setBrush(Qt::NoBrush); painter->setPen(QPen(mainColor())); painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); } } /* inherits documentation from base class */ QPointF QCPItemText::anchorPixelPoint(int anchorId) const { // get actual rect points (pretty much copied from draw function): QPointF pos(position->pixelPoint()); QTransform transform; transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) transform.rotate(mRotation); QFontMetrics fontMetrics(mainFont()); QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation textBoxRect.moveTopLeft(textPos.toPoint()); QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); switch (anchorId) { case aiTopLeft: return rectPoly.at(0); case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; case aiTopRight: return rectPoly.at(1); case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; case aiBottomRight: return rectPoly.at(2); case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; case aiBottomLeft: return rectPoly.at(3); case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the point that must be given to the QPainter::drawText function (which expects the top left point of the text rect), according to the position \a pos, the text bounding box \a rect and the requested \a positionAlignment. For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally drawn at that point, the lower left corner of the resulting text rect is at \a pos. */ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const { if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) return pos; QPointF result = pos; // start at top left if (positionAlignment.testFlag(Qt::AlignHCenter)) result.rx() -= rect.width()/2.0; else if (positionAlignment.testFlag(Qt::AlignRight)) result.rx() -= rect.width(); if (positionAlignment.testFlag(Qt::AlignVCenter)) result.ry() -= rect.height()/2.0; else if (positionAlignment.testFlag(Qt::AlignBottom)) result.ry() -= rect.height(); return result; } /*! \internal Returns the font that should be used for drawing text. Returns mFont when the item is not selected and mSelectedFont when it is. */ QFont QCPItemText::mainFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Returns the color that should be used for drawing text. Returns mColor when the item is not selected and mSelectedColor when it is. */ QColor QCPItemText::mainColor() const { return mSelected ? mSelectedColor : mColor; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemText::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemText::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemEllipse //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemEllipse \brief An ellipse \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in. */ /*! Creates an ellipse item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), top(createAnchor(QLatin1String("top"), aiTop)), topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), right(createAnchor(QLatin1String("right"), aiRight)), bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), left(createAnchor(QLatin1String("left"), aiLeft)), center(createAnchor(QLatin1String("center"), aiCenter)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } QCPItemEllipse::~QCPItemEllipse() { } /*! Sets the pen that will be used to draw the line of the ellipse \see setSelectedPen, setBrush */ void QCPItemEllipse::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the ellipse when selected \see setPen, setSelected */ void QCPItemEllipse::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen */ void QCPItemEllipse::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemEllipse::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; double result = -1; QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); QPointF center((p1+p2)/2.0); double a = qAbs(p1.x()-p2.x())/2.0; double b = qAbs(p1.y()-p2.y())/2.0; double x = pos.x()-center.x(); double y = pos.y()-center.y(); // distance to border: double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); result = qAbs(c-1)*qSqrt(x*x+y*y); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { if (x*x/(a*a) + y*y/(b*b) <= 1) result = mParentPlot->selectionTolerance()*0.99; } return result; } /* inherits documentation from base class */ void QCPItemEllipse::draw(QCPPainter *painter) { QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); if (p1.toPoint() == p2.toPoint()) return; QRectF ellipseRect = QRectF(p1, p2).normalized(); QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect { painter->setPen(mainPen()); painter->setBrush(mainBrush()); #ifdef __EXCEPTIONS try // drawEllipse sometimes throws exceptions if ellipse is too big { #endif painter->drawEllipse(ellipseRect); #ifdef __EXCEPTIONS } catch (...) { qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; setVisible(false); } #endif } } /* inherits documentation from base class */ QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const { QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); switch (anchorId) { case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemEllipse::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemEllipse::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPixmap //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemPixmap \brief An arbitrary pixmap \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to fit the rectangle or be drawn aligned to the topLeft position. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown on the right side of the example image), the pixmap will be flipped in the respective orientations. */ /*! Creates a rectangle item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition(QLatin1String("topLeft"))), bottomRight(createPosition(QLatin1String("bottomRight"))), top(createAnchor(QLatin1String("top"), aiTop)), topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), right(createAnchor(QLatin1String("right"), aiRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), left(createAnchor(QLatin1String("left"), aiLeft)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(Qt::NoPen); setSelectedPen(QPen(Qt::blue)); setScaled(false, Qt::KeepAspectRatio, Qt::SmoothTransformation); } QCPItemPixmap::~QCPItemPixmap() { } /*! Sets the pixmap that will be displayed. */ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) { mPixmap = pixmap; if (mPixmap.isNull()) qDebug() << Q_FUNC_INFO << "pixmap is null"; } /*! Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a bottomRight positions. */ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode) { mScaled = scaled; mAspectRatioMode = aspectRatioMode; mTransformationMode = transformationMode; updateScaledPixmap(); } /*! Sets the pen that will be used to draw a border around the pixmap. \see setSelectedPen, setBrush */ void QCPItemPixmap::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw a border around the pixmap when selected \see setPen, setSelected */ void QCPItemPixmap::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return rectSelectTest(getFinalRect(), pos, true); } /* inherits documentation from base class */ void QCPItemPixmap::draw(QCPPainter *painter) { bool flipHorz = false; bool flipVert = false; QRect rect = getFinalRect(&flipHorz, &flipVert); double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (boundingRect.intersects(clipRect())) { updateScaledPixmap(rect, flipHorz, flipVert); painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); QPen pen = mainPen(); if (pen.style() != Qt::NoPen) { painter->setPen(pen); painter->setBrush(Qt::NoBrush); painter->drawRect(rect); } } } /* inherits documentation from base class */ QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const { bool flipHorz; bool flipVert; QRect rect = getFinalRect(&flipHorz, &flipVert); // we actually want denormal rects (negative width/height) here, so restore // the flipped state: if (flipHorz) rect.adjust(rect.width(), 0, -rect.width(), 0); if (flipVert) rect.adjust(0, rect.height(), 0, -rect.height()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRight: return rect.topRight(); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeft: return rect.bottomLeft(); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a bottomRight.) This function only creates the scaled pixmap when the buffered pixmap has a different size than the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does not cause expensive rescaling every time. If scaling is disabled, sets mScaledPixmap to a null QPixmap. */ void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) { if (mPixmap.isNull()) return; if (mScaled) { if (finalRect.isNull()) finalRect = getFinalRect(&flipHorz, &flipVert); if (finalRect.size() != mScaledPixmap.size()) { mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, mTransformationMode); if (flipHorz || flipVert) mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); } } else if (!mScaledPixmap.isNull()) mScaledPixmap = QPixmap(); } /*! \internal Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions and scaling settings. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn flipped horizontally or vertically in the returned rect. (The returned rect itself is always normalized, i.e. the top left corner of the rect is actually further to the top/left than the bottom right corner). This is the case when the item position \a topLeft is further to the bottom/right than \a bottomRight. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner aligned with the item position \a topLeft. The position \a bottomRight is ignored. */ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const { QRect result; bool flipHorz = false; bool flipVert = false; QPoint p1 = topLeft->pixelPoint().toPoint(); QPoint p2 = bottomRight->pixelPoint().toPoint(); if (p1 == p2) return QRect(p1, QSize(0, 0)); if (mScaled) { QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); QPoint topLeft = p1; if (newSize.width() < 0) { flipHorz = true; newSize.rwidth() *= -1; topLeft.setX(p2.x()); } if (newSize.height() < 0) { flipVert = true; newSize.rheight() *= -1; topLeft.setY(p2.y()); } QSize scaledSize = mPixmap.size(); scaledSize.scale(newSize, mAspectRatioMode); result = QRect(topLeft, scaledSize); } else { result = QRect(p1, mPixmap.size()); } if (flippedHorz) *flippedHorz = flipHorz; if (flippedVert) *flippedVert = flipVert; return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemPixmap::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemTracer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemTracer \brief Item that sticks to QCPGraph data points \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions." The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt the coordinate axes of the graph and update its \a position to be on the graph's data. This means the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a position will have no effect because they will be overriden in the next redraw (this is when the coordinate update happens). If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will stay at the corresponding end of the graph. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data points or whether it interpolates data points linearly, if given a key that lies between two data points of the graph. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer have no own visual appearance (set the style to \ref tsNone), and just connect other item positions to the tracer \a position (used as an anchor) via \ref QCPItemPosition::setParentAnchor. \note The tracer position is only automatically updated upon redraws. So when the data of the graph changes and immediately afterwards (without a redraw) the a position coordinates of the tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref updatePosition must be called manually, prior to reading the tracer coordinates. */ /*! Creates a tracer item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition(QLatin1String("position"))), mGraph(0) { position->setCoords(0, 0); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setStyle(tsCrosshair); setSize(6); setInterpolating(false); setGraphKey(0); } QCPItemTracer::~QCPItemTracer() { } /*! Sets the pen that will be used to draw the line of the tracer \see setSelectedPen, setBrush */ void QCPItemTracer::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the tracer when selected \see setPen, setSelected */ void QCPItemTracer::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to draw any fills of the tracer \see setSelectedBrush, setPen */ void QCPItemTracer::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to draw any fills of the tracer, when selected. \see setBrush, setSelected */ void QCPItemTracer::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare does, \ref tsCrosshair does not). */ void QCPItemTracer::setSize(double size) { mSize = size; } /*! Sets the style/visual appearance of the tracer. If you only want to use the tracer \a position as an anchor for other items, set \a style to \ref tsNone. */ void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) { mStyle = style; } /*! Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed freely like any other item position. This is the state the tracer will assume when its graph gets deleted while still attached to it. \see setGraphKey */ void QCPItemTracer::setGraph(QCPGraph *graph) { if (graph) { if (graph->parentPlot() == mParentPlot) { position->setType(QCPItemPosition::ptPlotCoords); position->setAxes(graph->keyAxis(), graph->valueAxis()); mGraph = graph; updatePosition(); } else qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; } else { mGraph = 0; } } /*! Sets the key of the graph's data point the tracer will be positioned at. This is the only free coordinate of a tracer when attached to a graph. Depending on \ref setInterpolating, the tracer will be either positioned on the data point closest to \a key, or will stay exactly at \a key and interpolate the value linearly. \see setGraph, setInterpolating */ void QCPItemTracer::setGraphKey(double key) { mGraphKey = key; } /*! Sets whether the value of the graph's data points shall be interpolated, when positioning the tracer. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on the data point of the graph which is closest to the key, but which is not necessarily exactly there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and the appropriate value will be interpolated from the graph's data points linearly. \see setGraph, setGraphKey */ void QCPItemTracer::setInterpolating(bool enabled) { mInterpolating = enabled; } /* inherits documentation from base class */ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF center(position->pixelPoint()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) { case tsNone: return -1; case tsPlus: { if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos), distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos))); break; } case tsCrosshair: { return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos), distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos))); } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { // distance to border: double centerDist = QVector2D(center-pos).length(); double circleLine = w; double result = qAbs(centerDist-circleLine); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { if (centerDist <= circleLine) result = mParentPlot->selectionTolerance()*0.99; } return result; } break; } case tsSquare: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; return rectSelectTest(rect, pos, filledRect); } break; } } return -1; } /* inherits documentation from base class */ void QCPItemTracer::draw(QCPPainter *painter) { updatePosition(); if (mStyle == tsNone) return; painter->setPen(mainPen()); painter->setBrush(mainBrush()); QPointF center(position->pixelPoint()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) { case tsNone: return; case tsPlus: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); } break; } case tsCrosshair: { if (center.y() > clip.top() && center.y() < clip.bottom()) painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); if (center.x() > clip.left() && center.x() < clip.right()) painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); break; } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) painter->drawEllipse(center, w, w); break; } case tsSquare: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); break; } } } /*! If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a position to reside on the graph data, depending on the configured key (\ref setGraphKey). It is called automatically on every redraw and normally doesn't need to be called manually. One exception is when you want to read the tracer coordinates via \a position and are not sure that the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. In that situation, call this function before accessing \a position, to make sure you don't get out-of-date coordinates. If there is no graph set on this tracer, this function does nothing. */ void QCPItemTracer::updatePosition() { if (mGraph) { if (mParentPlot->hasPlottable(mGraph)) { if (mGraph->data()->size() > 1) { QCPDataMap::const_iterator first = mGraph->data()->constBegin(); QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1; if (mGraphKey < first.key()) position->setCoords(first.key(), first.value().value); else if (mGraphKey > last.key()) position->setCoords(last.key(), last.value().value); else { QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); if (it != first) // mGraphKey is somewhere between iterators { QCPDataMap::const_iterator prevIt = it-1; if (mInterpolating) { // interpolate between iterators around mGraphKey: double slope = 0; if (!qFuzzyCompare((double)it.key(), (double)prevIt.key())) slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key()); position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value); } else { // find iterator with key closest to mGraphKey: if (mGraphKey < (prevIt.key()+it.key())*0.5) it = prevIt; position->setCoords(it.key(), it.value().value); } } else // mGraphKey is exactly on first iterator position->setCoords(it.key(), it.value().value); } } else if (mGraph->data()->size() == 1) { QCPDataMap::const_iterator it = mGraph->data()->constBegin(); position->setCoords(it.key(), it.value().value); } else qDebug() << Q_FUNC_INFO << "graph has no data"; } else qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; } } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemTracer::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemTracer::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemBracket //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemBracket \brief A bracket for referencing/highlighting certain parts in the plot. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a left and \a right, which define the span of the bracket. If \a left is actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the example image. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket stretches away from the embraced span, can be controlled with \ref setLength. \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine or QCPItemCurve) or a text label (QCPItemText), to the bracket. */ /*! Creates a bracket item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), left(createPosition(QLatin1String("left"))), right(createPosition(QLatin1String("right"))), center(createAnchor(QLatin1String("center"), aiCenter)) { left->setCoords(0, 0); right->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setLength(8); setStyle(bsCalligraphic); } QCPItemBracket::~QCPItemBracket() { } /*! Sets the pen that will be used to draw the bracket. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use \ref setLength, which has a similar effect. \see setSelectedPen */ void QCPItemBracket::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the bracket when selected \see setPen, setSelected */ void QCPItemBracket::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the \a length in pixels how far the bracket extends in the direction towards the embraced span of the bracket (i.e. perpendicular to the left-right-direction) \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
*/ void QCPItemBracket::setLength(double length) { mLength = length; } /*! Sets the style of the bracket, i.e. the shape/visual appearance. \see setPen */ void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) { mStyle = style; } /* inherits documentation from base class */ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return -1; QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; switch (mStyle) { case QCPItemBracket::bsSquare: case QCPItemBracket::bsRound: { double a = distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos); double b = distSqrToLine((centerVec-widthVec+lengthVec).toPointF(), (centerVec-widthVec).toPointF(), pos); double c = distSqrToLine((centerVec+widthVec+lengthVec).toPointF(), (centerVec+widthVec).toPointF(), pos); return qSqrt(qMin(qMin(a, b), c)); } case QCPItemBracket::bsCurly: case QCPItemBracket::bsCalligraphic: { double a = distSqrToLine((centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos); double b = distSqrToLine((centerVec-widthVec+lengthVec*0.7f).toPointF(), (centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), pos); double c = distSqrToLine((centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos); double d = distSqrToLine((centerVec+widthVec+lengthVec*0.7f).toPointF(), (centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), pos); return qSqrt(qMin(qMin(a, b), qMin(c, d))); } } return -1; } /* inherits documentation from base class */ void QCPItemBracket::draw(QCPPainter *painter) { QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return; QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; QPolygon boundingPoly; boundingPoly << leftVec.toPoint() << rightVec.toPoint() << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); if (clip.intersects(boundingPoly.boundingRect())) { painter->setPen(mainPen()); switch (mStyle) { case bsSquare: { painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); break; } case bsRound: { painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } case bsCurly: { painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } case bsCalligraphic: { painter->setPen(Qt::NoPen); painter->setBrush(QBrush(mainPen().color())); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF()); path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } } } } /* inherits documentation from base class */ QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const { QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return leftVec.toPointF(); QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; switch (anchorId) { case aiCenter: return centerVec.toPointF(); } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemBracket::mainPen() const { return mSelected ? mSelectedPen : mPen; } thermald-1.5/tools/thermal_monitor/qcustomplot/GPL.txt0000664000175000017500000010451312661205366021756 0ustar kingking GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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 . 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: Copyright (C) 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 . 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 . thermald-1.5/tools/thermal_monitor/qcustomplot/changelog.txt0000664000175000017500000007744212661205366023275 0ustar kingking#### Version 1.3.1 released on 25.04.15 #### Bugfixes: - Fixed bug that prevented automatic axis rescaling when some graphs/curves had only NaN data points - Improved QCPItemBracket selection boundaries, especially bsCurly and bsCalligraphic - Fixed bug of axis rect and colorscale background shifted downward by one logical pixel (visible in scaled png and pdf export) - Replot upon mouse release is now only performed if a selection change has actually happened (improves responsivity on particularly complex plots) - Fixed bug that allowed scatter-only graphs to be selected by clicking the non-existent line between scatters - Fixed crash when trying to select a scatter-only QCPGraph whose only points in the visible key range are at identical key coordinates and vertically off-screen, with adaptive sampling enabled - Fixed pdf export of QCPColorMap with enabled interpolation (didn't appear interpolated in pdf) - Reduced QCPColorMap jitter of internal cell boundaries for small sized maps when viewed with high zoom, by applying oversampling factors dependant on map size - Fixed bug of QCPColorMap::fill() not causing the buffered internal image map to be updated, and thus the change didn't become visible immediately - Axis labels with size set in pixels (setPixelSize) instead of points now correctly calculate the exponent's font size if beautifully typeset powers are enabled - Fixed QCPColorMap appearing at the wrong position for logarithmic axes and color map spanning larger ranges Other: - Pdf export used to embed entire QCPColorMaps, potentially leading to large files. Now only the visible portion of the map is embedded in the pdf - Many documentation fixes and extensions, style modernization - Reduced documentation file size (and thus full package size) by automatically reducing image palettes during package build - Fixed MSVC warning message (at warning level 4) due to temporary QLists in some foreach statements #### Version 1.3.0 released on 27.12.14 #### Added features: - New plottable class QCPFinancial allows display of candlestick/ohlc data - New class QCPBarsGroup allows horizontal grouping of multiple QCPBars plottables - Added QCPBars feature allowing non-zero base values (see property QCPBars::setBaseValue) - Added QCPBars width type, for more flexible bar widths (see property QCPBars::setWidthType) - New QCPCurve optimization algorithm, fixes bug which caused line flicker at deep zoom into curve segment - Item positions can now have different position types and anchors for their x and y coordinates (QCPItemPosition::setTypeX/Y, setParentAnchorX/Y) - QCPGraph and QCPCurve can now display gaps in their lines, when inserting quiet NaNs as values (std::numeric_limits::quiet_NaN()) - QCPAxis now supports placing the tick labels inside the axis rect, for particularly space saving plots (QCPAxis::setTickLabelSide) Added features after beta: - Made code compatible with QT_NO_CAST_FROM_ASCII, QT_NO_CAST_TO_ASCII - Added compatibility with QT_NO_KEYWORDS after sending code files through a simple reg-ex script - Added possibility to inject own QCPAxis(-subclasses) via second, optional QCPAxisRect::addAxis parameter - Added parameter to QCPItemPixmap::setScaled to specify transformation mode Bugfixes: - Fixed bug in QCPCurve rendering of very zoomed-in curves (via new optimization algorithm) - Fixed conflict with MSVC-specific keyword "interface" in text-document-integration example - Fixed QCPScatterStyle bug ignoring the specified pen in the custom scatter shape constructor - Fixed bug (possible crash) during QCustomPlot teardown, when a QCPLegend that has no parent layout (i.e. was removed from layout manually) gets deleted Bugfixes after beta: - Fixed bug of QCPColorMap/QCPColorGradient colors being off by one color sampling step (only noticeable in special cases) - Fixed bug of QCPGraph adaptive sampling on vertical key axis, causing staggered look - Fixed low (float) precision in QCPCurve optimization algorithm, by not using QVector2D anymore Other: - Qt 5.3 and Qt 5.4 compatibility #### Version 1.2.1 released on 07.04.14 #### Bugfixes: - Fixed regression which garbled date-time tick labels on axes, if setTickLabelType is ltDateTime and setNumberFormat contains the "b" option #### Version 1.2.0 released on 14.03.14 #### Added features: - Adaptive Sampling for QCPGraph greatly improves performance for high data densities (see QCPGraph::setAdaptiveSampling) - QCPColorMap plottable with QCPColorScale layout element allows plotting of 2D color maps - QCustomPlot::savePdf now has additional optional parameters pdfCreator and pdfTitle to set according PDF metadata fields - QCustomPlot::replot now allows specifying whether the widget update is immediate (repaint) or queued (update) - QCPRange operators +, -, *, / with double operand for range shifting and scaling, and ==, != for range comparison - Layers now have a visibility property (QCPLayer::setVisible) - static functions QCPAxis::opposite and QCPAxis::orientation now offer more convenience when handling axis types - added notification signals for selectability change (selectableChanged) on all objects that have a selected/selectable property - added notification signal for QCPAxis scaleType property - added notification signal QCPLayerable::layerChanged Bugfixes: - Fixed assert halt, when QCPAxis auto tick labels not disabled but nevertheless a custom non-number tick label ending in "e" given - Fixed painting glitches when QCustomPlot resized inside a QMdiArea or under certain conditions inside a QLayout - If changing QCPAxis::scaleType and thus causing range sanitizing and a range modification, rangeChanged wouldn't be emitted - Fixed documentation bug that caused indentation to be lost in code examples Bugfixes after beta: - Fixed bug that caused crash if clicked-on legend item is removed in mousePressEvent. - On some systems, font size defaults to -1, which used to cause a debug output in QCPAxisPainterPrivate::TickLabelDataQCP. Now it's checked before setting values based on the default font size. - When using multiple axes on one side, setting one to invisible didn't properly compress the freed space. - Fixed bug that allowed selection of plottables when clicking in the bottom or top margin of a QCPAxisRect (outside the inner rect) Other: - In method QCPAbstractPlottable::getKeyRange/getValueRange, renamed parameter "validRange" to "foundRange", to better reflect its meaning (and contrast it from QCPRange::validRange) - QCPAxis low-level axis painting methods exported to QCPAxisPainterPrivate #### Version 1.1.1 released on 09.12.13 #### Bugfixes: - Fixed bug causing legends blocking input events from reaching underlying axis rect even if legend is invisible - Added missing Q_PROPERTY for QCPAxis::setDateTimeSpec - Fixed behaviour of QCPAxisRect::setupFullAxesBox (now transfers more properties from bottom/left to top/right axes and sets visibility of bottom/left axes to true) - Made sure PDF export doesn't default to grayscale output on some systems Other: - Plotting hint QCP::phForceRepaint is now enabled on all systems (and not only on windows) by default - Documentation improvements #### Version 1.1.0 released on 04.11.13 #### Added features: - Added QCPRange::expand and QCPRange::expanded - Added QCPAxis::rescale to rescale axis to all associated plottables - Added QCPAxis::setDateTimeSpec/dateTimeSpec to allow axis labels either in UTC or local time - QCPAxis now additionally emits a rangeChanged signal overload that provides the old range as second parameter Bugfixes: - Fixed QCustomPlot::rescaleAxes not rescaling properly if first plottable has an empty range - QCPGraph::rescaleAxes/rescaleKeyAxis/rescaleValueAxis are no longer virtual (never were in base class, was a mistake) - Fixed bugs in QCPAxis::items and QCPAxisRect::items not properly returning associated items and potentially stalling Other: - Internal change from QWeakPointer to QPointer, thus got rid of deprecated Qt functionality - Qt5.1 and Qt5.2 (beta1) compatibility - Release packages now extract to single subdirectory and don't place multiple files in current working directory #### Version 1.0.1 released on 05.09.13 #### Bugfixes: - using define flag QCUSTOMPLOT_CHECK_DATA caused debug output when data was correct, instead of invalid (fixed QCP::isInvalidData) - documentation images are now properly shown when viewed with Qt Assistant - fixed various documentation mistakes Other: - Adapted documentation style sheet to better match Qt5 documentation #### Version 1.0.0 released on 01.08.13 #### Quick Summary: - Layout system for multiple axis rects in one plot - Multiple axes per side - Qt5 compatibility - More flexible and consistent scatter configuration with QCPScatterStyle - Various interface cleanups/refactoring - Pixmap-cached axis labels for improved replot performance Changes that break backward compatibility: - QCustomPlot::axisRect() changed meaning due to the extensive changes to how axes and axis rects are handled it now returns a pointer to a QCPAxisRect and takes an integer index as parameter. - QCPAxis constructor changed to now take QCPAxisRect* as parent - setAutoMargin, setMarginLeft/Right/Top/Bottom removed due to the axis rect changes (see QCPAxisRect::setMargins/setAutoMargins) - setAxisRect removed due to the axis rect changes - setAxisBackground(-Scaled/-ScaledMode) now moved to QCPAxisRect as setBackground(-Scaled/ScaledMode) (access via QCustomPlot::axisRects()) - QCPLegend now is a QCPLayoutElement - QCPAbstractPlottable::drawLegendIcon parameter "rect" changed from QRect to QRectF - QCPAbstractLegendItem::draw second parameter removed (position/size now handled via QCPLayoutElement base class) - removed QCPLegend::setMargin/setMarginLeft/Right/Top/Bottom (now inherits the capability from QCPLayoutElement::setMargins) - removed QCPLegend::setMinimumSize (now inherits the capability from QCPLayoutElement::setMinimumSize) - removed enum QCPLegend::PositionStyle, QCPLegend::positionStyle/setPositionStyle/position/setPosition (replaced by capabilities of QCPLayoutInset) - QCPLegend transformed to work with new layout system (almost everything changed) - removed entire title interface: QCustomPlot::setTitle/setTitleFont/setTitleColor/setTitleSelected/setTitleSelectedFont/setTitleSelectedColor and the QCustomPlot::iSelectTitle interaction flag (all functionality is now given by the layout element "QCPPlotTitle" which can be added to the plot layout) - selectTest functions now take two additional parameters: bool onlySelectable and QVariant *details=0 - selectTest functions now ignores visibility of objects and (if parameter onlySelectable is true) does not anymore ignore selectability of the object - moved QCustomPlot::Interaction/Interactions to QCP namespace as QCP::Interaction/Interactions - moved QCustomPlot::setupFullAxesBox() to QCPAxisRect::setupFullAxesBox. Now also accepts parameter to decide whether to connect opposite axis ranges - moved range dragging/zooming interface from QCustomPlot to QCPAxisRect (setRangeDrag, setRangeZoom, setRangeDragAxes, setRangeZoomAxes,...) - rangeDrag/Zoom is now set to Qt::Horizontal|Qt::Vertical instead of 0 by default, on the other hand, iRangeDrag/Zoom is unset in interactions by default (this makes enabling dragging/zooming easier by just adding the interaction flags) - QCPScatterStyle takes over everything related to handling scatters in all plottables - removed setScatterPen/Size on QCPGraph and QCPCurve, removed setOutlierPen/Size on QCPStatisticalBox (now handled via QCPScatterStyle) - modified setScatterStyle on QCPGraph and QCPCurve, and setOutlierStyle on QCPStatisticalBox, to take QCPScatterStyle - axis grid and subgrid are now reachable via the QCPGrid *QCPAxis::grid() method. (e.g. instead of xAxis->setGrid(true), write xAxis->grid()->setVisible(true)) Added features: - Axis tick labels are now pixmap-cached, thus increasing replot performance (in usual setups by about 24%). See plotting hint phCacheLabels which is set by default - Advanced layout system, including the classes QCPLayoutElement, QCPLayout, QCPLayoutGrid, QCPLayoutInset, QCPAxisRect - QCustomPlot::axisRects() returns all the axis rects in the QCustomPlot. - QCustomPlot::plotLayout() returns the top level layout (initially a QCPLayoutGrid with one QCPAxisRect inside) - QCPAxis now may have an offset to the axis rect (setOffset) - Multiple axes per QCPAxisRect side are now supported (see QCPAxisRect::addAxis) - QCustomPlot::toPixmap renders the plot into a pixmap and returns it - When setting tick label rotation to +90 or -90 degrees on a vertical axis, the labels are now centered vertically on the tick height (This allows space saving vertical tick labels by having the text direction parallel to the axis) - Substantially increased replot performance when using very large manual tick vectors (> 10000 ticks) via QCPAxis::setTickVector - QCPAxis and QCPAxisRect now allow easy access to all plottables(), graphs() and items() that are associated with them - Added QCustomPlot::hasItem method for consistency with plottable interface, hasPlottable - Added QCPAxisRect::setMinimumMargins as replacement for hardcoded minimum axis margin (15 px) when auto margin is enabled - Added Flags type QCPAxis::AxisTypes (from QCPAxis::AxisType), used in QCPAxisRect interface - Automatic margin calculation can now be enabled/disabled on a per-side basis, see QCPAxisRect::setAutoMargins - QCPAxisRect margins of multiple axis rects can be coupled via QCPMarginGroup - Added new default layers "background" and "legend" (QCPAxisRect draws its background on the "background" layer, QCPLegend is on the "legend" layer by default) - Custom scatter style via QCP::ssCustom and respective setCustomScatter functions that take a QPainterPath - Filled scatters via QCPScatterStyle::setBrush Added features after beta: - Added QCustomPlot::toPainter method, to allow rendering with existing painter - QCPItemEllipse now provides a center anchor Bugfixes: - Fixed compile error on ARM - Wrong legend icons were displayed if using pixmaps for scatters that are smaller than the legend icon rect - Fixed clipping inaccuracy for rotated tick labels (were hidden too early, because the non-rotated bounding box was used) - Fixed bug that caused wrong clipping of axis ticks and subticks when the ticks were given manually by QCPAxis::setTickVector - Fixed Qt5 crash when dragging graph out of view (iterator out of bounds in QCPGraph::getVisibleDataBounds) - Fixed QCPItemText not scaling properly when using scaled raster export Bugfixes after beta: - Fixed bug that clipped the rightmost pixel column of tick labels when caching activated (only visible on windows for superscript exponents) - Restored compatibility to Qt4.6 - Restored support for -no-RTTI compilation - Empty manual tick labels are handled more gracefully (no QPainter qDebug messages anymore) - Fixed type ambiguity in QCPLineEnding::draw causing compile error on ARM - Fixed bug of grid layouts not propagating the minimum size from their child elements to the parent layout correctly - Fixed bug of child elements (e.g. axis rects) of inset layouts not properly receiving mouse events Other: - Opened up non-amalgamated project structure to public via git repository #### Version released on 09.06.12 #### Quick Summary: - Items (arrows, text,...) - Layers (easier control over rendering order) - New antialiasing system (Each objects controls own antialiasing with setAntialiased) - Performance Improvements - improved pixel-precise drawing - easier shared library creation/usage Changes that (might) break backward compatibility: - enum QCPGraph::ScatterSymbol was moved to QCP namespace (now QCP::ScatterSymbol). This replace should fix your code: "QCPGraph::ss" -> "QCP::ss" - enum QCustomPlot::AntialiasedElement and flag QCustomPlot::AntialiasedElements was moved to QCP namespace This replace should fix your code: "QCustomPlot::ae" -> "QCP::ae" - the meaning of QCustomPlot::setAntialiasedElements has changed slightly: It is now an override to force elements to be antialiased. If you want to force elements to not be drawn antialiased, use the new setNotAntialiasedElements. If an element is mentioned in neither of those functions, it now controls its antialiasing itself via its "setAntialiased" function(s). (e.g. QCPAxis::setAntialiased(bool), QCPAbstractPlottable::setAntialiased(bool), QCPAbstractPlottable::setAntialiasedScatters(bool), etc.) - QCPAxis::setTickVector and QCPAxis::setTickVectorLabels no longer take a pointer but a const reference of the respective QVector as parameter. (handing over a pointer didn't give any noticeable performance benefits but was inconsistent with the rest of the interface) - Equally QCPAxis::tickVector and QCPAxis::tickVectorLabels don't return by pointer but by value now - QCustomPlot::savePngScaled was removed, its purpose is now included as optional parameter "scale" of savePng. - If you have derived from QCPAbstractPlottable: all selectTest functions now consistently take the argument "const QPointF &pos" which is the test point in pixel coordinates. (the argument there was "double key, double value" in plot coordinates, before). - QCPAbstractPlottable, QCPAxis and QCPLegend now inherit from QCPLayerable - If you have derived from QCPAbstractPlottable: the draw method signature has changed from "draw (..) const" to "draw (..)", i.e. the method is not const anymore. This allows the draw function of your plottable to perform buffering/caching operations, if necessary. Added features: - Item system: QCPAbstractItem, QCPItemAnchor, QCPItemPosition, QCPLineEnding. Allows placing of lines, arrows, text, pixmaps etc. - New Items: QCPItemStraightLine, QCPItemLine, QCPItemCurve, QCPItemEllipse, QCPItemRect, QCPItemPixmap, QCPItemText, QCPItemBracket, QCPItemTracer - QCustomPlot::addItem/itemCount/item/removeItem/selectedItems - signals QCustomPlot::itemClicked/itemDoubleClicked - the QCustomPlot interactions property now includes iSelectItems (for selection of QCPAbstractItem) - QCPLineEnding. Represents the different styles a line/curve can end (e.g. different arrows, circle, square, bar, etc.), see e.g. QCPItemCurve::setHead - Layer system: QCPLayerable, QCPLayer. Allows more sophisticated control over drawing order and a kind of grouping. - QCPAbstractPlottable, QCPAbstractItem, QCPAxis, QCPGrid, QCPLegend are layerables and derive from QCPLayerable - QCustomPlot::addLayer/moveLayer/removeLayer/setCurrentLayer/layer/currentLayer/layerCount - Initially there are three layers: "grid", "main", and "axes". The "main" layer is initially empty and set as current layer, so new plottables/items are put there. - QCustomPlot::viewport now makes the previously inaccessible viewport rect read-only-accessible (needed that for item-interface) - PNG export now allows transparent background by calling QCustomPlot::setColor(Qt::transparent) before savePng - QCPStatisticalBox outlier symbols may now be all scatter symbols, not only hardcoded circles. - perfect precision of scatter symbol/error bar drawing and clipping in both antialiased and non-antialiased mode, by introducing QCPPainter that works around some QPainter bugs/inconveniences. Further, more complex symbols like ssCrossSquare used to look crooked, now they look good. - new antialiasing control system: Each drawing element now has its own "setAntialiased" function to control whether it is drawn antialiased. - QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements can be used to override the individual settings. - Subclasses of QCPAbstractPlottable can now use the convenience functions like applyFillAntialiasingHint or applyScattersAntialiasingHint to easily make their drawing code comply with the overall antialiasing system. - QCustomPlot::setNoAntialiasingOnDrag allows greatly improved performance and responsiveness by temporarily disabling all antialiasing while the user is dragging axis ranges - QCPGraph can now show scatter symbols at data points and hide its line (see QCPGraph::setScatterStyle, setScatterSize, setScatterPixmap, setLineStyle) - Grid drawing code was sourced out from QCPAxis to QCPGrid. QCPGrid is mainly an internal class and every QCPAxis owns one. The grid interface still works through QCPAxis and hasn't changed. The separation allows the grid to be drawn on a different layer as the axes, such that e.g. a graph can be above the grid but below the axes. - QCustomPlot::hasPlottable(plottable), returns whether the QCustomPlot contains the plottable - QCustomPlot::setPlottingHint/setPlottingHints, plotting hints control details about the plotting quality/speed - export to jpg and bmp added (QCustomPlot::saveJpg/saveBmp), as well as control over compression quality for png and jpg - multi-select-modifier may now be specified with QCustomPlot::setMultiSelectModifier and is not fixed to Ctrl anymore Bugfixes: - fixed QCustomPlot ignores replot after it had size (0,0) even if size becomes valid again - on Windows, a repaint used to be delayed during dragging/zooming of a complex plot, until the drag operation was done. This was fixed, i.e. repaints are forced after a replot() call. See QCP::phForceRepaint and setPlottingHints. - when using the raster paintengine and exporting to scaled PNG, pen widths are now scaled correctly (QPainter bug workaround via QCPPainter) - PDF export now respects QCustomPlot background color (QCustomPlot::setColor), also Qt::transparent - fixed a bug on QCPBars and QCPStatisticalBox where auto-rescaling of axis would fail when all data is very small (< 1e-11) - fixed mouse event propagation bug that prevented range dragging from working on KDE (GNU/Linux) - fixed a compiler warning on 64-bit systems due to pointer cast to int instead of quintptr in a qDebug output Other: - Added support for easier shared library creation (including examples for compiling and using QCustomPlot as shared library) - QCustomPlot now has the Qt::WA_OpaquePaintEvent widget attribute (gives slightly improved performance). - QCP::aeGraphs (enum QCP::AntialiasedElement, previously QCustomPlot::aeGraphs) has been marked deprecated since version 02.02.12 and was now removed. Use QCP::aePlottables instead. - optional performance-quality-tradeoff for solid graph lines (see QCustomPlot::setPlottingHints). - marked data classes and QCPRange as Q_MOVABLE_TYPE - replaced usage of own macro FUNCNAME with Qt macro Q_FUNC_INFO - QCustomPlot now returns a minimum size hint of 50*50 #### Version released on 31.03.12 #### Changes that (might) break backward compatibility: - QCPAbstractLegendItem now inherits from QObject - mousePress, mouseMove and mouseRelease signals are now emitted before and not after any QCustomPlot processing (range dragging, selecting, etc.) Added features: - Interaction system: now allows selecting of objects like plottables, axes, legend and plot title, see QCustomPlot::setInteractions documentation - Interaction system for plottables: - setSelectable, setSelected, setSelectedPen, setSelectedBrush, selectTest on QCPAbstractPlottable and all derived plottables - setSelectionTolerance on QCustomPlot - selectedPlottables and selectedGraphs on QCustomPlot (returns the list of currently selected plottables/graphs) - Interaction system for axes: - setSelectable, setSelected, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedLabelFont, setSelectedTickLabelFont, setSelectedLabelColor, setSelectedTickLabelColor, selectTest on QCPAxis - selectedAxes on QCustomPlot (returns a list of the axes that currently have selected parts) - Interaction system for legend: - setSelectable, setSelected, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont, setSelectedTextColor, selectedItems on QCPLegend - setSelectedFont, setSelectedTextColor, setSelectable, setSelected on QCPAbstractLegendItem - selectedLegends on QCustomPlot - Interaction system for title: - setSelectedTitleFont, setSelectedTitleColor, setTitleSelected on QCustomPlot - new signals in accordance with the interaction system: - selectionChangedByUser on QCustomPlot - selectionChanged on QCPAbstractPlottable - selectionChanged on QCPAxis - selectionChanged on QCPLegend and QCPAbstractLegendItem - plottableClick, legendClick, axisClick, titleClick, plottableDoubleClick, legendDoubleClick, axisDoubleClick, titleDoubleClick on QCustomPlot - QCustomPlot::deselectAll (deselects everything, i.e. axes and plottables) - QCPAbstractPlottable::pixelsToCoords (inverse function to the already existing coordsToPixels function) - QCPRange::contains(double value) - QCPAxis::setLabelColor and setTickLabelColor - QCustomPlot::setTitleColor - QCustomPlot now emits beforeReplot and afterReplot signals. Note that it is safe to make two customPlots mutually call eachothers replot functions in one of these slots, it will not cause an infinite loop. (usefull for synchronizing axes ranges between two customPlots, because setRange alone doesn't replot) - If the Qt version is 4.7 or greater, the tick label strings in date-time-mode now support sub-second accuracy (e.g. with format like "hh:mm:ss.zzz"). Bugfixes: - tick labels/margins should no longer oscillate by one pixel when dragging range or replotting repeatedly while changing e.g. data. This was caused by a bug in Qt's QFontMetrics::boundingRect function when the font has an integer point size (probably some rounding problem). The fix hence consists of creating a temporary font (only for bounding-box calculation) which is 0.05pt larger and thus avoiding the jittering rounding outcome. - tick label, axis label and plot title colors used to be undefined. This was fixed by providing explicit color properties. Other: - fixed some glitches in the documentation - QCustomPlot::replot and QCustomPlot::rescaleAxes are now slots #### Version released on 02.02.12 #### Changes that break backward compatibility: - renamed all secondary classes from QCustomPlot[...] to QCP[...]: QCustomPlotAxis -> QCPAxis QCustomPlotGraph -> QCPGraph QCustomPlotRange -> QCPRange QCustomPlotData -> QCPData QCustomPlotDataMap -> QCPDataMap QCustomPlotLegend -> QCPLegend QCustomPlotDataMapIterator -> QCPDataMapIterator QCustomPlotDataMutableMapIterator -> QCPDataMutableMapIterator A simple search and replace on all code files should make your code run again, e.g. consider the regex "QCustomPlot(?=[AGRDL])" -> "QCP". Make sure not to just replace "QCustomPlot" with "QCP" because the main class QCustomPlot hasn't changed to QCP. This change was necessary because class names became unhandy, pardon my bad naming decision in the beginning. - QCPAxis::tickLength() and QCPAxis::subTickLength() now each split into two functions for inward and outward ticks (tickLengthIn/tickLengthOut). - QCPLegend now uses QCPAbstractLegendItem to carry item data (before, the legend was passed QCPGraphs directly) - QCustomPlot::addGraph() now doesn't return the index of the created graph anymore, but a pointer to the created QCPGraph. - QCustomPlot::setAutoAddGraphToLegend is replaced by setAutoAddPlottableToLegend Added features: - Reversed axis range with QCPAxis::setRangeReversed(bool) - Tick labels are now only drawn if not clipped by the viewport (widget border) on the sides (e.g. left and right on a horizontal axis). - Zerolines. Like grid lines only with a separate pen (QCPAxis::setZeroLinePen), at tick position zero. - Outward ticks. QCPAxis::setTickLength/setSubTickLength now accepts two arguments for inward and outward tick length. This doesn't break backward compatibility because the second argument (outward) has default value zero and thereby a call with one argument hasn't changed its meaning. - QCPGraph now inherits from QCPAbstractPlottable - QCustomPlot::addPlottable/plottable/removePlottable/clearPlottables added to interface with the new QCPAbstractPlottable-based system. The simpler interface which only acts on QCPGraphs (addGraph, graph, removeGraph, etc.) was adapted internally and is kept for backward compatibility and ease of use. - QCPLegend items for plottables (e.g. graphs) can automatically wrap their texts to fit the widths, see QCPLegend::setMinimumSize and QCPPlottableLegendItem::setTextWrap. - QCustomPlot::rescaleAxes. Adapts axis ranges to show all plottables/graphs, by calling QCPAbstractPlottable::rescaleAxes on all plottables in the plot. - QCPCurve. For plotting of parametric curves. - QCPBars. For plotting of bar charts. - QCPStatisticalBox. For statistical box plots. Bugfixes: - Fixed QCustomPlot::removeGraph(int) not being able to remove graph index 0 - made QCustomPlot::replot() abort painting when painter initialization fails (e.g. because width/height of QCustomPlot is zero) - The distance of the axis label from the axis ignored the tick label padding, this could have caused overlapping axis labels and tick labels - fixed memory leak in QCustomPlot (dtor didn't delete legend) - fixed bug that prevented QCPAxis::setRangeLower/Upper from setting the value to exactly 0. Other: - Changed default error bar handle size (QCustomPlotGraph::setErrorBarSize) from 4 to 6. - Removed QCustomPlotDataFetcher. Was deprecated and not used class. - Extended documentation, especially class descriptions. #### Version released on 15.01.12 #### Changes that (might) break backward compatibility: - QCustomPlotGraph now inherits from QObject Added features: - Added axis background pixmap (QCustomPlot::setAxisBackground, setAxisBackgroundScaled, setAxisBackgroundScaledMode) - Added width and height parameter on PDF export function QCustomPlot::savePdf(). This now allows PDF export to have arbitrary dimensions, independent of the current geometry of the QCustomPlot. - Added overload of QCustomPlot::removeGraph that takes QCustomPlotGraph* as parameter, instead the index of the graph - Added all enums to the Qt meta system via Q_ENUMS(). The enums can now be transformed to QString values easily with the Qt meta system, which makes saving state e.g. as XML significantly nicer. - added typedef QMapIterator QCustomPlotDataMapIterator and typedef QMutableMapIterator QCustomPlotDataMutableMapIterator for improved information hiding, when using iterators outside QCustomPlot code Bugfixes: - Fixed savePngScaled. Axis/label drawing functions used to reset the painter transform and thereby break savePngScaled. Now they buffer the current transform and restore it afterwards. - Fixed some glitches in the doxygen comments (affects documentation only) Other: - Changed the default tickLabelPadding of top axis from 3 to 6 pixels. Looks better. - Changed the default QCustomPlot::setAntialiasedElements setting: Graph fills are now antialiased by default. That's a bit slower, but makes fill borders look better. #### Version released on 19.11.11 #### Changes that break backward compatibility: - QCustomPlotAxis: tickFont and setTickFont renamed to tickLabelFont and setTickLabelFont (for naming consistency) Other: - QCustomPlotAxis: Added rotated tick labels, see setTickLabelRotation thermald-1.5/tools/thermal_monitor/logdialog.ui0000664000175000017500000000472612661205366020506 0ustar kingking LogDialog 0 0 400 300 Log 30 240 341 32 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok 50 40 91 27 Enable 50 90 113 29 170 90 67 21 Filename 160 40 131 27 Log visible only buttonBox accepted() LogDialog accept() 248 254 157 274 buttonBox rejected() LogDialog reject() 316 260 286 274 thermald-1.5/tools/thermal_monitor/tripsdialog.ui0000664000175000017500000000510512661205366021056 0ustar kingking tripsDialog 0 0 400 300 Temperature Trips 0 0 Qt::Vertical QDialogButtonBox::Cancel|QDialogButtonBox::Ok TextLabel TextLabel Zone Trip Type Display buttonBox accepted() tripsDialog accept() 248 254 157 274 buttonBox rejected() tripsDialog reject() 316 260 286 274 thermald-1.5/tools/thermal_monitor/thermaldinterface.h0000664000175000017500000000606712661205366022040 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #ifndef THERMALDINTERFACE_H #define THERMALDINTERFACE_H #include #include #define SERVICE_NAME "org.freedesktop.thermald" #define MAX_TEMP_INPUT_COUNT 64 #define CRITICAL_TRIP 0 #define MAX_TRIP 1 #define PASSIVE_TRIP 2 #define ACTIVE_TRIP 3 #define POLLING_TRIP 4 #define INVALID_TRIP 5 typedef struct { QString name; int min_state; int max_state; int current_state; } coolingDeviceInformationType; typedef struct { QString name; QString path; int temperature; } sensorInformationType; typedef struct { int temp; int trip_type; bool visible; int sensor_id; int cdev_size; QList cdev_ids; // Not currently using } tripInformationType; typedef struct { QString name; uint sensor_count; uint trip_count; QVector trips; uint lowest_valid_index; } zoneInformationType; class ThermaldInterface { public: ThermaldInterface(); ~ThermaldInterface(); int initialize(); uint getCoolingDeviceCount(); QString getCoolingDeviceName(uint index); int getCoolingDeviceMinState(uint index); int getCoolingDeviceMaxState(uint index); int getCoolingDeviceCurrentState(uint index); uint getSensorCount(); QString getSensorName(uint index); QString getSensorPath(uint index); int getSensorTemperature(uint index); int getSensorIndex(QString sensor_type); int getSensorCountForZone(uint zone); int getSensorTypeForZone(uint zone, uint index, QString &sensor_type); int getLowestValidTripTempForZone(uint zone); int getTripCountForZone(uint zone); int getTripTempForZone(uint zone, uint trip); int getTripTypeForZone(uint zone, uint trip); zoneInformationType* getZone(uint zone); uint getZoneCount(); QString getZoneName(uint zone); int setTripTempForZone(uint zone, uint trip, int temperature); bool tripVisibility(uint zone, uint trip); void setTripVisibility(uint zone, uint trip, bool visibility); private: QDBusInterface *iface; QVector cooling_devices; QVector sensors; QVector zones; int getCoolingDeviceInformation(uint index, coolingDeviceInformationType &info); int getSensorInformation(uint index, sensorInformationType &info); int getTripInformation(uint zone_index, uint trip_index, tripInformationType &info); int getZoneInformation(uint index, zoneInformationType &info); }; #endif thermald-1.5/tools/thermal_monitor/mainwindow.h0000664000175000017500000000537612661205366020535 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include #include #include #include #include "qcustomplot/qcustomplot.h" #include "thermaldinterface.h" namespace Ui { class MainWindow; } typedef struct { QString display_name; QString sensor_name; int index; int zone; } sensorZoneInformationType; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void displayTemperature(QCustomPlot *customPlot); int addNewTemperatureTemperatureSample(int index, double temperature); bool getVisibleState(int index); protected: virtual void closeEvent(QCloseEvent *event); public slots: void currentChangedSlot(int index); void changePollIntervalSlot(uint new_val); void changeGraphVisibilitySlot(uint index, bool visible); void changeLogVariables(bool log_enabled, bool log_vis_only, QString log_file_name); void setTripSetpoint(uint zone, uint trip, int temperature); void setTripVisibility(uint zone, uint trip, bool visibility); private slots: void updateTemperatureDataSlot(); void on_actionClear_triggered(); void on_actionSet_Polling_Interval_triggered(); void on_actionSensors_triggered(); void on_actionLog_triggered(); void on_action_About_triggered(); void on_actionE_xit_triggered(); void on_action_Trips_triggered(); private: Ui::MainWindow *ui; QTimer tempUpdateTimer; QVector colors; QVector temp_samples; int currentTempsensorIndex; QVector temperature_samples[MAX_TEMP_INPUT_COUNT]; int current_sample_index[MAX_TEMP_INPUT_COUNT]; uint temp_poll_interval; bool *sensor_visibility; // QLabel *sensor_label; QLabel *sensor_temp; QVector > trips; QVectorsensor_types; QVBoxLayout *layout; QWidget *window; ThermaldInterface thermaldInterface; bool logging_enabled; bool log_visible_only; QString log_filename; QFile logging_file; QTextStream outStreamLogging; void resoreSettings(); void storeSettings(); }; #endif // MAINWINDOW_H thermald-1.5/tools/thermal_monitor/sensorsdialog.ui0000664000175000017500000002133512661205366021414 0ustar kingking SensorsDialog 0 0 400 619 Sensors 290 20 81 241 Qt::Vertical QDialogButtonBox::Cancel|QDialogButtonBox::Ok 20 10 131 27 CheckBox true 20 40 131 27 CheckBox true 20 70 131 27 CheckBox true 20 100 131 27 CheckBox true 20 130 131 27 CheckBox true 20 160 131 27 CheckBox true 20 190 131 27 CheckBox true 20 220 131 27 CheckBox true 20 250 131 27 CheckBox true 20 280 131 27 CheckBox true 20 310 131 27 CheckBox true 20 340 131 27 CheckBox true 20 370 131 27 CheckBox true 160 20 85 29 Set All 160 60 85 29 Clear All 20 400 131 27 CheckBox true 20 430 131 27 CheckBox true 20 460 131 27 CheckBox true 20 490 131 27 CheckBox true 20 520 131 27 CheckBox true 20 550 131 27 CheckBox true 20 580 131 27 CheckBox true buttonBox accepted() SensorsDialog accept() 248 254 157 274 buttonBox rejected() SensorsDialog reject() 316 260 286 274 thermald-1.5/tools/thermal_monitor/ThermalMonitor.pro0000664000175000017500000000137212661205366021666 0ustar kingking#------------------------------------------------- # # Project created by QtCreator 2015-05-13T11:28:27 # #------------------------------------------------- QT += core gui dbus greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport TARGET = ThermalMonitor TEMPLATE = app SOURCES += main.cpp\ mainwindow.cpp \ qcustomplot/qcustomplot.cpp \ thermaldinterface.cpp \ pollingdialog.cpp \ sensorsdialog.cpp \ logdialog.cpp \ tripsdialog.cpp HEADERS += mainwindow.h \ qcustomplot/qcustomplot.h \ thermaldinterface.h \ pollingdialog.h \ sensorsdialog.h \ logdialog.h \ tripsdialog.h FORMS += mainwindow.ui \ pollingdialog.ui \ sensorsdialog.ui \ logdialog.ui \ tripsdialog.ui thermald-1.5/tools/thermal_monitor/main.cpp0000664000175000017500000000325412661205366017631 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #include #include "mainwindow.h" #include #define ROOT_ID 0 int main(int argc, char *argv[]) { QApplication a(argc, argv); // Warn the user if not running as root uid_t id = getuid(); if (id != ROOT_ID){ QMessageBox msgBox; QString str; str = QString("%1 requires root privilages to access the thermal daemon. " "Try invoking again with root privileges.\n") .arg(QCoreApplication::applicationName()); msgBox.setText(str); msgBox.setStandardButtons(QMessageBox::Abort); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Abort: // Abort was clicked return(1); break; default: // should never be reached qFatal("main: unexpected button result"); break; } } QCoreApplication::setOrganizationDomain("intel.com"); QCoreApplication::setOrganizationName("Intel"); QCoreApplication::setApplicationName("ThermalMonitor"); MainWindow w; w.show(); return a.exec(); } thermald-1.5/tools/thermal_monitor/pollingdialog.ui0000664000175000017500000000471012661205366021362 0ustar kingking PollingDialog 0 0 345 187 Set Polling Interval -50 150 341 32 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok 50 60 261 21 TextLabel 50 90 113 29 170 100 67 21 ms 210 90 85 29 Set buttonBox accepted() PollingDialog accept() 248 254 157 274 buttonBox rejected() PollingDialog reject() 316 260 286 274 thermald-1.5/tools/thermal_monitor/logdialog.h0000664000175000017500000000220512661205366020306 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #ifndef LOGDIALOG_H #define LOGDIALOG_H #include namespace Ui { class LogDialog; } class LogDialog : public QDialog { Q_OBJECT public: explicit LogDialog(QWidget *parent = 0); ~LogDialog(); void setLoggingState(bool logging, bool visible_only, QString filename); signals: void setLogVariable(bool logging_enabled, bool log_visible_only, QString log_file_name); private slots: void on_checkBoxLogging_toggled(bool checked); void on_buttonBox_accepted(); private: Ui::LogDialog *ui; }; #endif // LOGDIALOG_H thermald-1.5/tools/thermal_monitor/tripsdialog.h0000664000175000017500000000206712661205366020674 0ustar kingking#ifndef TRIPSDIALOG_H #define TRIPSDIALOG_H #include #include "thermaldinterface.h" #include "ui_tripsdialog.h" namespace Ui { class tripsDialog; } class tripsDialog : public QDialog { Q_OBJECT public: explicit tripsDialog(QWidget *parent = 0, ThermaldInterface *therm = 0); ~tripsDialog(); void addZone(zoneInformationType *zone); signals: void changeTripSetpoint(uint zone, uint trip, int temperature); void setTripVis(uint zone, uint trip, bool visibility); private slots: void on_treeWidget_clicked(const QModelIndex &index); void on_treeWidget_doubleClicked(const QModelIndex &index); void on_buttonBox_accepted(); void on_buttonBox_rejected(); void on_treeWidget_expanded(); void on_treeWidget_collapsed(); void on_lineEdit_editingFinished(); private: Ui::tripsDialog *ui; ThermaldInterface *thermal; QTreeWidgetItem *last_item; uint last_trip; uint last_zone; void resizeColumns(); void setRowHighlighting(QTreeWidgetItem *item, bool visible); }; #endif // TRIPSDIALOG_H thermald-1.5/tools/thermal_monitor/logdialog.cpp0000664000175000017500000000335612661205366020651 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #include "logdialog.h" #include "ui_logdialog.h" #include #include LogDialog::LogDialog(QWidget *parent) : QDialog(parent), ui(new Ui::LogDialog) { ui->setupUi(this); } LogDialog::~LogDialog() { delete ui; } void LogDialog::setLoggingState(bool logging, bool visible_only, QString filename) { ui->checkBoxLogging->setChecked(logging); ui->checkBoxLogVisibleOnly->setChecked(visible_only); ui->lineEditLogFilename->setText(filename); // disable inputs if logging is not enabled on_checkBoxLogging_toggled(ui->checkBoxLogging->checkState()); } void LogDialog::on_checkBoxLogging_toggled(bool checked) { if (checked) { ui->checkBoxLogVisibleOnly->setEnabled(true); ui->lineEditLogFilename->setEnabled(true); } else { ui->checkBoxLogVisibleOnly->setEnabled(false); ui->lineEditLogFilename->setEnabled(false); } } void LogDialog::on_buttonBox_accepted() { // send signal to mainwindow with logging status emit setLogVariable(ui->checkBoxLogging->checkState(), ui->checkBoxLogVisibleOnly->checkState(), ui->lineEditLogFilename->text()); } thermald-1.5/tools/thermal_monitor/sensorsdialog.h0000664000175000017500000000427212661205366021227 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #ifndef SENSORSDIALOG_H #define SENSORSDIALOG_H #include #include #define MAX_NUMBER_SENSOR_VISIBILITY_CHECKBOXES 20 namespace Ui { class SensorsDialog; } class SensorsDialog : public QDialog { Q_OBJECT public: explicit SensorsDialog(QWidget *parent = 0); ~SensorsDialog(); void disableCheckbox(int index); void setupCheckbox(int index, QString name, bool checked); signals: void setGraphVisibility(uint, bool); private slots: void on_checkBox_toggled(bool checked); void on_checkBox_2_toggled(bool checked); void on_checkBox_3_toggled(bool checked); void on_checkBox_4_toggled(bool checked); void on_checkBox_5_toggled(bool checked); void on_checkBox_6_toggled(bool checked); void on_checkBox_7_toggled(bool checked); void on_checkBox_8_toggled(bool checked); void on_checkBox_9_toggled(bool checked); void on_checkBox_10_toggled(bool checked); void on_checkBox_11_toggled(bool checked); void on_checkBox_12_toggled(bool checked); void on_checkBox_13_toggled(bool checked); void on_checkBox_14_toggled(bool checked); void on_checkBox_15_toggled(bool checked); void on_checkBox_16_toggled(bool checked); void on_checkBox_17_toggled(bool checked); void on_checkBox_18_toggled(bool checked); void on_checkBox_19_toggled(bool checked); void on_checkBox_20_toggled(bool checked); void on_setAllButton_clicked(); void on_clearAllButton_clicked(); private: Ui::SensorsDialog *ui; //QCheckBox *checkbox; QVector checkbox; QCheckBox* getCheckboxPtr(int index); }; #endif // SENSORSDIALOG_H thermald-1.5/tools/thermal_monitor/tripsdialog.cpp0000664000175000017500000001332512661205366021226 0ustar kingking#include "tripsdialog.h" #include "ui_tripsdialog.h" tripsDialog::tripsDialog(QWidget *parent, ThermaldInterface *therm) : QDialog(parent), ui(new Ui::tripsDialog) { thermal = therm; ui->setupUi(this); ui->label->setText(""); ui->label_2->setText(""); ui->lineEdit->setEnabled(false); ui->lineEdit->setValidator(new QIntValidator); } tripsDialog::~tripsDialog() { delete ui; } void tripsDialog::addZone(zoneInformationType *zone) { QTreeWidgetItem *treeItem = new QTreeWidgetItem(ui->treeWidget); treeItem->setText(0, zone->name); for(uint i = 0; i < (uint)zone->trips.count(); i++){ QTreeWidgetItem *treeTripItem = new QTreeWidgetItem(treeItem); treeTripItem->setData(1, Qt::DisplayRole, zone->trips[i].temp); treeTripItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); QString str; switch(zone->trips[i].trip_type){ case CRITICAL_TRIP: str = "Critical"; break; case MAX_TRIP: str = "Max"; break; case PASSIVE_TRIP: str = "Passive"; break; case ACTIVE_TRIP: str = "Active"; break; case POLLING_TRIP: str = "Polling"; break; case INVALID_TRIP: str = "Invalid"; break; default: qCritical() << "tripsDialog::addZone" << "invalid trip type: " << zone->trips[i].trip_type; str = "I'm losing my mind Dave"; } treeTripItem->setText(2, str); setRowHighlighting(treeTripItem, zone->trips[i].visible); } // Sorting by temperature looks better, but we would have to track the trip index // treeItem->sortChildren(1, Qt::AscendingOrder); ui->treeWidget->setToolTip("Click on temperature to change.\n" "Double click to display or clear."); resizeColumns(); } void tripsDialog::resizeColumns() { for (int i = 0; i < ui->treeWidget->columnCount(); i++){ ui->treeWidget->resizeColumnToContents(i); } } void tripsDialog::setRowHighlighting(QTreeWidgetItem *item, bool visible) { if (visible){ item->setForeground(1, Qt::white); item->setBackground(1, Qt::black); item->setForeground(2, Qt::white); item->setBackground(2, Qt::black); item->setForeground(3, Qt::white); item->setBackground(3, Qt::black); item->setText(3, "Yes"); } else { item->setForeground(1, Qt::black); item->setBackground(1, Qt::white); item->setForeground(2, Qt::black); item->setBackground(2, Qt::white); item->setForeground(3, Qt::black); item->setBackground(3, Qt::white); item->setText(3, ""); } } void tripsDialog::on_treeWidget_clicked(const QModelIndex &index) { int zone; int trip; int col; // check to see if the user clicked on a zone root node if(index.parent().column() == -1){ zone = index.row(); col = index.column(); trip = -1; } else { // otherwise the user clicked on a trip zone = index.parent().row(); col = index.column(); trip = index.row(); } // Alternate the background color, black to display on the graph, white to ignore if (trip != -1 && col == 1){ // if the user clicks on a temperature ui->label->setText("Zone: " + index.parent().data().toString()); ui->label_2->setText("Type: " + index.parent().child(trip, col + 1).data().toString() + " (°C)"); ui->lineEdit->setText(index.data().toString()); // ACTIVE_TRIP modification not supported at this time if (thermal->getTripTypeForZone(zone, trip) == MAX_TRIP || thermal->getTripTypeForZone(zone, trip) == PASSIVE_TRIP){ ui->lineEdit->setEnabled(true); // store the zone and trip in case the user edits the trip temperature last_zone = zone; last_trip = trip; last_item = ui->treeWidget->currentItem(); } else { ui->lineEdit->setEnabled(false); } } else { ui->label->setText("Click on"); ui->label_2->setText("temperature"); ui->lineEdit->setText(""); ui->lineEdit->setEnabled(false); } resizeColumns(); } void tripsDialog::on_treeWidget_doubleClicked(const QModelIndex &index) { int zone; int trip; // check to see if the user clicked on a zone root node if(index.parent().column() == -1){ zone = index.row(); } else { // otherwise the user clicked on a trip zone = index.parent().row(); trip = index.row(); // Invert the fore and background colors to display trip on the graph // Look at column 1, the trip temperature, to determine the outcome if (ui->treeWidget->currentItem()->foreground(1).color() == Qt::black){ setRowHighlighting(ui->treeWidget->currentItem(), true); emit setTripVis(zone, trip, true); } else { setRowHighlighting(ui->treeWidget->currentItem(), false); emit setTripVis(zone, trip, false); } } resizeColumns(); } void tripsDialog::on_buttonBox_accepted() { } void tripsDialog::on_buttonBox_rejected() { } void tripsDialog::on_treeWidget_expanded() { resizeColumns(); } void tripsDialog::on_treeWidget_collapsed() { resizeColumns(); } void tripsDialog::on_lineEdit_editingFinished() { last_item->setText(1, ui->lineEdit->text()); if (ui->lineEdit->text().toInt() != thermal->getTripTempForZone(last_zone, last_trip)){ emit changeTripSetpoint(last_zone, last_trip, ui->lineEdit->text().toInt()); } } thermald-1.5/tools/thermal_monitor/thermaldinterface.cpp0000664000175000017500000004347412661205366022376 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #include #include #include "thermaldinterface.h" #include "tripsdialog.h" ThermaldInterface::ThermaldInterface() : iface(NULL) { } ThermaldInterface::~ThermaldInterface() { delete iface; } int ThermaldInterface::initialize() { /* Create the D-Bus interface * Get the temperature sensor count and information from each sensor * Get the cooling device count and information from each device */ if (!QDBusConnection::systemBus().isConnected()) { qCritical() << "Cannot connect to the D-Bus session bus"; return -1; } iface = new QDBusInterface(SERVICE_NAME, "/org/freedesktop/thermald", "org.freedesktop.thermald", QDBusConnection::systemBus()); if (!iface->isValid()) { qCritical() << "Cannot connect to interface" << SERVICE_NAME; return -1; } // get temperature sensor count uint sensor_count; QDBusReply count = iface->call("GetSensorCount"); if (count.isValid()) { if (count <= MAX_TEMP_INPUT_COUNT){ sensor_count = count; } else { qCritical() << "error: input sensor count of" << count << "is larger than system maximum (" << MAX_TEMP_INPUT_COUNT << ")"; return -1; } } else { qCritical() << "error from" << iface->interface() << "=" << count.error(); return -1; } // Read in all the the temperature sensor data from the thermal daemon for (uint i = 0; i < sensor_count; i++){ sensorInformationType new_sensor; if (getSensorInformation(i, new_sensor) >= 0){ sensors.append(new_sensor); } } if (sensor_count != (uint)sensors.count()){ qCritical() << "error: ThermaldInterface::getSensorCount() sensor_count != sensors.count())," << sensor_count << "vs" << sensors.count(); } // get cooling device count uint cooling_device_count; QDBusReply cdev_count = iface->call("GetCdevCount"); if (cdev_count.isValid()) { cooling_device_count = cdev_count; } else { qCritical() << "error from" << iface->interface() << "=" << cdev_count.error(); return -1; } // Read in all the the cooling device data from the thermal daemon for (uint i = 0; i < cooling_device_count; i++){ coolingDeviceInformationType new_device; if (getCoolingDeviceInformation(i, new_device) >= 0){ cooling_devices.append(new_device); } } if (cooling_device_count != (uint)cooling_devices.count()){ qCritical() << "error: ThermaldInterface::getCoolingDeviceCount()" << " cooling_device_count != cooling_devices.count()," << cooling_device_count << "vs" << cooling_devices.count(); } // get zone count uint zone_count; QDBusReply z_count = iface->call("GetZoneCount"); if (z_count.isValid()) { zone_count = z_count; } else { qCritical() << "error from" << iface->interface() << "=" << cdev_count.error(); return -1; } // Read in all the the zone data from the thermal daemon for (uint i = 0; i < zone_count; i++){ zoneInformationType new_zone; if (getZoneInformation(i, new_zone) >= 0){ zones.append(new_zone); } } if (zone_count != (uint)zones.count()){ qCritical() << "error: ThermaldInterface::getCoolingDeviceCount()" << " zone_count != zones.count()," << zone_count << "vs" << zones.count(); } // Read in all the the trip data from the thermal daemon for (uint i = 0; i < zone_count; i++){ uint lowest_valid_index = (uint)zones[i].trip_count; for (uint j = 0; j < (uint)zones[i].trip_count; j++){ tripInformationType new_trip; if (getTripInformation(i, j, new_trip) >= 0){ zones[i].trips.append(new_trip); // Figure out the lowest valid trip index if (new_trip.trip_type == CRITICAL_TRIP || new_trip.trip_type == PASSIVE_TRIP || new_trip.trip_type == ACTIVE_TRIP){ if (j < lowest_valid_index){ lowest_valid_index = j; } } } } // Store the actual number of trips, as opposed to the theoritical maximum zones[i].trip_count = zones[i].trips.count(); // Store the first valid trip temp for the zone if (lowest_valid_index < (uint)zones[i].trip_count){ zones[i].lowest_valid_index = lowest_valid_index; //trip_temps.append(zones[i].trips[lowest_valid_index].temp); } else { qCritical() << "error: ThermaldInterface::initialize()" << " could not find valid trip for zone" << i; } /* Yo! zones[i].trip_count is the theoretical count * but zones[i].trips.count() is the actual valid count * * So when you want the trip count for any given zone, * use zones[i].trips.count() */ } return 0; } uint ThermaldInterface::getCoolingDeviceCount(){ return cooling_devices.count(); } QString ThermaldInterface::getCoolingDeviceName(uint index) { if (index < (uint)cooling_devices.count()){ return cooling_devices[index].name; } else { qCritical() << "error: ThermaldInterface::getCoolingDeviceName" << "index" << index << "is >= than cooling_device.count" << cooling_devices.count(); return QString(""); } } int ThermaldInterface::getCoolingDeviceMinState(uint index) { if (index < (uint)cooling_devices.count()){ return cooling_devices[index].min_state; } else { qCritical() << "error: ThermaldInterface::getCoolingMinState" << "index" << index << "is >= than cooling_device.count" << cooling_devices.count(); return -1; } } int ThermaldInterface::getCoolingDeviceMaxState(uint index) { if (index < (uint)cooling_devices.count()){ return cooling_devices[index].max_state; } else { qCritical() << "error: ThermaldInterface::getCoolingMaxState" << "index" << index << "is >= than cooling_device.count" << cooling_devices.count(); return -1; } } int ThermaldInterface::getCoolingDeviceCurrentState(uint index) { if (index < (uint)cooling_devices.count()){ coolingDeviceInformationType cdev; // The state may have changed, so poll it again getCoolingDeviceInformation(index, cdev); cooling_devices[index].current_state = cdev.current_state; return cooling_devices[index].current_state; } else { qCritical() << "error: ThermaldInterface::getCoolingCurrentState" << "index" << index << "is >= than cooling_device.count" << cooling_devices.count(); return -1; } } int ThermaldInterface::getCoolingDeviceInformation(uint index, coolingDeviceInformationType &info) { QDBusMessage result; result = iface->call("GetCdevInformation", index); if (result.type() == QDBusMessage::ReplyMessage) { info.name = result.arguments().at(0).toString(); info.min_state = result.arguments().at(1).toInt(); info.max_state = result.arguments().at(2).toInt(); info.current_state = result.arguments().at(3).toInt(); return 0; } else { qCritical() << "error from" << iface->interface() << result.errorMessage(); return -1; } } uint ThermaldInterface::getSensorCount() { return sensors.count(); } int ThermaldInterface::getSensorInformation(uint index, sensorInformationType &info) { QDBusMessage result; result = iface->call("GetSensorInformation", index); if (result.type() == QDBusMessage::ReplyMessage) { info.name = result.arguments().at(0).toString(); info.path = result.arguments().at(1).toString(); info.temperature = result.arguments().at(2).toInt(); return 0; } else { qCritical() << "error from" << iface->interface() << result.errorMessage(); return -1; } } QString ThermaldInterface::getSensorName(uint index){ if (index < (uint)sensors.size()){ return sensors[index].name; } else { return QString(""); } } QString ThermaldInterface::getSensorPath(uint index){ if (index < (uint)sensors.size()){ return sensors[index].path; } else { return QString(""); } } int ThermaldInterface::getSensorTemperature(uint index) { QDBusReply temp = iface->call("GetSensorTemperature", index); if (temp.isValid()) { return temp; } else { qCritical() << "error from" << iface->interface() << "=" << temp.error(); return -1; } } int ThermaldInterface::getTripInformation(uint zone_index, uint trip_index, tripInformationType &info) { QDBusMessage result; result = iface->call("GetZoneTripAtIndex", zone_index, trip_index); if (result.type() == QDBusMessage::ReplyMessage) { info.temp = result.arguments().at(0).toInt() / 1000; info.trip_type = result.arguments().at(1).toInt(); info.sensor_id = result.arguments().at(2).toInt(); info.cdev_size = result.arguments().at(3).toInt(); // info.cdev_ids = result.arguments().at(4).toList(); return 0; } else if (result.signature().isEmpty()){ // If we get and empty response, then ignore it, but return error code return -1; } else { qCritical() << "error from" << iface->interface() << result.errorMessage() << zone_index << trip_index; return -1; } } int ThermaldInterface::getLowestValidTripTempForZone(uint zone) { if (zone < (uint)zones.count()){ return zones[zone].trips[zones[zone].lowest_valid_index].temp; } else { qCritical() << "error: ThermaldInterface::getLowestValidTripTempForZone" << "zone index" << zone << "is >= than zone count" << zones.count(); return -1; } } int ThermaldInterface::getSensorCountForZone(uint zone) { if (zone < (uint)zones.count()){ return (uint)zones[zone].sensor_count; } else { qCritical() << "error: ThermaldInterface::getSensorCountForZone" << "zone index" << zone << "is >= than zone count" << zones.count(); return -1; } } int ThermaldInterface::getSensorTypeForZone(uint zone, uint index, QString &sensor_type) { QDBusMessage result; result = iface->call("GetZoneSensorAtIndex", zone, index); if (result.type() == QDBusMessage::ReplyMessage) { sensor_type = result.arguments().at(0).toString(); return 0; } else { qCritical() << "error from" << iface->interface() << result.errorMessage(); return -1; } } int ThermaldInterface::getSensorIndex(QString sensor_type) { for (uint i = 0; i < (uint)sensors.count(); i++){ if(sensor_type == sensors[i].name) return (int)i; } return -1; } int ThermaldInterface::getTripCountForZone(uint zone) { /* Yo! zones[i].trip_count is the theoretical count * but zones[i].trips.count() is the actual valid count * * So when you want the trip count for any given zone, * use zones[i].trips.count() */ if (zone < (uint)zones.count()){ return (uint)zones[zone].trips.count(); } else { qCritical() << "error: ThermaldInterface::getTripCountForZone" << "zone index" << zone << "is >= than zone count" << zones.count(); return -1; } } int ThermaldInterface::getTripTempForZone(uint zone, uint trip) { if (zone < (uint)zones.count()){ if (trip < zones[zone].trip_count){ return zones[zone].trips[trip].temp; } else { qCritical() << "error: ThermaldInterface::getTripTempForZone" << "trip index" << trip << "is >= than trip count" << zones[zone].trip_count; return -1; } } else { qCritical() << "error: ThermaldInterface::getTripTempForZone" << "zone index" << zone << "is >= than zone count" << zones.count(); return -1; } } int ThermaldInterface::getTripTypeForZone(uint zone, uint trip) { if (zone < (uint)zones.count()){ if (trip < zones[zone].trip_count){ return zones[zone].trips[trip].trip_type; } else { qCritical() << "error: ThermaldInterface::getTripTypeForZone" << "trip index" << trip << "is >= than trip count" << zones[zone].trip_count; return -1; } } else { qCritical() << "error: ThermaldInterface::getTripTypeForZone" << "zone index" << zone << "is >= than zone count" << zones.count(); return -1; } } zoneInformationType* ThermaldInterface::getZone(uint zone) { if (zone < (uint)zones.count()){ return &zones[zone]; } else { qCritical() << "error: ThermaldInterface::getZone" << "zone index" << zone << "is >= than zone count" << zones.count(); return NULL; } } uint ThermaldInterface::getZoneCount() { return (uint)zones.count(); } QString ThermaldInterface::getZoneName(uint zone) { if (zone < (uint)zones.count()){ return zones[zone].name; } else { qCritical() << "error: ThermaldInterface::getZoneName" << "zone index" << zone << "is >= than zone count" << zones.count(); return QString(""); } } int ThermaldInterface::getZoneInformation(uint index, zoneInformationType &info) { QDBusMessage result; result = iface->call("GetZoneInformation", index); if (result.type() == QDBusMessage::ReplyMessage) { info.name = result.arguments().at(0).toString(); info.sensor_count = result.arguments().at(1).toInt(); info.trip_count = result.arguments().at(2).toInt(); return 0; } else { qCritical() << "error from" << iface->interface() << result.errorMessage(); return -1; } } int ThermaldInterface::setTripTempForZone(uint zone, uint trip, int temperature) { if (zone < (uint)zones.count()){ if (trip < zones[zone].trip_count){ zones[zone].trips[trip].temp = temperature; // tell thermald to change the temperature for max and passive if (zones[zone].trips[trip].trip_type == MAX_TRIP){ iface->call("SetUserMaxTemperature", zones[zone].name, (uint)(temperature * 1000)); return 0; } else if (zones[zone].trips[trip].trip_type == PASSIVE_TRIP){ iface->call("SetUserPassiveTemperature", zones[zone].name, (uint)(temperature * 1000)); // Call reinit from thermald in order to get the change to stick iface->call("Reinit"); return 0; } else { qCritical() << "error: ThermaldInterface::setTripTempForZone" << "trip type is not 'max' or 'passive'" << "zone" << zone << "trip" << trip; return -1; } } else { qCritical() << "error: ThermaldInterface::setTripTempForZone" << "trip index" << trip << "is >= than trip count" << zones[zone].trip_count; return -1; } } else { qCritical() << "error: ThermaldInterface::setTripTempForZone" << "zone index" << zone << "is >= than zone count" << zones.count(); return -1; } } void ThermaldInterface::setTripVisibility(uint zone, uint trip, bool visibility) { if (zone < (uint)zones.count()){ if (trip < zones[zone].trip_count){ zones[zone].trips[trip].visible = visibility; } else { qCritical() << "error: ThermaldInterface::setTripVisibility" << "trip index" << trip << "is >= than trip count" << zones[zone].trip_count; } } else { qCritical() << "error: ThermaldInterface::setTripVisibility" << "zone index" << zone << "is >= than zone count" << zones.count(); } } bool ThermaldInterface::tripVisibility(uint zone, uint trip) { if (zone < (uint)zones.count()){ if (trip < zones[zone].trip_count){ return zones[zone].trips[trip].visible; } else { qCritical() << "error: ThermaldInterface::tripVisibility" << "trip index" << trip << "is >= than trip count" << zones[zone].trip_count; return false; } } else { qCritical() << "error: ThermaldInterface::tripVisibility" << "zone index" << zone << "is >= than zone count" << zones.count(); return false; } } thermald-1.5/tools/thermal_monitor/README0000664000175000017500000000464312661205366017064 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ Compatibility with thermald -------------------------------------------- This tool requires thermald version "1.4.3" or later. Building the Thermal Monitor with Qt Creator -------------------------------------------- The project uses Qt 5 for the graphical user interface portion of the thermal monitor. A normal distribution of Qt includes Qt Creator, the IDE used for editing the forms and code. Using Creator Qt is the easiest way to build the project. Open Qt Creator, click File->Open File or Project, browse the project files to open ThermalMonitor.pro. The project files are displayed on the left side under Headers, Sources, and Forms. Build the project by clicking Build->Build Project (or Ctrl-b). A solid green status bar in the lower right corner indicates a successful build. Running the project ------------------- Note: you cannot run the project from within Qt Creator due to the root access necessary to interface with the thermal daemon (thermald). Instead, locate the Qt build directory, which should be in ../build-ThermalMonitor-BUILD_TYPE, where BUILD_TYPE describes the build, such as Desktop_Qt_5_4_2_GCC_64bit-Debug. Run the project as root from the build directory: sudo ./ThermalMonitor Building the Thermal Monitor with make -------------------------------------- Normally Qt Creator handles the compilation of the project. If you wish to use the command line to compile, then you first have to create a makefile. Qmake will create the makefile for you based on the project file. Qmake resided in /opt/Qt/5.4/gcc_64/bin on our system. Invoke with: qmake ThermalMonitor.pro After the makefile has been created, use 'make' to build the project. The object files and executable will be in the same directory as the source code, a different location than when using Qt Creator. Use 'make clean' to clean up everything except the executable. thermald-1.5/tools/thermal_monitor/pollingdialog.h0000664000175000017500000000204612661205366021174 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #ifndef POLLINGDIALOG_H #define POLLINGDIALOG_H #include namespace Ui { class PollingDialog; } class PollingDialog : public QDialog { Q_OBJECT public: explicit PollingDialog(QWidget *parent, uint current_interval); ~PollingDialog(); signals: void setPollInterval(uint val); private slots: void on_lineEdit_returnPressed(); void on_setButton_clicked(); private: Ui::PollingDialog *ui; uint default_interval; }; #endif // POLLINGDIALOG_H thermald-1.5/tools/thermal_monitor/pollingdialog.cpp0000664000175000017500000000245412661205366021532 0ustar kingking/* * Thermal Monitor displays current temperature readings on a graph * Copyright (c) 2015, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 3 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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. */ #include "pollingdialog.h" #include "ui_pollingdialog.h" #include "mainwindow.h" PollingDialog::PollingDialog(QWidget *parent, uint current_interval) : QDialog(parent), ui(new Ui::PollingDialog), default_interval(current_interval) { ui->setupUi(this); ui->lineEdit->setValidator(new QIntValidator); ui->lineEdit->setText(QString("%1").arg(current_interval)); ui->label->setText("Set temperature polling interval (ms)"); ui->label_2->setText("ms"); } PollingDialog::~PollingDialog() { delete ui; } void PollingDialog::on_lineEdit_returnPressed() { emit setPollInterval(ui->lineEdit->text().toInt()); } void PollingDialog::on_setButton_clicked() { emit setPollInterval(ui->lineEdit->text().toInt()); } thermald-1.5/data/0000775000175000017500000000000012661205366012543 5ustar kingkingthermald-1.5/data/thermal-cpu-cdev-order.xml0000664000175000017500000000077412661205366017546 0ustar kingking rapl_controller intel_pstate intel_powerclamp cpufreq Processor thermald-1.5/data/org.freedesktop.thermald.service.in0000664000175000017500000000017512661205366021435 0ustar kingking[D-BUS Service] Name=org.freedesktop.thermald Exec=/bin/false User=root SystemdService=dbus-org.freedesktop.thermald.service thermald-1.5/data/org.freedesktop.thermald.conf0000664000175000017500000000164412661205366020317 0ustar kingking thermald-1.5/data/thermald.conf0000664000175000017500000000055012661205366015212 0ustar kingking# thermald - thermal daemon # Upstart configuration file # Manages platform thermals description "thermal daemon" start on runlevel [2345] and started dbus stop on stopping dbus # # don't respawn on error # normal exit 1 respawn # # consider something wrong if respawned 10 times in 1 minute # respawn limit 10 60 exec thermald --no-daemon --dbus-enable thermald-1.5/data/thermald.service.in0000664000175000017500000000037612661205366016340 0ustar kingking[Unit] Description=Thermal Daemon Service [Service] Type=dbus SuccessExitStatus=1 BusName=org.freedesktop.thermald ExecStart=@sbindir@/thermald --no-daemon --dbus-enable [Install] WantedBy=multi-user.target Alias=dbus-org.freedesktop.thermald.service thermald-1.5/data/Makefile.am0000664000175000017500000000172312661205366014602 0ustar kingkinginclude $(GLIB_MAKEFILE) if HAVE_SYSTEMD systemdsystemunit_DATA = \ thermald.service thermald.service: thermald.service.in $(edit) $< >$@ servicedir = $(datadir)/dbus-1/system-services service_in_files = org.freedesktop.thermald.service.in service_DATA = $(service_in_files:.service.in=.service) $(service_DATA): $(service_in_files) Makefile $(edit) $< >$@ endif edit = sed \ -e 's|@bindir[@]|$(bindir)|g' \ -e 's|@sbindir[@]|$(sbindir)|g' \ -e 's|@sysconfdir[@]|$(sysconfdir)|g' \ -e 's|@localstatedir[@]|$(localstatedir)|g' dbusservicedir = $(DBUS_SYS_DIR) dbusservice_DATA = org.freedesktop.thermald.conf tdconfigdir = $(tdconfdir) tdconfig_DATA = thermal-conf.xml \ thermal-cpu-cdev-order.xml upstartconfdir = /etc/init upstartconf_DATA = thermald.conf EXTRA_DIST = \ thermald.service.in \ org.freedesktop.thermald.service.in \ $(dbusservice_DATA) \ $(tdconfig_DATA) \ $(upstartconf_DATA) CLEANFILES = thermald.service org.freedesktop.thermald.service thermald-1.5/data/thermal-conf.xml0000664000175000017500000001077512661205366015656 0ustar kingking Generic X86 Laptop Device EXAMPLE_SYSTEM QUIET TSKN 1 SKIN TSKN 55000 passive SEQUENTIAL 1 rapl_controller 100 16 2 intel_powerclamp 100 12 Example Platform Name Example UUID Example Product Name QUIET example_sensor_1 /some_path 0 example_thermal_sysfs_sensor 1 example_virtual_sensor 1 example_sensor_1 0.5 10 Example Zone type example_sensor_1 75000 max SEQUENTIAL 1 example_cooling_device 100 12 example_cooling_device 0 10 0 50 5000 > 0.001 0.0001 0.0001 thermald-1.5/misc/0000775000175000017500000000000012661205366012565 5ustar kingkingthermald-1.5/misc/valgrind.supp0000664000175000017500000000407712661205366015314 0ustar kingking# Valgrind suppressions file for glib, stl string calls { Syscall param write Memcheck:Param ... fun:g_main_loop_run fun:main } { g_type_init_with_debug_flags Memcheck:Leak ... fun:g_type_init_with_debug_flags fun:main } { g_main_loop_run Memcheck:Leak fun:memalign ... fun:g_main_loop_run fun:main } { c_plus_plus_string_hack Memcheck:Leak fun:_Znwm fun:_ZNSs?_Rep?_S_createEmmRKSaIcE fun:_ZNSs??_S_constructIPKcEEPcT_S?_RKSaIcESt??forward_iterator_tag fun:_ZNSsC?EPKcRKSaIcE fun:_ZN?cthd_msrC?Ev fun:_ZN??cthd_engine_dts??read_cooling_devicesEv fun:_ZN??cthd_engine??thd_engine_startEv fun:main } { c_plus_plus_string_hack Memcheck:Leak fun:_Znwm fun:_ZNSs4_Rep9_S_createEmmRKSaIcE fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag fun:_ZNSsC1EPKcRKSaIcE fun:_ZN8cthd_msrC1Ev fun:_ZN15cthd_engine_dts26check_intel_p_state_driverEv fun:_ZN15cthd_engine_dts20read_cooling_devicesEv fun:_ZN11cthd_engine16thd_engine_startEv fun:main } { c_plus_plus_string_hack Memcheck:Leak fun:_Znwm fun:_ZNSs?_Rep?_S_createEmmRKSaIcE fun:_ZNSs??_S_constructIPKcEEPcT_S?_RKSaIcESt??forward_iterator_tag fun:_ZNSsC?EPKcRKSaIcE fun:_ZN?cthd_msrC1Ev fun:_ZN??c_rapl_interfaceC?Ei fun:_ZN??cthd_engine_dts??read_cooling_devicesEv fun:_ZN??cthd_engine??thd_engine_startEv fun:main } { c_plus_plus_string_hack Memcheck:Leak fun:_Znwm fun:_ZNSs?_Rep?_S_createEmmRKSaIcE fun:_ZNSs??_S_constructIPKcEEPcT_S?_RKSaIcESt??forward_iterator_tag fun:_ZNSsC?EPKcRKSaIcE fun:_ZN?cthd_msrC?Ev fun:_ZN??cthd_engine_dts??check_intel_p_state_driverEv fun:_ZN??cthd_engine_dts??read_cooling_devicesEv fun:_ZN??cthd_engine??thd_engine_startEv fun:main } { c_plus_plus_string_hack Memcheck:Leak fun:_Znwm fun:_ZNSt?vectorIiSaIiEE??_M_insert_auxEN?__gnu_cxx??__normal_iteratorIPiS?_EERKi fun:_ZN??cthd_cdev_pstates?initEv fun:_ZN??cthd_engine_dts??read_cooling_devicesEv fun:_ZN??cthd_engine??thd_engine_startEv fun:main } thermald-1.5/man/0000775000175000017500000000000012661205366012405 5ustar kingkingthermald-1.5/man/thermal-conf.xml.50000664000175000017500000002765012661205366015663 0ustar kingking.\" thermal-conf.xml(5) manual page .\" .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual 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 Licence along .\" with this manual; if not, write to the Free Software Foundation, Inc., .\" 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. .\" .\" Copyright (C) 2012 Intel Corporation. All rights reserved. .\" .TH thermal-conf.xml "5" "11 Dec 2013" .SH NAME thermal-conf.xml \- Configuration file for thermal daemon .SH SYNOPSIS $(TDCONFDIR)/etc/thermald/thermal-conf.xml .SH DESCRIPTION .B thermal-conf.xml is a configuration file for the thermal daemon. It is used to configure thermal sensors, zone and cooling devices.The location of this file depends on the configuration option used during build time. .TP The terminology used in this file confirms to "Advanced Configuration and Power Interface Specification". The ACPI thermal model is based around conceptual platform regions called thermal zones that physically contain devices, thermal sensors, and cooling controls. For example of a thermal zone can be a CPU or a laptop cover. A zone can contain multiple sensors for monitoring temperature. A cooling device provides interface to reduce the temperature of a source device, which causes increase in the temperature. An example of a cooling device is a FAN or some Linux driver which can throttle the source device. .TP A thermal zone configuration includes one or more trip points. A trip point is a temperature at which a cooling device needs to be activated. .TP A cooling device can be either active or passive. An example of an active device is a FAN, which will not reduce performance at the cost of consuming more power and noise. A passive device uses performance throttling to control temperature. In addition to cooling devices present in the thermal sysfs, the following cooling devices are built into the thermald, which can be used as valid cooling device type: .TP - rapl_controller .TP - intel_pstate .TP - cpufreq .TP - LCD .TP The thermal sysfs under Linux (/sys/class/thermal) provides a way to represent per platform ACPI configuration. The kernel thermal governor uses this data to keep the platform thermals under control. But there are some limitations, which thermald tries to resolve. For example: .TP - If the ACPI data is not optimized or buggy. In this case thermal-conf.xml can be used to correct the behavior without change in BIOS. .TP - There may be thermal zones exposed by the thermal sysfs without associated cooling actions. In this case thermal conf.xml can be used to tie the cooling devices to those zones. .TP - The best cooling method may not be in the thermal sysfs. In this case thermal-conf.xml can be used to bind a zone to an external cooling device. .TP - Specify thermal relationships. A zone can be influenced by multiple source devices with varying degrees. In this case thermal-conf.xml can be used to define the relative influence for apply compensation. .SH FILE FORMAT The configuration file format confirms to XML specifications. A set of tags defined to define platform, sensors, zones, cooling devices and trip points. .TP .TP .TP Example Platform Name .TP .TP Example UUID .TP configuration file format confirms to XML specifications. A set of tags defined to define platform, sensors, zones, cooling devices and trip points. Example Product Name .TP QUIET|PERFORMANCE .TP .TP .TP .TP .TP example_sensor_1 .TP /some_path .TP 0 .TP .TP .TP .TP example_thermal_sysfs_sensor .TP .TP 1 .TP .TP .TP .TP .TP Example Zone type .TP .TP .TP example_sensor_1 .TP .TP 75000 .TP .TP max .TP .TP SEQUENTIAL .TP .TP 1 .TP example_cooling_device .TP .TP 100 .TP .TP 12 .TP .TP 6 .TP .TP .TP .TP .TP .TP .TP .TP .TP example_cooling_device .TP 0 .TP 10 .TP 0 .TP 50 .TP 5000 .TP .TP .TP 0.001 .TP 0.0001 .TP 0.0001 .TP .TP .TP .TP .TP .SH EXAMPLE CONFIGURATIONS .TP Example 1: This is a very simple configuration, to change the passive limit on the CPU. Instead of default, this new temperature 86C in the configuration is used. This will start cooling, once the temperature reaches 86C. .TP .TP .TP .TP Overide CPU default passive .TP * .TP QUIET .TP .TP .TP cpu .TP .TP .TP 86000 .TP passive .TP .TP .TP .TP .TP .TP .TP Example 2: In this configuration, we are controlling backlight when some sensor "SEN2" reaches 60C. Here "LCD" is a standard cooling device, which uses Linux backlight sysfs interface. "SEN2" is a valid thermal zone in Linux thermal sysfs on the test platform, hence we don't need to provide path for sysfs for "SEN2". The Linux thermal sysfs is already parsed and loaded by thermald program. .TP .TP .TP .TP Change Backlight .TP * .TP QUIET .TP .TP .TP LCD_Zone .TP .TP .TP SEN2 .TP 60000 .TP passive .TP .TP LCD .TP .TP .TP .TP .TP .TP .TP .TP Example 3: In this example Lenovo Thinkpad X220 and fan speed is controlled. Here a cooling device "_Fan", can be controlled via sysfs /sys/devices/platform/thinkpad_hwmon/pwm1. When the x86_pkg_temp reaches 45C, Fan is started with increasing speeds, if the temperature can't be controlled at 45C. .TP .TP .TP .TP Lenovo ThinkPad X220 .TP * .TP QUIET .TP .TP .TP x86_pkg_temp .TP .TP .TP x86_pkg_temp .TP 45000 .TP passive .TP SEQUENTIAL .TP .TP 1 .TP _Fan .TP 100 .TP 12 .TP .TP .TP .TP .TP .TP .TP .TP _Fan .TP /sys/devices/platform/thinkpad_hwmon/pwm1 .TP 0 .TP 30 .TP 0 .TP 255 .TP 5 .TP .TP .TP .TP .TP thermald-1.5/man/thermald.80000664000175000017500000000712412661205366014302 0ustar kingking.\" thermald (8) manual page .\" .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual 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 Licence along .\" with this manual; if not, write to the Free Software Foundation, Inc., .\" 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. .\" .\" Copyright (C) 2012 Intel Corporation. All rights reserved. .\" .TH thermald "8" "8 May 2013" .SH NAME thermald \- start Linux thermal daemon .SH SYNOPSIS .B thermald .RI " [ " OPTIONS " ] .SH DESCRIPTION .B thermald is a Linux daemon used to prevent the overheating of platforms. This daemon monitors temperature and applies compensation using available cooling methods. By default, it monitors CPU temperature using available CPU digital temperature sensors and maintains CPU temperature under control, before HW takes aggressive correction action. Thermal daemon looks for thermal sensors and thermal cooling drivers in the Linux thermal sysfs (/sys/class/thermal) and builds a list of sensors and cooling drivers. Each of the thermal sensors can optionally be binded to a cooling drivers by the in kernel drivers. In this case the Linux kernel thermal core can directly take actions based on the temperature trip points, for each sensor and associated cooling device. For example a trip temperature X in a sensor can be associates a cooling driver Y. So when the sensor temperature = X, the cooling driver "Y" is activated. Thermal daemon allows to change this relationship or add new one via a thermal configuration file (thermal-conf.xml). This file is automatically created and used, if the platform has ACPI thermal relationship table. If not this needs to be manually configured. When there is a sensor, which has no associate cooling device, via configuration file or thermal relationship table, then this sensor is tested for relationship with CPU load dynamically up to maximum 3 times. If there is no relationship, then it is added to a black list of unbinded sensors and not tried again. Optionally thermal daemon can act as an exclusive thermal controller by using thermal sysfs and acting as a user space governor. In this case kernel thermal core is not active and decision is taken by thermal daemon only. .SH OPTIONS .TP .B \-h, \-\-help Show help options. .TP .B \-\-version Print thermald version and exit. .TP .B \-\-no-daemon Don't become a daemon: Default is daemon mode. .TP .B \-\-loglevel=info log severity: info level and up. .TP .B \-\-loglevel=debug log severity: debug level and up: Max logging. .TP .B \-\-poll-interval Poll interval in seconds: Poll for zone temperature changes. To disable polling, set to zero. Polling can only be disabled, if available temperature sensors can notify temperature change asynchronously. .TP .B \-\-dbus-enable Enable Dbus. .TP .B \-\-exclusive-control Act as exclusive thermal controller. This will use user-space governor for thermal sysfs and take over control. .SH SEE ALSO thermal-conf.xml(5) thermald-1.5/configure.ac0000664000175000017500000000506712661205366014130 0ustar kingkingAC_PREREQ(1.0) m4_define([td_major_version], [1]) m4_define([td_minor_version], [5]) m4_define([td_version], [td_major_version.td_minor_version]) AC_INIT([thermald], [td_version], [], [thermald]) AC_CONFIG_AUX_DIR(build-aux) AC_CONFIG_HEADERS([config.h]) AM_INIT_AUTOMAKE([1.11 foreign no-define subdir-objects]) AM_MAINTAINER_MODE([enable]) AC_ARG_WITH(dbus-sys-dir, AS_HELP_STRING([--with-dbus-sys-dir=DIR], [where D-BUS system.d directory is])) if test -n "$with_dbus_sys_dir" ; then DBUS_SYS_DIR="$with_dbus_sys_dir" else DBUS_SYS_DIR="/etc/dbus-1/system.d" fi AC_SUBST(DBUS_SYS_DIR) # paths AC_SUBST(tdbinary, "$sbindir/$PACKAGE", [Binary executable]) AC_SUBST(tdconfdir, "$sysconfdir/$PACKAGE", [Configuration directory]) AC_SUBST(tdrundir, "$localstatedir/run/$PACKAGE", [Runtime state directory]) PKG_PROG_PKG_CONFIG AC_ARG_WITH([systemdsystemunitdir], AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files]), [], [with_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)]) if test "x$with_systemdsystemunitdir" != xno; then AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir]) fi AM_CONDITIONAL(HAVE_SYSTEMD, [test -n "$with_systemdsystemunitdir" -a "x$with_systemdsystemunitdir" != xno ]) # print configuration echo echo "System paths:" echo " prefix: $prefix" echo " exec_prefix: $exec_prefix" echo " systemdunitdir: $with_systemdsystemunitdir" echo " tdbinary: $tdbinary" echo " tdconfdir: $tdconfdir" echo " tdrundir: $tdrundir" echo GETTEXT_PACKAGE=thermald AC_SUBST(GETTEXT_PACKAGE) AC_DEFINE_UNQUOTED(GETTEXT_PACKAGE,"$GETTEXT_PACKAGE", [Gettext package]) dnl dnl Checks for new dbus-glib property access function dnl AC_CHECK_LIB([dbus-glib-1], [dbus_glib_global_set_disable_legacy_property_access], ac_have_dg_prop="1", ac_have_dg_prop="0") AC_DEFINE_UNQUOTED(HAVE_DBUS_GLIB_DISABLE_LEGACY_PROP_ACCESS, $ac_have_dg_prop, [Define if you have a dbus-glib with dbus_glib_global_set_disable_legacy_property_access()]) PKG_CHECK_MODULES(DBUS, dbus-1 >= 1.1 dbus-glib-1 >= 0.94) AC_SUBST(DBUS_CFLAGS) AC_SUBST(DBUS_LIBS) GLIB_VERSION_DEFINES="-DGLIB_VERSION_MIN_REQUIRED=GLIB_VERSION_2_26" DBUS_CFLAGS="$DBUS_CFLAGS $GLIB_VERSION_DEFINES" PKG_CHECK_MODULES(GLIB, gio-unix-2.0 >= 2.22 gmodule-2.0) GLIB_CFLAGS="$GLIB_CFLAGS $GLIB_VERSION_DEFINES" AC_SUBST(GLIB_CFLAGS) AC_SUBST(GLIB_LIBS) PKG_CHECK_MODULES(XML, libxml-2.0 >= 2.4) AC_PROG_CC AC_PROG_CPP AC_PROG_CXX AC_PROG_INSTALL AC_C_CONST AC_C_INLINE AC_TYPE_SIZE_T AC_CONFIG_FILES([Makefile data/Makefile]) AC_OUTPUT thermald-1.5/COPYING0000664000175000017500000004310012661205366012663 0ustar kingking GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. thermald-1.5/Makefile.am0000664000175000017500000000367112661205366013675 0ustar kingkinginclude $(GLIB_MAKEFILE) SUBDIRS = data ACLOCAL_AMFLAGS = # Global C Flags AM_CFLAGS = ${DBUS_CFLAGS} AM_CXXFLAGS = ${DBUS_CFLAGS}\ $(XML_CFLAGS) \ -DTDRUNDIR=\"$(tdrundir)\" \ -DTDCONFDIR=\"$(tdconfdir)\" \ -I src \ -fpermissive \ -fopenmp \ -Wreorder \ -Wsign-compare \ -Wreturn-type \ -Wunused-but-set-variable\ -Wformat EXTRA_DIST=Makefile.glib \ thermald.pc.in # Programs to build sbin_PROGRAMS = thermald # Evaluate Table Application thermald_CPPFLAGS = \ -I@top_srcdir@/src \ -DTDLOCALEDIR=\"$(datadir)/locale\" \ -DGLIB_SUPPORT thermald_includedir = @top_srcdir@ thermald_LDADD = \ $(DBUS_LIBS) \ $(GLIB_LIBS) \ $(LIBNL_LIBS) \ $(LIBM) \ $(LIBDL) \ $(XML_LIBS) BUILT_SOURCES = \ thd_dbus_interface.h thermald_SOURCES = \ src/main.cpp \ src/thd_dbus_interface.cpp \ src/thd_engine.cpp \ src/thd_cdev.cpp \ src/thd_cdev_therm_sys_fs.cpp \ src/thd_engine_default.cpp \ src/thd_sys_fs.cpp \ src/thd_trip_point.cpp \ src/thd_zone.cpp \ src/thd_zone_surface.cpp \ src/thd_zone_cpu.cpp \ src/thd_zone_therm_sys_fs.cpp \ src/thd_zone_dynamic.cpp \ src/thd_preference.cpp \ src/thd_model.cpp \ src/thd_parse.cpp \ src/thd_sensor.cpp \ src/thd_sensor_virtual.cpp \ src/thd_kobj_uevent.cpp \ src/thd_cdev_order_parser.cpp \ src/thd_cdev_gen_sysfs.cpp \ src/thd_pid.cpp \ src/thd_zone_generic.cpp \ src/thd_cdev_cpufreq.cpp \ src/thd_cdev_rapl.cpp \ src/thd_cdev_intel_pstate_driver.cpp \ src/thd_msr.cpp \ src/thd_rapl_interface.cpp \ src/thd_rapl_power_meter.cpp \ src/thd_trt_art_reader.cpp \ src/thd_cdev_rapl_dram.cpp \ src/thd_cpu_default_binding.cpp \ src/thd_cdev_backlight.cpp man5_MANS = man/thermal-conf.xml.5 man8_MANS = man/thermald.8 thd_dbus_interface.h: $(top_srcdir)/src/thd_dbus_interface.xml $(AM_V_GEN) dbus-binding-tool --prefix=thd_dbus_interface --mode=glib-server --output=$@ $< CLEANFILES = $(BUILT_SOURCES)