Move status to python

This commit is contained in:
Rico Tiongson 2019-03-03 21:43:57 +08:00
parent 697e0b8802
commit 0f7a222d86
19 changed files with 115 additions and 390 deletions

View File

@ -1,9 +1,12 @@
from __future__ import print_function
import sys
from comfortable_swipe.autostart import toggle_status
from comfortable_swipe.cpp import service as cpp_service
from comfortable_swipe.constants import CONFIG
from comfortable_swipe.status import print_status
from comfortable_swipe.cpp import service as cpp_service
def main():
if len(sys.argv) <= 1:
@ -16,7 +19,7 @@ def main():
buffer=cpp_service.buffer,
help=cpp_service.help,
debug=cpp_service.debug,
status=cpp_service.status,
status=print_status,
autostart=lambda: print('Autostart switched', toggle_status()),
config=lambda: print(CONFIG),
)[sys.argv[1]]()

View File

@ -2,8 +2,8 @@ from __future__ import print_function
import os
import sys
from distutils.spawn import find_executable
from comfortable_swipe.constants import EXE, RES
from comfortable_swipe.constants import NAME, RES, exe
# status enums
@ -14,15 +14,18 @@ ON = 'on'
# the target path to the autostart desktop file
def target_path():
return os.path.join(
os.getenv('XDG_CONFIG_HOME', os.path.join(os.getenv('HOME'), '.config')),
os.getenv(
'XDG_CONFIG_HOME',
os.path.join(os.getenv('HOME'), '.config')
),
'autostart',
EXE + '.desktop'
'{}.desktop'.format(NAME)
)
# path to the autostart template file to be copied
def template_path():
return os.path.join(RES, EXE + '.desktop')
return os.path.join(RES, '{}.desktop'.format(NAME))
# parsed contents of the template file
@ -31,7 +34,7 @@ def template(raw=False):
contents = file.read()
if raw:
return contents
return contents.replace('Exec=' + EXE, 'Exec={} {}'.format(sys.executable, find_executable(EXE)))
return contents.replace('Exec=' + NAME, 'Exec={} {}'.format(sys.executable, exe()))
# gets the current autostart status
@ -41,10 +44,10 @@ def get_status():
# sets the autostart status
def set_status(status=ON):
if status is ON:
if status == ON:
with open(target_path(), 'w') as file:
file.write(template())
elif status is OFF:
elif status == OFF:
if os.path.exists(target_path()):
os.remove(target_path())
else:
@ -55,4 +58,4 @@ def set_status(status=ON):
# toggles autostart status
def toggle_status():
return set_status(OFF if get_status() == ON else OFF)
return set_status(OFF if get_status() == ON else ON)

View File

@ -1,9 +1,17 @@
import os
import sys
from distutils.spawn import find_executable
EXE = 'comfortable-swipe'
NAME = 'comfortable-swipe'
DESCRIPTION = 'Comfortable 3-finger and 4-finger swipe gestures'
BIN = os.path.dirname(sys.executable)
DIR = os.path.dirname(os.path.abspath(__file__))
PYTHON_NAME = os.path.basename(DIR)
RES = os.path.join(DIR, 'res')
CONFIG = os.path.join(sys.prefix, 'local', 'share', EXE, EXE + '.conf')
CONFIG = os.path.join(sys.prefix, 'local', 'share', NAME, '{}.conf'.format(NAME))
DEFAULT_CONFIG = os.path.join(RES, 'defaults.conf')
def exe():
return find_executable(NAME)

View File

@ -0,0 +1,22 @@
from __future__ import print_function
import os
from comfortable_swipe import autostart
from comfortable_swipe.cpp import service
from comfortable_swipe.constants import NAME, exe
def print_status():
service.status()
print('autostart is', autostart.get_status().upper())
print('{} is {}'.format(NAME, 'RUNNING' if is_running() else 'STOPPED'))
def is_running():
import psutil
for process in psutil.process_iter():
process_args = [process.name()] + process.cmdline()
for index in range(len(process_args) - 1):
if process_args[index + 1] == 'start' and process_args[index].endswith(NAME):
return True
return False

View File

@ -2,11 +2,11 @@
#define __COMFORTABLE_SWIPE__macro_hpp__
#ifndef __COMFORTABLE_SWIPE__CONFIG__
#define __COMFORTABLE_SWIPE__CONFIG__ "/usr/local/share/comfortable-swipe/comfortable-swipe.conf"
#warning "__COMFORTABLE_SWIPE__CONFIG__ must be defined."
#endif /* __COMFORTABLE_SWIPE__CONFIG__ */
#ifndef __COMFORTABLE_SWIPE__VERSION__
#warning __COMFORTABLE_SWIPE__VERSION__ "must be defined."
#warning "__COMFORTABLE_SWIPE__VERSION__ must be defined."
#endif /* __COMFORTABLE_SWIPE__VERSION__ */
#endif /* __COMFORTABLE_SWIPE__macro_hpp__ */

View File

@ -2,7 +2,6 @@
#define __COMFORTABLE_SWIPE__python_cpp__
#include "service/_python.cpp"
// #include "util/_python.cpp"
#include "comfortable-swipe.cpp"
#endif /* __COMFORTABLE_SWIPE__python_cpp__ */

View File

@ -2,9 +2,7 @@
#define __COMFORTABLE_SWIPE__service_index_cpp__
#include "_index.hpp"
// #include "autostart.cpp"
#include "buffer.cpp"
// #include "config.cpp"
#include "debug.cpp"
#include "help.cpp"
#include "restart.cpp"

View File

@ -10,9 +10,7 @@ extern "C"
{
namespace service
{
// void autostart();
void buffer();
// void config();
void debug();
void help();
void restart();

View File

@ -1,73 +0,0 @@
#ifndef __COMFORTABLE_SWIPE__service_autostart__
#define __COMFORTABLE_SWIPE__service_autostart__
/*
Comfortable Swipe
by Rico Tiongson
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/>.
*/
#include "../util/_index.hpp"
#include <iostream> // std::cerr, std::cout, std::endl
#include <fstream> // std::ifstream, std::ofstream
#include <string> // std::string
#include <cstdio> // std::remove
#include <cstdlib> // std::system
namespace comfortable_swipe::service
{
/**
* Toggles automatic startup of comfortable swipe.
*/
void autostart()
{
using comfortable_swipe::util::autostart_filename;
const std::string& path = autostart_filename();
if (std::ifstream(path.data()).good())
{
// file found, delete it
if (std::remove(path.data()) != 0)
std::cerr << "Error: failed to switch off autostart. "
<< "Maybe the autostart file is in use?"
<< std::endl;
else
std::cout << "Autostart switched off" << std::endl;
}
else {
// file not found, create it
int result = std::system(("mkdir -p $(dirname " + path + ")").data());
std::ofstream fout(path.data());
if (result != 0 || !fout.good())
std::cerr << "Error: failed to switch on autostart. "
<< "Are you sure you have the permissions?"
<< std::endl;
else {
fout <<
"[Desktop Entry]\n"
"Type=Application\n"
"Exec=comfortable-swipe start\n"
"Hidden=false\n"
"NoDisplay=false\n"
"X-GNOME-Autostart-enabled=true\n"
"Name=Comfortable Swipe\n"
"Comment=3 or 4 touchpad gestures\n";
std::cout << "Autostart switched on" << std::endl;
}
}
}
}
#endif /* __COMFORTABLE_SWIPE__service_autostart__ */

View File

@ -19,6 +19,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../_macro.cpp"
#include "../util/_index.hpp"
#include "../gesture/_index.hpp"
#include <cstdio> // fgets_unlocked, stdin
@ -31,7 +32,7 @@ namespace comfortable_swipe::service
void buffer()
{
// read config file
auto config = comfortable_swipe::util::read_config_file(comfortable_swipe::util::conf_filename());
auto config = comfortable_swipe::util::read_config_file(__COMFORTABLE_SWIPE__CONFIG__);
// initialize swipe gesture handler
comfortable_swipe::gesture::swipe_gesture swipe_gesture_handler

View File

@ -1,38 +0,0 @@
#ifndef __COMFORTABLE_SWIPE__service_config__
#define __COMFORTABLE_SWIPE__service_config__
/*
Comfortable Swipe
by Rico Tiongson
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/>.
*/
#include "../util/_index.hpp"
#include <cstdio> // std::puts
namespace comfortable_swipe::service
{
/**
* Prints where the config file of comfortable swipe is located.
*
* Usage: nano $(comfortable-swipe config)
*/
void config()
{
std::puts(comfortable_swipe::util::conf_filename());
}
}
#endif /* __COMFORTABLE_SWIPE__service_config__ */

View File

@ -19,7 +19,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../util/_index.hpp"
#include <cstdio> // std::puts, std::printf
namespace comfortable_swipe::service
@ -29,7 +28,6 @@ namespace comfortable_swipe::service
*/
void help()
{
using comfortable_swipe::util::conf_filename;
std::puts("comfortable-swipe [start|stop|restart|autostart|buffer|help|config|debug|status]");
std::puts("");
std::puts("start - starts 3/4-finger gesture service");
@ -41,8 +39,6 @@ namespace comfortable_swipe::service
std::puts("config - locates the config file");
std::puts("debug - logs raw output from input events taken from libinput");
std::puts("status - checks status of program and autostart");
std::puts("");
std::printf("Configuration file can be found in %s\n", conf_filename());
}
}

View File

@ -19,6 +19,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../_macro.cpp"
#include "../util/_index.hpp"
#include "../gesture/_index.hpp"
#include <stdexcept> // std::runtime_error
@ -36,45 +37,22 @@ namespace comfortable_swipe::service
*/
void status()
{
// check if comfortable-swipe is running
bool running = false;
std::array<char, 128> buffer;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen("pgrep -f comfortable-swipe", "r"), pclose);
if (pipe && !std::feof(pipe.get()) && std::fgets(buffer.data(), buffer.size(), pipe.get()) != NULL)
{
int pid = std::atoi(buffer.data());
if (pid != getpid())
running = true;
}
// check if autostart is on
auto autostart_f = comfortable_swipe::util::autostart_filename();
bool autostart_on = access(autostart_f, F_OK) != -1;
// print status
std::printf("program is %s\n", running ? "ON" : "OFF");
std::printf("autostart is %s\n", autostart_on ? "ON" : "OFF");
std::printf("config file at %s\n", comfortable_swipe::util::conf_filename());
// std::printf("autostart is %s\n", autostart_on ? "ON" : "OFF");
// check status of configuration file
try
{
auto config = comfortable_swipe::util::read_config_file(comfortable_swipe::util::conf_filename());
// print keys and values of config file
std::printf("\nConfigurations:\n");
std::puts(__COMFORTABLE_SWIPE__CONFIG__);
auto config = comfortable_swipe::util::read_config_file(__COMFORTABLE_SWIPE__CONFIG__);
// print threshold
if (config.count("threshold") > 0)
{
auto & threshold = config["threshold"];
// check if regex pattern matches threshold
std::cmatch matches;
bool ok = (std::regex_match(threshold.data(), matches, std::regex("^\\d+(?:\\.\\d+)??$")) != 0);
// print status of threshold
std::printf(" %9s is %s (%s)\n", "threshold", ok ? "OK" : "INVALID", threshold.data());
std::printf(" %9s = %s (%s)\n", "threshold", threshold.data(), ok ? "VALID" : "INVALID");
}
else
std::printf(" %9s is OFF\n", "threshold");
@ -83,9 +61,9 @@ namespace comfortable_swipe::service
for (auto &command : comfortable_swipe::gesture::swipe_gesture::command_map)
{
if (config.count(command) > 0)
std::printf(" %9s is OK (%s)\n", command, config[command].data());
std::printf(" %9s = %s\n", command, config[command].data());
else
std::printf(" %9s is OFF\n", command);
std::printf(" %9s NOT SET\n", command);
}
}
catch (const std::runtime_error& e)

View File

@ -2,8 +2,6 @@
#define __COMFORTABLE_SWIPE__util_index_cpp__
#include "_index.hpp"
#include "autostart_filename.cpp"
#include "conf_filename.cpp"
#include "read_config_file.cpp"
#endif /* __COMFORTABLE_SWIPE__util_index_cpp__ */

View File

@ -10,8 +10,6 @@ extern "C"
{
namespace util
{
const char* autostart_filename();
constexpr const char* conf_filename();
std::map<std::string, std::string> read_config_file(const char*);
}
}

View File

@ -1,70 +0,0 @@
#ifndef __COMFORTABLE_SWIPE__util_python__
#define __COMFORTABLE_SWIPE__util_python__
#include "_index.hpp"
#include <Python.h>
// export as python module
namespace comfortable_swipe::util::python
{
// create the python method signatures
static PyObject *
autostart_filename(PyObject * self, PyObject * args)
{
return Py_BuildValue("s", comfortable_swipe::util::autostart_filename());
}
static PyObject *
conf_filename(PyObject * self, PyObject * args)
{
return Py_BuildValue("s", comfortable_swipe::util::conf_filename);
}
#undef __comfortable_swipe_void_method
// create the method list for C++
static PyMethodDef methods[] =
{
{ "autostart_filename", &autostart_filename, METH_VARARGS, "the location of the autostart file" },
{ "conf_filename", &conf_filename, METH_VARARGS, "the location of the configuration file" },
{ NULL, NULL, 0, NULL } // sentinel
};
// create the module configuration
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef module_def =
{
PyModuleDef_HEAD_INIT,
"util",
"Comfortable swipe utility",
-1,
methods
};
#endif
PyObject * module;
}
// initialize module
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC
PyInit_util(void)
{
using comfortable_swipe::util::python::module_def;
using comfortable_swipe::util::python::module;
if (module != NULL) return module;
return module = PyModule_Create(&module_def);
}
#else /* PY_MAJOR_VERSION < 3 */
PyMODINIT_FUNC
initutil(void)
{
using comfortable_swipe::util::python::methods;
using comfortable_swipe::util::python::module;
if (module != NULL) return;
module = Py_InitModule("util", methods);
}
#endif /* PY_MAJOR_VERSION */
#endif /* __COMFORTABLE_SWIPE__util_python__ */

View File

@ -1,46 +0,0 @@
#ifndef __COMFORTABLE_SWIPE__util_autostart_filename__
#define __COMFORTABLE_SWIPE__util_autostart_filename__
/*
Comfortable Swipe
by Rico Tiongson
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/>.
*/
#include <string> // std::string
#include <unistd.h> // getenv
namespace comfortable_swipe::util
{
/**
* The path where the autostart configuration is located.
*/
const char* autostart_filename()
{
static std::string filename;
if (filename.empty()) {
const char* xdg_config = getenv("XDG_CONFIG_HOME");
std::string config(
xdg_config == NULL
? std::string(getenv("HOME")) + "/.config"
: xdg_config
);
filename = config + "/autostart/comfortable-swipe.desktop";
}
return filename.data();
}
}
#endif /* __COMFORTABLE_SWIPE__util_autostart_filename__ */

View File

@ -1,33 +0,0 @@
#ifndef __COMFORTABLE_SWIPE__util_conf_filename__
#define __COMFORTABLE_SWIPE__util_conf_filename__
/*
Comfortable Swipe
by Rico Tiongson
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/>.
*/
namespace comfortable_swipe::util
{
/**
* The path where the configuration file is located.
*/
constexpr const char* conf_filename()
{
return __COMFORTABLE_SWIPE__CONFIG__;
}
}
#endif /* __COMFORTABLE_SWIPE__util_conf_filename__ */

View File

@ -13,27 +13,31 @@ from wheel.bdist_wheel import bdist_wheel
VERSION = '1.1.0-beta'
__BIN__ = os.path.dirname(sys.executable)
__CWD__ = os.getcwd()
__DIR__ = os.path.dirname(os.path.abspath(__file__))
__URL__ = 'https://github.com/Hikari9/comfortable-swipe-ubuntu'
extension_names = ['service']
try:
# make sure working directory is here
os.chdir(__DIR__)
# match constants with source
from comfortable_swipe.constants import EXE, RES, CONFIG, DEFAULT_CONFIG
# additional constants
NAME = EXE
PYTHON_NAME = NAME.replace('-', '_')
# save README as long_description
with open('README.md', 'r') as README_file:
README = README_file.read()
# match constants with source
from comfortable_swipe.constants import *
# include old conf paths to list from previous versions
conf_paths = [
DEFAULT_CONFIG,
os.path.join(os.getenv('HOME'), '.config', 'comfortable-swipe', 'comfortable-swipe.conf'),
os.path.join(os.getenv('HOME', ''), '.config', 'comfortable-swipe', 'comfortable-swipe.conf'),
os.path.join('/usr/local/share', 'comfortable-swipe', 'comfortable-swipe.conf'),
CONFIG
]
@ -44,12 +48,7 @@ try:
__COMFORTABLE_SWIPE__CONFIG__='"{}"'.format(CONFIG)
)
# save README as long_description
with open('README.md', 'r') as README_file:
README = README_file.read()
# read C++ libraries for comfortable swipe
extension_names = ['service']
extensions = [Extension(
name='{}.cpp.{}'.format(PYTHON_NAME, extension_name),
define_macros=list(cpp_macros.items()),
@ -59,15 +58,16 @@ try:
) for extension_name in extension_names]
# add post_install script to install method
class Install(install):
def run(self):
self.pre_install()
install.run(self)
self.post_install()
def pre_install(self):
# print('running pre_install')
pass
def post_install(self):
print('running post_install')
# create program/config directories
if not os.path.exists(os.path.dirname(CONFIG)):
os.makedirs(os.path.dirname(CONFIG))
@ -79,11 +79,9 @@ try:
if conf_files[-1] != CONFIG:
# new installation or upgrading from old version, copy to new location
copyfile(conf_files[-1], CONFIG)
if conf_files[-1] == DEFAULT_CONFIG:
# new installation - copy default configuration
print('Copying configuration file to', CONFIG)
else:
# upgrading - delete the deprecated config file (failsafe)
print('warning: depcrecated configuration file at', conf_files[-1])
@ -96,36 +94,20 @@ try:
print('\nInstallation successful\nTry running: {} start'.format(NAME))
class Develop(develop):
def run(self):
self.pre_uninstall() if self.uninstall else Install.pre_install(self)
develop.run(self)
self.post_uninstall() if self.uninstall else Install.post_install(self)
def pre_uninstall(self):
print('running pre_uninstall')
# remove autostart config
from comfortable_swipe import autostart
if autostart.get_status() is autostart.ON:
print('Removing autostart at', autostart.target_path())
autostart.set_status(autostart.OFF)
def post_uninstall(self):
# print('running post_uninstall')
pass
# add post_install script to install method
class Install(install):
def run(self):
pre_install(self)
install.run(self)
post_install(self)
class Develop(develop):
def run(self):
pre_uninstall(self) if self.uninstall else pre_install(self)
develop.run(self)
post_uninstall(self) if self.uninstall else post_install(self)
# Override command classes here
cmdclass = dict(Install=Install, develop=Develop, bdist_wheel=bdist_wheel)
@ -133,7 +115,7 @@ try:
setup_script = setup(
name=NAME,
version=VERSION,
description='Comfortable 3-finger and 4-finger swipe gestures',
description=DESCRIPTION,
long_description=README,
license='MIT',
author='Rico Tiongson',
@ -142,9 +124,10 @@ try:
zip_safe=False,
packages=find_packages(),
include_package_data=True,
entry_points=dict(console_scripts=['{}=comfortable_swipe.__main__:main'.format(NAME)]),
entry_points=dict(console_scripts=['{}={}.__main__:main'.format(NAME, PYTHON_NAME)]),
ext_modules=extensions,
cmdclass=cmdclass
cmdclass=cmdclass,
install_requires=['psutil']
)
finally: