Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add workflow to change bg image of current desktop
- Loading branch information
Daniel Kriesten
committed
Aug 28, 2014
1 parent
f5bce3d
commit ac3a0a7
Showing
6 changed files
with
306 additions
and
0 deletions.
There are no files selected for viewing
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
#author: Peter Okma | ||
import xml.etree.ElementTree as et | ||
|
||
|
||
class Feedback(): | ||
"""Feeback used by Alfred Script Filter | ||
Usage: | ||
fb = Feedback() | ||
fb.add_item('Hello', 'World') | ||
fb.add_item('Foo', 'Bar') | ||
print fb | ||
""" | ||
|
||
def __init__(self): | ||
self.feedback = et.Element('items') | ||
|
||
def __repr__(self): | ||
"""XML representation used by Alfred | ||
Returns: | ||
XML string | ||
""" | ||
return et.tostring(self.feedback) | ||
|
||
def add_item(self, title, subtitle="", arg="", valid="yes", autocomplete="", icon="icon.png"): | ||
""" | ||
Add item to alfred Feedback | ||
Args: | ||
title(str): the title displayed by Alfred | ||
Keyword Args: | ||
subtitle(str): the subtitle displayed by Alfred | ||
arg(str): the value returned by alfred when item is selected | ||
valid(str): whether or not the entry can be selected in Alfred to trigger an action | ||
autcomplete(str): the text to be inserted if an invalid item is selected. This is only used if 'valid' is 'no' | ||
icon(str): filename of icon that Alfred will display | ||
""" | ||
item = et.SubElement(self.feedback, 'item', uid=str(len(self.feedback)), | ||
arg=arg, valid=valid, autocomplete=autocomplete) | ||
_title = et.SubElement(item, 'title') | ||
_title.text = title | ||
_sub = et.SubElement(item, 'subtitle') | ||
_sub.text = subtitle | ||
_icon = et.SubElement(item, 'icon') | ||
_icon.text = icon |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
#!/usr/bin/env python | ||
# vim: ts=4:sw=4:sts=4:tw=120:expandtab:fileencoding=utf-8 | ||
""" | ||
Package : open_bg_images | ||
Author(s) : Daniel Kriesten | ||
Email : daniel.kriesten@etit.tu-chemnitz.de | ||
Creation Date : Do 28 Aug 21:23:25 2014 | ||
""" | ||
|
||
import sys | ||
import argparse | ||
import logging | ||
__logger__ = logging.getLogger(__name__) | ||
import logging.handlers | ||
import runcommand | ||
import feedback | ||
|
||
__BG_BASEDIR__ = "/Users/krid/Dropbox/Public/Wallpapers" | ||
|
||
def find_files(basedir, _filter=""): | ||
"""create a list of tp files""" | ||
command = ["mdfind", "-onlyin", basedir, "kMDItemContentTypeTree==public.image&&kMDItemFSName==*" + _filter + "*"] | ||
__logger__.debug(command) | ||
# simple call to run a system process | ||
cmd = runcommand.RunCommand(command) | ||
file_list = cmd.run() | ||
atree = feedback.Feedback() | ||
if file_list != None: | ||
__logger__.debug(file_list) | ||
for file_ in sorted(file_list): | ||
fname = file_.split("/")[-1] | ||
atree.add_item(fname, subtitle="Use " + fname + " as Background Image", arg=file_) | ||
__logger__.info(atree) | ||
alfred_xml = repr(atree) | ||
return alfred_xml | ||
|
||
def main(): | ||
"""the main programm""" | ||
# some arguments to care fore | ||
parser = argparse.ArgumentParser( | ||
description=u"View a list of TaskPaper files in Alfred xml Format", | ||
epilog=u"Tested with TaskPaper v2 and Alfred v2", | ||
conflict_handler="resolve") | ||
parser.add_argument("--version", action="version", version="%(prog)s 0.1") | ||
parser.add_argument("-v", | ||
"--verbose", | ||
default=False, | ||
action="store_true", | ||
help="be verbose" | ||
) | ||
parser.add_argument("-d", | ||
"--debug", | ||
default=False, | ||
action="store_true", | ||
help="do debugging to stderr") | ||
parser.add_argument("-b", | ||
"--basedir", | ||
default=__BG_BASEDIR__, | ||
help="the basedir to start searching") | ||
parser.add_argument("-f", | ||
"--filter", | ||
default="", | ||
help="filter results") | ||
(options, args) = parser.parse_known_args() | ||
|
||
###################### | ||
# instantiate a logger | ||
logger = logging.getLogger() | ||
logger.setLevel(logging.DEBUG) | ||
handler = logging.StreamHandler(stream=sys.stderr) | ||
if options.debug: | ||
handler.setLevel(logging.DEBUG) | ||
elif options.verbose: | ||
handler.setLevel(logging.INFO) | ||
else: | ||
handler.setLevel(logging.WARNING) | ||
handler.setFormatter(logging.Formatter("-- %(funcName)s [%(levelname)s]: %(message)s")) | ||
logger.addHandler(handler) | ||
|
||
# run the working task | ||
ret = find_files(options.basedir.replace(" ", r"\ "), options.filter) | ||
if ret != None: | ||
sys.stdout.write(ret) | ||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
#!/usr/bin/env python | ||
# vim: ts=4:sw=4:sts=4:tw=80:expandtab:fileencoding=utf-8 | ||
# Package : run_command | ||
# Author(s) : Daniel Kriesten | ||
# Email : daniel.kriesten@etit.tu-chemnitz.de | ||
# Creation Date : Di 25 Jun 11:21:07 2013 | ||
#################################################################### | ||
""" runncommand | ||
A simple wrapper to run a given command using python subprocess module | ||
""" | ||
|
||
import sys | ||
import time | ||
import subprocess | ||
|
||
# like always .. the __logger__ | ||
import logging | ||
import logging.handlers | ||
__logger__ = logging.getLogger(__name__) | ||
|
||
|
||
class RunCommand(object): | ||
'''wrapper class for running a command with timeout''' | ||
|
||
def __init__(self, command=None, timeout=25): | ||
'''Initialize the module''' | ||
__logger__.debug('''Initializing %s''', __name__) | ||
self._timeout = timeout | ||
if command: | ||
self._command = list(command) #create a copy of the given list | ||
else: | ||
self._command = [] | ||
__logger__.debug('Command %s; timeout %d', command, timeout) | ||
self._start = -1 | ||
self._duration = -1 | ||
|
||
def set_timeout(self, timeout): | ||
''' set a timeout ''' | ||
assert timeout > 0 | ||
self._timeout = timeout | ||
|
||
def get_starttime(self): | ||
''' return the start time ''' | ||
return self._start | ||
|
||
def get_duration(self): | ||
''' return the duration ''' | ||
return self._duration | ||
|
||
def add_command(self, command): | ||
'''add the command's name''' | ||
__logger__.debug('Adding command: %s', command) | ||
if len(self._command) < 1: | ||
self._command.append(command) | ||
else: | ||
self._command[0] = command | ||
|
||
def get_command(self): | ||
''' return the command ''' | ||
return self.__str__() | ||
|
||
def add_option(self, option, argument=None, connector=None): | ||
'''Add an option with optional argument''' | ||
# TODO: check if option/argument is a valid one | ||
#if option in self._optionslist: | ||
if argument: | ||
if connector: | ||
self._command.append('%s%s%s'%(option, connector, argument)) | ||
__logger__.debug('added: %s%s%s', option, connector, argument) | ||
else: | ||
self._command.extend([option, str(argument)]) | ||
__logger__.debug('added: %s %s', option, argument) | ||
else: | ||
self._command.append(option) | ||
__logger__.debug('added: %s', option) | ||
__logger__.debug('''Command is now: "%s"''', self._command) | ||
|
||
def run(self, timeout=None): | ||
'''runn command, using the command list''' | ||
if timeout == None: | ||
timeout = self._timeout | ||
return self._execute(self._command, timeout) | ||
|
||
def _execute(self, command, timeout): | ||
'''really execute the command, checking the return value''' | ||
__logger__.debug('Running (%d): %s', timeout, self.__str__()) | ||
assert len(command) > 0 | ||
try: | ||
self._start = stop = time.time() | ||
proc = subprocess.Popen(command, stdout=subprocess.PIPE, | ||
stderr=subprocess.PIPE) | ||
|
||
#now we create a watchdog | ||
deadline = self._start+timeout | ||
poll_seconds = .250 | ||
while stop < deadline and proc.poll() == None: | ||
time.sleep(poll_seconds) | ||
stop = time.time() | ||
|
||
if proc.poll() == None: | ||
__logger__.warn('%s timed out!', self.__str__()) | ||
if float(sys.version[:3]) >= 2.6: | ||
__logger__.debug('killing') | ||
proc.kill() | ||
return None | ||
self._duration = stop - self._start | ||
|
||
stdout, stderr = proc.communicate() | ||
except OSError as exc: | ||
__logger__.error('Error "%s" while executing', exc) | ||
stderr = str(exc) | ||
stdout = None | ||
proc = None | ||
|
||
if stderr: | ||
__logger__.warn('StdErr: %s', stderr) | ||
#TODO: return None ?? | ||
|
||
if not proc: | ||
__logger__.error('proc is None!') | ||
return None | ||
elif proc.returncode > 0: | ||
__logger__.error('Return Code is %s!', str(proc.returncode)) | ||
return None | ||
elif not stdout: | ||
__logger__.warn('stdout is None!') | ||
return None | ||
else: | ||
return stdout.splitlines() | ||
|
||
def __str__(self): | ||
return ' '.join(self._command) | ||
|
||
def unittest(): | ||
"""a small unit test for the class""" | ||
lggr = logging.getLogger() | ||
lggr.setLevel(logging.DEBUG) | ||
handler = logging.StreamHandler(stream=sys.stderr) | ||
handler.setLevel(logging.DEBUG) | ||
handler.setFormatter(logging.Formatter('[%(name)s.%(levelname)s] (%(filename)s.%(funcName)s): %(message)s')) | ||
lggr.addHandler(handler) | ||
|
||
cmd = RunCommand(['true'], 4) | ||
cmd.run() | ||
|
||
cmd = RunCommand(['false'], 4) | ||
cmd.run() | ||
|
||
cmd = RunCommand(['CmdNotFound'], 4) | ||
cmd.run() | ||
|
||
if __name__ == '__main__': | ||
unittest() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
#!/usr/bin/env python | ||
# vim: ts=4:sw=4:sts=4:tw=120:expandtab:fileencoding=utf-8 | ||
|
||
""" | ||
Package : scriptfilter | ||
Author(s) : Daniel Kriesten | ||
Email : daniel.kriesten@etit.tu-chemnitz.de | ||
Creation Date : Do 28 Aug 21:23:25 2014 | ||
""" | ||
|
||
import sys | ||
import find_bg_images as fbg | ||
|
||
__BG_BASEDIR__ = fbg.__BG_BASEDIR__ | ||
__THE_FILTER__ = "{query}" | ||
|
||
if __name__ == "__main__": | ||
__retval__ = fbg.find_files(__BG_BASEDIR__.replace(" ", r"\ "), __THE_FILTER__) | ||
if __retval__ != None: | ||
sys.stdout.write(__retval__) |
Binary file not shown.