repo
string | commit
string | message
string | diff
string |
---|---|---|---|
JoseBlanca/psubprocess
|
398f0c1b00e9dfd59b6331e6925bb279ca34c188
|
The prunner works now. We're able to launch parallel jobs.
|
diff --git a/psubprocess/condor_runner.py b/psubprocess/condor_runner.py
index 51dd32b..efdd4d5 100644
--- a/psubprocess/condor_runner.py
+++ b/psubprocess/condor_runner.py
@@ -1,259 +1,260 @@
'''It launches processes using Condor with an interface similar to Popen
Created on 14/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
from tempfile import NamedTemporaryFile
import subprocess, signal, os.path
from psubprocess.streams import get_streams_from_cmd
def call(cmd, env=None, stdin=None):
'It calls a command and it returns stdout, stderr and retcode'
def subprocess_setup():
''' Python installs a SIGPIPE handler by default. This is usually not
what non-Python subprocesses expect. Taken from this url:
http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009/07/02#
2009-07-02-python-sigpipe'''
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
if stdin is None:
pstdin = None
else:
pstdin = subprocess.PIPE
process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=env, stdin=pstdin,
preexec_fn=subprocess_setup)
if stdin is None:
stdout, stderr = process.communicate()
else:
# a = stdin.read()
# print a
# stdout, stderr = subprocess.Popen.stdin = stdin
# print stdin.read()
stdout, stderr = process.communicate(stdin)
retcode = process.returncode
return stdout, stderr, retcode
def write_condor_job_file(fhand, parameters):
'It writes a condor job file using the given fhand'
to_print = 'Executable = %s\nArguments = "%s"\nUniverse = vanilla\n' % \
(parameters['executable'], parameters['arguments'])
fhand.write(to_print)
to_print = 'Log = %s\n' % parameters['log_file'].name
fhand.write(to_print)
if parameters['transfer_files']:
to_print = 'When_to_transfer_output = ON_EXIT\n'
fhand.write(to_print)
to_print = 'Getenv = True\n'
fhand.write(to_print)
to_print = 'Transfer_executable = %s\n' % parameters['transfer_executable']
fhand.write(to_print)
if 'input_fnames' in parameters and parameters['input_fnames']:
ins = ','.join(parameters['input_fnames'])
to_print = 'Transfer_input_files = %s\n' % ins
fhand.write(to_print)
if parameters['transfer_files']:
to_print = 'Should_transfer_files = IF_NEEDED\n'
fhand.write(to_print)
if 'stdout' in parameters:
to_print = 'Output = %s\n' % parameters['stdout'].name
fhand.write(to_print)
if 'stderr' in parameters:
to_print = 'Error = %s\n' % parameters['stderr'].name
fhand.write(to_print)
if 'stdin' in parameters:
to_print = 'Input = %s\n' % parameters['stdin'].name
fhand.write(to_print)
to_print = 'Queue\n'
fhand.write(to_print)
fhand.flush()
class Popen(object):
'It launches and controls a condor job'
def __init__(self, cmd, cmd_def=None, runner_conf=None,
stdout=None, stderr=None, stdin=None):
'It launches a condor job'
if cmd_def is None:
cmd_def = []
#runner conf
if runner_conf is None:
runner_conf = {}
#some defaults
if 'transfer_files' not in runner_conf:
runner_conf['transfer_files'] = True
self._log_file = NamedTemporaryFile(suffix='.log')
#create condor job file
condor_job_file = self._create_condor_job_file(cmd, cmd_def,
self._log_file,
runner_conf,
stdout, stderr, stdin)
self._condor_job_file = condor_job_file
#launch condor
self._retcode = None
self._cluster_number = None
self._launch_condor(condor_job_file)
def _launch_condor(self, condor_job_file):
'Given the condor_job_file it launches the condor job'
stdout, stderr, retcode = call(['condor_submit', condor_job_file.name])
if retcode:
msg = 'There was a problem with condor_submit: ' + stderr
raise RuntimeError(msg)
#the condor cluster number is given by condor_submit
#1 job(s) submitted to cluster 15.
for line in stdout.splitlines():
if 'submitted to cluster' in line:
self._cluster_number = line.strip().strip('.').split()[-1]
def _get_pid(self):
'It returns the condor cluster number'
return self._cluster_number
pid = property(_get_pid)
def _get_returncode(self):
'It returns the return code'
return self._retcode
returncode = property(_get_returncode)
@staticmethod
def _remove_paths_from_cmd(cmd, streams, conf):
'''It removes the absolute and relative paths from the cmd,
it returns the modified cmd'''
cmd_mod = cmd[:]
for stream in streams:
if 'fname' not in stream:
continue
fpath = stream['fname']
#for the output files we can't deal with transfering files with
#paths. Condor will deliver those files into the initialdir, not
#where we expected.
if (stream['io'] != 'in' and conf['transfer_files']
and os.path.split(fpath)[-1] != fpath):
msg = 'output files with paths are not transferable'
raise ValueError(msg)
index = cmd_mod.index(fpath)
fpath = os.path.split(fpath)[-1]
cmd_mod[index] = fpath
return cmd_mod
def _create_condor_job_file(self, cmd, cmd_def, log_file, runner_conf,
stdout, stderr, stdin):
'Given a cmd and the cmd_def it returns the condor job file'
#streams
- streams = get_streams_from_cmd(cmd, cmd_def)
+ streams = get_streams_from_cmd(cmd, cmd_def, stdout=stdout,
+ stderr=stderr, stdin=stdin)
#we need some parameters to write the condor file
parameters = {}
parameters['executable'] = cmd[0]
parameters['log_file'] = log_file
#the cmd shouldn't have absolute path in the files because they will be
#transfered to another node in the condor working dir and they wouldn't
#be found with an absolute path
cmd_no_path = self._remove_paths_from_cmd(cmd, streams, runner_conf)
parameters['arguments'] = ' '.join(cmd_no_path[1:])
if stdout is not None:
parameters['stdout'] = stdout
if stderr is not None:
parameters['stderr'] = stderr
if stdin is not None:
parameters['stdin'] = stdin
transfer_bin = False
if 'transfer_executable' in runner_conf:
transfer_bin = runner_conf['transfer_executable']
parameters['transfer_executable'] = str(transfer_bin)
transfer_files = runner_conf['transfer_executable']
parameters['transfer_files'] = str(transfer_files)
in_fnames = []
for stream in streams:
if stream['io'] == 'in':
fname = None
if 'fname' in stream:
fname = stream['fname']
else:
fname = stream['fhand'].name
in_fnames.append(fname)
parameters['input_fnames'] = in_fnames
#now we can create the job file
condor_job_file = NamedTemporaryFile()
write_condor_job_file(condor_job_file, parameters=parameters)
return condor_job_file
def _update_retcode(self):
'It updates the retcode looking at the log file, it returns the retcode'
for line in open(self._log_file.name):
if 'return value' in line:
ret = line.split('return value')[1].strip().strip(')')
self._retcode = int(ret)
return self._retcode
def poll(self):
'It checks if condor has run ower condor cluster'
cluster_number = self._cluster_number
cmd = ['condor_q', cluster_number,
'-format', '"%d.\n"', 'ClusterId']
stdout, stderr, retcode = call(cmd)
if retcode:
msg = 'There was a problem with condor_q: ' + stderr
raise RuntimeError(msg)
if cluster_number not in stdout:
#the job is finished
return self._update_retcode()
return self._retcode
def wait(self):
'It waits until the condor job is finished'
stderr, retcode = call(['condor_wait', self._log_file.name])[1:]
if retcode:
msg = 'There was a problem with condor_wait: ' + stderr
raise RuntimeError(msg)
return self._update_retcode()
def kill(self):
'It runs condor_rm for the condor job'
stderr, retcode = call(['condor_rm', self.pid])[1:]
if retcode:
msg = 'There was a problem with condor_rm: ' + stderr
raise RuntimeError(msg)
return self._update_retcode()
def terminate(self):
'It runs condor_rm for the condor job'
self.kill()
def get_default_splits():
'It returns a suggested number of splits for this Popen runner'
stdout, stderr, retcode = call(['condor_status', '-total'])
if retcode:
msg = 'There was a problem with condor_status: ' + stderr
raise RuntimeError(msg)
for line in stdout.splitlines():
line = line.strip().lower()
if line.startswith('total') and 'owner' not in line:
return int(line.split()[1]) * 2
diff --git a/psubprocess/prunner.py b/psubprocess/prunner.py
index 51aca48..4ce511d 100644
--- a/psubprocess/prunner.py
+++ b/psubprocess/prunner.py
@@ -1,567 +1,573 @@
'''It launches parallel processes with an interface similar to Popen.
It divides jobs into subjobs and launches the subjobs.
Created on 16/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
from subprocess import Popen as StdPopen
import os, tempfile, shutil, copy
from psubprocess.streams import get_streams_from_cmd, STDOUT, STDERR, STDIN
from psubprocess import condor_runner
-RUNNER_MODULES ={}
+RUNNER_MODULES = {}
RUNNER_MODULES['condor_runner'] = condor_runner
class NamedTemporaryDir(object):
'''This class creates temporary directories '''
#pylint: disable-msg=W0622
#we redifine the build in dir because temfile uses that inteface
def __init__(self, dir=None):
'''It initiates the class.'''
self._name = tempfile.mkdtemp(dir=dir)
def get_name(self):
'Returns path to the dict'
return self._name
name = property(get_name)
def close(self):
'''It removes the temp dir'''
if os.path.exists(self._name):
shutil.rmtree(self._name)
def __del__(self):
'''It removes de temp dir when instance is removed and the garbaje
colector decides it'''
self.close()
def NamedTemporaryFile(dir=None, delete=False, suffix=''):
'''It creates a temporary file that won't be deleted when close
This behaviour can be done with tempfile.NamedTemporaryFile in python > 2.6
'''
#pylint: disable-msg=W0613
#delete is not being used, it's there as a reminder, once we start to use
#python 2.6 this function should be removed
#pylint: disable-msg=C0103
#pylint: disable-msg=W0622
#We want to mimick tempfile.NamedTemporaryFile
fpath = tempfile.mkstemp(dir=dir, suffix=suffix)[1]
return open(fpath, 'w')
def _calculate_divisions(num_items, splits):
'''It calculates how many items should be in every split to divide
the num_items into splits.
Not all splits will have an equal number of items, it will return a tuple
with two tuples inside:
((num_fragments_1, num_items_1), (num_fragments_2, num_items_2))
splits = num_fragments_1 + num_fragments_2
num_items_1 = num_items_2 + 1
num_fragments_1 could be equal to 0.
This is the best way to create as many splits as possible as similar as
possible.
'''
if splits >= num_items:
return ((0, 1), (splits, 1))
num_fragments1 = num_items % splits
num_fragments2 = splits - num_fragments1
num_items2 = num_items // splits
num_items1 = num_items2 + 1
res = ((num_fragments1, num_items1), (num_fragments2, num_items2))
return res
def _items_in_file(fhand, expression_kind, expression):
'''Given an fhand and an expression it yields the items cutting where the
line matches the expression'''
sofar = fhand.readline()
for line in fhand:
if ((expression_kind == 'str' and expression in line) or
expression.search(line)):
yield sofar
sofar = line
else:
sofar += line
else:
#the last item
yield sofar
def _create_file_splitter_with_re(expression):
'''Given an expression it creates a file splitter.
The expression can be a regex or an str.
The item in the file will be defined everytime a line matches the
expression.
'''
expression_kind = None
if isinstance(expression, str):
expression_kind = 'str'
else:
expression_kind = 're'
def splitter(file_, work_dirs):
'''It splits the given file into several splits.
Every split will be located in one of the work_dirs, although it is not
guaranteed to create as many splits as work dirs. If in the file there
are less items than work_dirs some work_dirs will be left empty.
It returns a list with the fpaths or fhands for the splitted files.
file_ can be an fhand or an fname.
'''
#the file_ can be an fname or an fhand. which one is it?
file_is_str = None
if isinstance(file_, str):
fname = file_
file_is_str = True
else:
fname = file_.name
file_is_str = False
#how many splits do we want?
nsplits = len(work_dirs)
#how many items are in the file? We assume that all files have the same
#number of items
nitems = 0
for line in open(fname, 'r'):
if ((expression_kind == 'str' and expression in line) or
expression.search(line)):
nitems += 1
#how many splits a we going to create? and how many items will be in
#every split
#if there are more items than splits we create as many splits as items
if nsplits > nitems:
nsplits = nitems
(nsplits1, nitems1), (nsplits2, nitems2) = _calculate_divisions(nitems,
nsplits)
#we have to create nsplits1 files with nitems1 in it and nsplits2 files
#with nitems2 items in it
new_files = []
fhand = open(fname, 'r')
items = _items_in_file(fhand, expression_kind, expression)
splits_made = 0
for nsplits, nitems in ((nsplits1, nitems1), (nsplits2, nitems2)):
#we have to create nsplits files with nitems in it
#we don't need the split_index for anything
#pylint: disable-msg=W0612
for split_index in range(nsplits):
suffix = os.path.splitext(fname)[-1]
work_dir = work_dirs[splits_made]
ofh = NamedTemporaryFile(dir=work_dir.name, delete=False,
suffix=suffix)
for item_index in range(nitems):
ofh.write(items.next())
ofh.flush()
if file_is_str:
new_files.append(ofh.name)
ofh.close()
else:
new_files.append(ofh)
splits_made += 1
return new_files
return splitter
def _output_splitter(file_, work_dirs):
'''It creates one output file for every splits.
Every split will be located in one of the work_dirs.
It returns a list with the fpaths for the new output files.
'''
#the file_ can be an fname or an fhand. which one is it?
file_is_str = None
if isinstance(file_, str):
fname = file_
file_is_str = True
else:
fname = file_.name
file_is_str = False
#how many splits do we want?
nsplits = len(work_dirs)
new_fpaths = []
#we have to create nsplits
for split_index in range(nsplits):
suffix = os.path.splitext(fname)[-1]
work_dir = work_dirs[split_index]
#we use delete=False because this temp file is in a temp dir that will
#be completely deleted. If we use delete=True we get an error because
#the file might be already deleted when its __del__ method is called
ofh = NamedTemporaryFile(dir=work_dir.name, suffix=suffix,
delete=False)
#the file will be deleted
#what do we need the fname or the fhand?
if file_is_str:
#it will be deleted because we just need the name in the temporary
#directory. tempfile.mktemp would be better for this use, but it is
#deprecated
new_fpaths.append(ofh.name)
ofh.close()
else:
new_fpaths.append(ofh)
return new_fpaths
def default_cat_joiner(out_file_, in_files_):
'''It joins the given in files into the given out file.
It works with fnames or fhands.
'''
#are we working with fhands or fnames?
file_is_str = None
if isinstance(out_file_, str):
file_is_str = True
else:
file_is_str = False
#the output fhand
if file_is_str:
out_fhand = open(out_file_, 'w')
else:
out_fhand = open(out_file_.name, 'w')
for in_file_ in in_files_:
#the input fhand
if file_is_str:
in_fhand = open(in_file_, 'r')
else:
in_fhand = open(in_file_.name, 'r')
for line in in_fhand:
out_fhand.write(line)
in_fhand.close()
out_fhand.close()
class Popen(object):
'It paralellizes the given processes divinding them into subprocesses.'
- def __init__(self, cmd, cmd_def=None, runner=None, stdout=None, stderr=None,
- stdin=None, splits=None):
+ def __init__(self, cmd, cmd_def=None, runner=None, runner_conf=None,
+ stdout=None, stderr=None, stdin=None, splits=None):
'''
Constructor
'''
#we want the same interface as subprocess.popen
#pylint: disable-msg=R0913
self._retcode = None
self._outputs_collected = False
#some defaults
#if the runner is not given, we use subprocess.Popen
if runner is None:
runner = StdPopen
if cmd_def is None:
if stdin is not None:
raise ValueError('No cmd_def given but stdin present')
cmd_def = []
#if the number of splits is not given we calculate them
if splits is None:
splits = self.default_splits(runner)
#we need a work dir to create the temporary split files
self._work_dir = NamedTemporaryDir()
#the main job
self._job = {'cmd': cmd, 'work_dir': self._work_dir}
#we create the new subjobs
self._jobs = self._split_jobs(cmd, cmd_def, splits, self._work_dir,
stdout=stdout, stderr=stderr, stdin=stdin)
#launch every subjobs
- self._launch_jobs(self._jobs, runner=runner)
+ self._launch_jobs(self._jobs, runner=runner, runner_conf=runner_conf)
@staticmethod
- def _launch_jobs(jobs, runner):
+ def _launch_jobs(jobs, runner, runner_conf):
'It launches all jobs and it adds its popen instance to them'
jobs['popens'] = []
cwd = os.getcwd()
for job_index, (cmd, streams, work_dir) in enumerate(zip(jobs['cmds'],
jobs['streams'], jobs['work_dirs'])):
#the std stream can be present or not
stdin, stdout, stderr = None, None, None
if jobs['stdins']:
stdin = jobs['stdins'][job_index]
if jobs['stdouts']:
stdout = jobs['stdouts'][job_index]
if jobs['stderrs']:
stderr = jobs['stderrs'][job_index]
#for every job we go to its dir to launch it
os.chdir(work_dir.name)
#we have to be sure that stdin is open for read
if stdin:
stdin = open(stdin.name)
#we launch the job
if runner == StdPopen:
popen = runner(cmd, stdout=stdout, stderr=stderr, stdin=stdin)
else:
popen = runner(cmd, cmd_def=streams, stdout=stdout,
- stderr=stderr, stdin=stdin)
+ stderr=stderr, stdin=stdin,
+ runner_conf=runner_conf)
#we record it's popen instane
jobs['popens'].append(popen)
os.chdir(cwd)
def _split_jobs(self, cmd, cmd_def, splits, work_dir, stdout=None,
stderr=None, stdin=None,):
''''I creates one job for every split.
Every job has a cmd, work_dir and streams, this info is in the jobs dict
with the keys: cmds, work_dirs, streams
'''
#too many arguments, but similar interface to our __init__
#pylint: disable-msg=R0913
#pylint: disable-msg=R0914
#the main job streams
main_job_streams = get_streams_from_cmd(cmd, cmd_def, stdout=stdout,
stderr=stderr, stdin=stdin)
self._job['streams'] = main_job_streams
streams, work_dirs = self._split_streams(main_job_streams, splits,
work_dir.name)
#now we have to create a new cmd with the right in and out streams for
#every split
cmds, stdins, stdouts, stderrs = self._create_cmds(cmd, streams)
jobs = {'cmds': cmds, 'work_dirs': work_dirs, 'streams': streams,
'stdins':stdins, 'stdouts':stdouts, 'stderrs':stderrs}
return jobs
@staticmethod
def _create_cmds(cmd, streams):
'''Given a base cmd and a steams list it creates one modified cmds for
every stream'''
#the streams is a list of streams
streamss = streams
cmds = []
stdouts = []
stdins = []
stderrs = []
for streams in streamss:
new_cmd = copy.deepcopy(cmd)
for stream in streams:
#is the stream in the cmd or in is a std one?
- location = stream['cmd_location']
+ if 'cmd_location' in stream:
+ location = stream['cmd_location']
+ else:
+ location = None
if location is None:
continue
elif location == STDIN:
stdins.append(stream['fhand'])
elif location == STDOUT:
stdouts.append(stream['fhand'])
elif location == STDERR:
stderrs.append(stream['fhand'])
else:
#we modify the cmd[location] with the new file
#we use the fname and no path because the jobs will be
#launched from the job working dir
location = stream['cmd_location']
fpath = stream['fname']
fname = os.path.split(fpath)[-1]
new_cmd[location] = fname
cmds.append(new_cmd)
return cmds, stdins, stdouts, stderrs
@staticmethod
def _split_streams(streams, splits, work_dir):
'''Given a list of streams it splits every stream in the given number of
splits'''
#which are the input and output streams?
input_stream_indexes = []
output_stream_indexes = []
for index, stream in enumerate(streams):
if stream['io'] == 'in':
input_stream_indexes.append(index)
elif stream['io'] == 'out':
output_stream_indexes.append(index)
#we create one work dir for every split
work_dirs = []
for index in range(splits):
work_dirs.append(NamedTemporaryDir(dir=work_dir))
#we have to do first the input files because the number of splits could
#be changed by them
#we split the input stream files into several splits
#we have to sort the input_stream_indexes, first we should take the ones
#that have an input file to be split
def to_be_split_first(stream1, stream2):
'It sorts the streams, the ones to be split go first'
split1 = None
split2 = None
for split, stream in ((split1, stream1), (split2, stream2)):
#maybe they shouldn't be split
if 'special' in stream and 'no_split' in stream['special']:
split = False
#maybe the have no file to split
if (('fhand' in stream and stream['fhand'] is None) or
('fname' in stream and stream['fname'] is None) or
('fname' not in stream and 'fhand' not in stream)):
split = False
elif (('fhand' in stream and stream['fhand'] is not None) or
('fname' in stream and stream['fname'] is not None)):
split = True
return int(split1) - int(split2)
input_stream_indexes = sorted(input_stream_indexes, to_be_split_first)
first = True
split_files = {}
for index in input_stream_indexes:
stream = streams[index]
#splitter
if 'splitter' not in stream:
msg = 'An splitter should be provided for every input stream'
msg += 'missing for: ' + str(stream)
raise ValueError(msg)
splitter = stream['splitter']
#the splitter can be a re, in that case with create the function
if '__call__' not in dir(splitter):
splitter = _create_file_splitter_with_re(splitter)
#we split the input files in the splits, every file will be in one
#of the given work_dirs
#the stream can have fname or fhands
if 'fhand' in stream:
file_ = stream['fhand']
- else:
+ elif 'fname' in stream:
file_ = stream['fname']
+ else:
+ file_ = None
if file_ is None:
#the stream migth have no file associated
files = [None] * len(work_dirs)
else:
files = splitter(file_, work_dirs)
#the files len can be different than splits, in that case we modify
#the splits or we raise an error
if len(files) != splits:
if first:
splits = len(files)
#we discard the empty temporary dirs
work_dirs = work_dirs[0:splits]
else:
msg = 'Not all input files were divided in the same number'
msg += ' of splits'
raise RuntimeError(msg)
first = False
split_files[index] = files #a list of files for every in stream
#we split the ouptut stream files into several splits
for index in output_stream_indexes:
stream = streams[index]
#for th output we just create the new names, but we don't split
#any file
if 'fhand' in stream:
fname = stream['fhand']
else:
fname = stream['fname']
files = _output_splitter(fname, work_dirs)
split_files[index] = files #a list of files for every in stream
new_streamss = []
#we need one new stream for every split
for split_index in range(splits):
#the streams for one job
new_streams = []
for stream_index, stream in enumerate(streams):
#we duplicate the original stream
new_stream = stream.copy()
#we set the new files
if 'fhand' in stream:
new_stream['fhand'] = split_files[stream_index][split_index]
else:
new_stream['fname'] = split_files[stream_index][split_index]
new_streams.append(new_stream)
new_streamss.append(new_streams)
return new_streamss, work_dirs
@staticmethod
def default_splits(runner):
'Given a runner it returns the number of splits recommended by default'
if runner is StdPopen:
#the number of processors
return os.sysconf('SC_NPROCESSORS_ONLN')
else:
module = runner.__module__.split('.')[-1]
module = RUNNER_MODULES[module]
return module.get_default_splits()
def wait(self):
'It waits for all the works to finnish'
#we wait till all jobs finish
for job in self._jobs['popens']:
job.wait()
#now that all jobs have finished we join the results
self._collect_output_streams()
#we join now the retcodes
self._collect_retcodes()
return self._retcode
def _collect_output_streams(self):
'''It joins all the output streams into the output files and it removes
the work dirs'''
if self._outputs_collected:
return
#for each file in the main job cmd
for stream_index, stream in enumerate(self._job['streams']):
if stream['io'] == 'in':
#now we're dealing only with output files
continue
#every subjob has a part to join for this output stream
part_out_fnames = []
for streams in self._jobs['streams']:
this_stream = streams[stream_index]
if 'fname' in this_stream:
part_out_fnames.append(this_stream['fname'])
else:
part_out_fnames.append(this_stream['fhand'])
#we need a function to join this stream
joiner = None
if joiner in stream:
joiner = stream['joiner']
else:
joiner = default_cat_joiner
if 'fname' in stream:
out_file = stream['fname']
else:
out_file = stream['fhand']
default_cat_joiner(out_file, part_out_fnames)
#now we can delete the tempdirs
for work_dir in self._jobs['work_dirs']:
work_dir.close()
self._outputs_collected = True
def _collect_retcodes(self):
'It gathers the retcodes from all processes'
retcode = None
for popen in self._jobs['popens']:
job_retcode = popen.returncode
if job_retcode is None:
#if some job is yet to be finished the main job is not finished
retcode = None
break
elif job_retcode != 0:
#if one job has finnished badly the main job is badly finished
retcode = job_retcode
break
#it should be 0 at this point
retcode = job_retcode
#if the retcode is not None the jobs have finished and we have to
#collect the outputs
if retcode is not None:
self._collect_output_streams()
self._retcode = retcode
return retcode
def _get_returncode(self):
'It returns the return code'
if self._retcode is None:
self._collect_retcodes()
return self._retcode
returncode = property(_get_returncode)
\ No newline at end of file
diff --git a/psubprocess/streams.py b/psubprocess/streams.py
index 4191f64..32b7016 100644
--- a/psubprocess/streams.py
+++ b/psubprocess/streams.py
@@ -1,109 +1,123 @@
'''
Created on 13/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of project.
# project is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# project 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with project. If not, see <http://www.gnu.org/licenses/>.
STDIN = 'stdin'
STDOUT = 'stdout'
STDERR = 'stderr'
def _find_param_def_in_cmd(cmd, param_def):
'''Given a cmd and a parameter definition it returns the index of the param
in the cmd.
If the param is not found in the cmd it will raise a ValueError.
'''
options = param_def['options']
#options could be a list or an item
if not isinstance(options, list) and not isinstance(options, tuple):
options = (options,)
#the standard options with command line options
for index, item in enumerate(cmd):
if item in options:
return index
raise ValueError('Parameter not found in the given cmd')
def _positive_int(index, sequence):
'''It returns the same int index, but positive.'''
if index is None:
return None
elif index < 0:
return len(sequence) + index
return index
+def _add_std_cmd_defs(cmd_def, stdout, stdin, stderr):
+ '''It adds the standard stream to the cmd_def.
+
+ If they're already there it just completes them
+ '''
+ #which std streams are in the cmd_def?
+ in_cmd_def = {}
+ for param_def in cmd_def:
+ option = param_def['options']
+ if option in (STDOUT, STDIN, STDERR):
+ in_cmd_def[option] = True
+ #we create the missing ones
+ if stdout is not None and STDOUT not in in_cmd_def:
+ cmd_def.append({'options':STDOUT, 'io':'out'})
+ if stderr is not None and STDERR not in in_cmd_def:
+ cmd_def.append({'options':STDERR, 'io':'out'})
+ if stdin is not None and STDIN not in in_cmd_def:
+ cmd_def.append({'options':STDIN, 'io':'in'})
+
def get_streams_from_cmd(cmd, cmd_def, stdout=None, stdin=None, stderr=None):
'Given a cmd and a cmd definition it returns the streams'
+ #stdout and stderr might not be in the cmd_def
+ _add_std_cmd_defs(cmd_def, stdout=stdout, stdin=stdin, stderr=stderr)
+
+
streams = []
for param_def in cmd_def:
options = param_def['options']
- stream_values = None
#where is this stream located in the cmd?
location = None
#we have to look for the stream in the cmd
#where is the parameter in the cmd list?
#if the param options is not an int, its a list of strings
if isinstance(options, int):
#for PRE_ARG (1) and POST_ARG (-1)
#we take 1 unit because the options should be 1 to the right
#of the value
index = _positive_int(options, cmd) - 1
- elif options == STDIN:
- index = STDIN
+ elif options in (STDERR, STDOUT, STDIN):
+ index = options
else:
#look for param in cmd
try:
index = _find_param_def_in_cmd(cmd, param_def)
except ValueError:
index = None
- #get the stream values
- if index == STDIN:
+ if index == STDERR:
+ location = STDERR
+ fname = stderr
+ elif index == STDOUT:
+ location = STDOUT
+ fname = stdout
+ elif index == STDIN:
location = STDIN
- stream_values = stdin
+ fname = stdin
elif index is not None:
location = index + 1
- stream_values = cmd[location]
+ fname = cmd[location]
#create the result dict
stream = param_def.copy()
- if location is STDIN:
- stream['fhand'] = stream_values
- else:
- stream['fname'] = stream_values
- stream['cmd_location'] = location
- streams.append(stream)
- #We have to add also the stdout and stderr
- for stream_name, fhand in ((STDOUT, stdout), (STDERR, stderr)):
- if fhand is None:
- continue
- io_value = None
- if stream_name == STDIN:
- io_value = 'in'
- else:
- io_value = 'out'
- stream = {}
- stream['fhand'] = fhand
- stream['io'] = io_value
- stream['cmd_location'] = stream_name
+ if location is not None:
+ if location in (STDIN, STDOUT, STDERR):
+ stream['fhand'] = fname
+ else:
+ stream['fname'] = fname
+ stream['cmd_location'] = location
streams.append(stream)
return streams
\ No newline at end of file
diff --git a/test/cmd_def_test.py b/test/cmd_def_test.py
index 1faffd7..35c3fb6 100644
--- a/test/cmd_def_test.py
+++ b/test/cmd_def_test.py
@@ -1,150 +1,157 @@
'''
Created on 13/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
import unittest
from psubprocess.streams import (get_streams_from_cmd,
STDIN, STDOUT, STDERR)
#What's a stream
#
#A command takes some input streams and creates some ouput streams
#An stream is a file-like object or a directory. In fact an stream can be
#composed by several files (e.g. a seq and a qual file that should be splitted
#together)
#
#Kinds of streams in a cmd
#cmd arg1 arg2 -i opt1 opt2 -j opt3 arg3 < stdin > stdout stderr retcode
#in this general command there are several types of streams:
# - previous arguments. arguments (without options) located before the first
# option (like arg1 and arg2)
# - options with one option, like opt3
# - options with several arguments, like -i that has opt1 and opt2
# - arguments (aka post_arguments). arguments located after the last option
# - stdin, stdout, stderr and retcode. The standard ones.
#
#How to define the streams
#An stream is defined by a dict with the following keys: options, io, splitter,
#value, special, location. All of them are optional except the options.
#Options: It defines in which options or arguments is the stream found. It
#should by just a value or a tuple.
#Options kinds:
# - -i the stream will be located after the parameter -i
# - (-o, --output) the stream will be after -o or --output
# - PRE_ARG right after the cmd and before the first parameter
# - POST_ARG after the last option
# - STDIN
# - STDOUT
# - STDERR
#io: It defines if it's an input or an output stream for the cmd
#splitter: It defines how the stream should be split. There are three ways of
#definint it:
# - an str that will be used to scan through the in streams, every
# line with the str in in will be considered a token start
# e.g '>' for the blast files
# - a re every line with a match will be considered a token start
# - a function the function should take the stream an return an
# iterator with the tokens
#joiner: A function that should take the out streams for all jobs and return
#the joined stream. If not given the output stream will be just concatenated.
#value: the value for the stream, this stream will not define the value in the
#command line, it will be implicit
#special: It defines some special treaments for the streams.
# - no_split It shouldn't be split
# - no_transfer It shouldn't be transfer to all nodes
# - no_abspath Its path shouldn't be converted to absolute
# - create It should be created before running the command
# - no_support An error should be raised if used.
#cmd_locations: If the location is not given the assumed location will be 0.
#That means that the stream will be located in the 0 position after the option.
#It can be either an int or an slice. In the slice case several substreams will
#be taken together in the stream. Useful for instance for the case of two fasta
#files with the seq an qual that should be split together and transfered
#together.
def _check_streams(streams, expected_streams):
'It checks that streams meet the requirements set by the expected streams'
for stream, expected_stream in zip(streams, expected_streams):
for key in expected_stream:
assert stream[key] == expected_stream[key]
class StreamsFromCmdTest(unittest.TestCase):
'It tests that we can get the input and output files from the cmd'
@staticmethod
def test_simple_case():
'It tests the most simple cases'
#a simple case
cmd = ['hola', '-i', 'caracola.txt']
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'}]
expected_streams = [{'fname': 'caracola.txt', 'io':'in',
'cmd_location':2}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
#a parameter not found in the cmd
cmd = ['hola', '-i', 'caracola.txt']
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
{'options': ('-j', '--input2'), 'io': 'in'}]
expected_streams = [{'fname': 'caracola.txt', 'io':'in',
'cmd_location': 2}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
@staticmethod
def test_arguments():
'It test that it works with cmd arguments, not options'
#the options we want is in the pre_argv, after the binary
cmd = ['hola', 'hola.txt', '-i', 'caracola.txt']
cmd_def = [{'options': 1, 'io': 'in'}]
expected_streams = [{'fname': 'hola.txt', 'io':'in',
'cmd_location':1}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
#the option we want is at the end of the cmd
cmd = ['hola', '-i', 'caracola.txt', 'hola.txt']
cmd_def = [{'options': -1, 'io': 'in'}]
expected_streams = [{'fname': 'hola.txt', 'io':'in',
'cmd_location':3}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
@staticmethod
def test_stdin():
'We want stdin, stdout and stderr as streams'
#stdin
cmd = ['hola']
- cmd_def = [{'options':STDIN, 'io': 'in'}]
+ cmd_def = [{'options':STDIN, 'io': 'in'},
+ {'options':STDOUT, 'io': 'out'}]
stdout = 'stdout' #in the real world they will be files
stderr = 'stderr'
stdin = 'stdin'
- expected_streams = [{'fhand': stdin, 'io':'in', 'cmd_location':STDIN},
- {'fhand': stdout, 'io':'out', 'cmd_location':STDOUT},
- {'fhand': stderr, 'io':'out', 'cmd_location':STDERR}]
+ expected_streams = [{'fhand': stdin, 'io':'in', 'cmd_location':STDIN,
+ 'options': stdin},
+ {'fhand': stdout, 'io':'out', 'cmd_location':STDOUT,
+ 'options':stdout},
+ {'fhand': stderr, 'io':'out', 'cmd_location':STDERR,
+ 'options':stderr}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def, stdout=stdout,
stderr=stderr, stdin=stdin)
_check_streams(streams, expected_streams)
+ assert 'fname' not in streams[0]
+ assert 'fname' not in streams[1]
+ assert 'fname' not in streams[2]
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
\ No newline at end of file
diff --git a/test/prunner_test.py b/test/prunner_test.py
index 60b85b0..7330e85 100644
--- a/test/prunner_test.py
+++ b/test/prunner_test.py
@@ -1,152 +1,154 @@
'''
Created on 16/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
import unittest
from tempfile import NamedTemporaryFile
import os
from psubprocess import Popen
from psubprocess.streams import STDIN
from test_utils import create_test_binary
class PRunnerTest(unittest.TestCase):
'It test that we can parallelize processes'
@staticmethod
def test_file_in():
'It tests the most basic behaviour'
bin = create_test_binary()
#with infile
in_file = NamedTemporaryFile()
in_file.write('hola')
in_file.flush()
cmd = [bin]
cmd.extend(['-i', in_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''}]
popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def)
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(stdout.name).read() == 'hola'
in_file.close()
os.remove(bin)
@staticmethod
def test_job_no_in_stream():
'It test that a job with no in stream is run splits times'
bin = create_test_binary()
cmd = [bin]
cmd.extend(['-o', 'hola', '-e', 'caracola'])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''}]
splits = 4
popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def,
splits=splits)
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(stdout.name).read() == 'hola' * splits
assert open(stderr.name).read() == 'caracola' * splits
os.remove(bin)
@staticmethod
def test_stdin():
'It test that stdin works as input'
bin = create_test_binary()
#with stdin
content = 'hola1\nhola2\nhola3\nhola4\nhola5\nhola6\nhola7\nhola8\n'
content += 'hola9\nhola10|n'
stdin = NamedTemporaryFile()
stdin.write(content)
stdin.flush()
cmd = [bin]
cmd.extend(['-s'])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options':STDIN, 'io': 'in', 'splitter':''}]
popen = Popen(cmd, stdout=stdout, stderr=stderr, stdin=stdin,
cmd_def=cmd_def)
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(stdout.name).read() == content
assert open(stderr.name).read() == ''
os.remove(bin)
@staticmethod
def test_infile_outfile():
'It tests that we can set an input file and an output file'
bin = create_test_binary()
#with infile
in_file = NamedTemporaryFile()
content = 'hola1\nhola2\nhola3\nhola4\nhola5\nhola6\nhola7\nhola8\n'
content += 'hola9\nhola10|n'
in_file.write(content)
in_file.flush()
out_file = NamedTemporaryFile()
cmd = [bin]
cmd.extend(['-i', in_file.name, '-t', out_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''},
{'options': ('-t', '--output'), 'io': 'out'}]
popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def)
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert not open(stdout.name).read()
assert not open(stderr.name).read()
assert open(out_file.name).read() == content
in_file.close()
os.remove(bin)
@staticmethod
def test_infile_outfile_condor():
'It tests that we can set an input file and an output file'
bin = create_test_binary()
#with infile
in_file = NamedTemporaryFile()
content = 'hola1\nhola2\nhola3\nhola4\nhola5\nhola6\nhola7\nhola8\n'
content += 'hola9\nhola10|n'
in_file.write(content)
in_file.flush()
out_file = NamedTemporaryFile()
cmd = [bin]
cmd.extend(['-i', in_file.name, '-t', out_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''},
{'options': ('-t', '--output'), 'io': 'out'}]
from psubprocess import CondorPopen
popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def,
- runner=CondorPopen)
+ runner=CondorPopen,
+ runner_conf={'transfer_executable':True})
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert not open(stdout.name).read()
assert not open(stderr.name).read()
assert open(out_file.name).read() == content
in_file.close()
os.remove(bin)
+ #TODO test retcode
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
\ No newline at end of file
|
JoseBlanca/psubprocess
|
ce47b3424c6ed69d794f07ec10cbb5b6e5e37961
|
A lot of bugfixes, but more to go.
|
diff --git a/psubprocess/condor_runner.py b/psubprocess/condor_runner.py
index ae94bba..51dd32b 100644
--- a/psubprocess/condor_runner.py
+++ b/psubprocess/condor_runner.py
@@ -1,241 +1,259 @@
'''It launches processes using Condor with an interface similar to Popen
Created on 14/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
from tempfile import NamedTemporaryFile
import subprocess, signal, os.path
from psubprocess.streams import get_streams_from_cmd
def call(cmd, env=None, stdin=None):
'It calls a command and it returns stdout, stderr and retcode'
def subprocess_setup():
''' Python installs a SIGPIPE handler by default. This is usually not
what non-Python subprocesses expect. Taken from this url:
http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009/07/02#
2009-07-02-python-sigpipe'''
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
if stdin is None:
pstdin = None
else:
pstdin = subprocess.PIPE
process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=env, stdin=pstdin,
preexec_fn=subprocess_setup)
if stdin is None:
stdout, stderr = process.communicate()
else:
# a = stdin.read()
# print a
# stdout, stderr = subprocess.Popen.stdin = stdin
# print stdin.read()
stdout, stderr = process.communicate(stdin)
retcode = process.returncode
return stdout, stderr, retcode
def write_condor_job_file(fhand, parameters):
'It writes a condor job file using the given fhand'
to_print = 'Executable = %s\nArguments = "%s"\nUniverse = vanilla\n' % \
(parameters['executable'], parameters['arguments'])
fhand.write(to_print)
to_print = 'Log = %s\n' % parameters['log_file'].name
fhand.write(to_print)
if parameters['transfer_files']:
to_print = 'When_to_transfer_output = ON_EXIT\n'
fhand.write(to_print)
to_print = 'Getenv = True\n'
fhand.write(to_print)
to_print = 'Transfer_executable = %s\n' % parameters['transfer_executable']
fhand.write(to_print)
if 'input_fnames' in parameters and parameters['input_fnames']:
ins = ','.join(parameters['input_fnames'])
to_print = 'Transfer_input_files = %s\n' % ins
fhand.write(to_print)
if parameters['transfer_files']:
to_print = 'Should_transfer_files = IF_NEEDED\n'
fhand.write(to_print)
if 'stdout' in parameters:
to_print = 'Output = %s\n' % parameters['stdout'].name
fhand.write(to_print)
if 'stderr' in parameters:
to_print = 'Error = %s\n' % parameters['stderr'].name
fhand.write(to_print)
if 'stdin' in parameters:
to_print = 'Input = %s\n' % parameters['stdin'].name
fhand.write(to_print)
to_print = 'Queue\n'
fhand.write(to_print)
fhand.flush()
class Popen(object):
'It launches and controls a condor job'
def __init__(self, cmd, cmd_def=None, runner_conf=None,
stdout=None, stderr=None, stdin=None):
'It launches a condor job'
if cmd_def is None:
cmd_def = []
#runner conf
if runner_conf is None:
runner_conf = {}
#some defaults
if 'transfer_files' not in runner_conf:
runner_conf['transfer_files'] = True
self._log_file = NamedTemporaryFile(suffix='.log')
#create condor job file
condor_job_file = self._create_condor_job_file(cmd, cmd_def,
self._log_file,
runner_conf,
stdout, stderr, stdin)
self._condor_job_file = condor_job_file
#launch condor
self._retcode = None
self._cluster_number = None
self._launch_condor(condor_job_file)
def _launch_condor(self, condor_job_file):
'Given the condor_job_file it launches the condor job'
stdout, stderr, retcode = call(['condor_submit', condor_job_file.name])
if retcode:
msg = 'There was a problem with condor_submit: ' + stderr
raise RuntimeError(msg)
#the condor cluster number is given by condor_submit
#1 job(s) submitted to cluster 15.
for line in stdout.splitlines():
if 'submitted to cluster' in line:
self._cluster_number = line.strip().strip('.').split()[-1]
def _get_pid(self):
'It returns the condor cluster number'
return self._cluster_number
pid = property(_get_pid)
def _get_returncode(self):
'It returns the return code'
return self._retcode
returncode = property(_get_returncode)
@staticmethod
def _remove_paths_from_cmd(cmd, streams, conf):
'''It removes the absolute and relative paths from the cmd,
it returns the modified cmd'''
cmd_mod = cmd[:]
for stream in streams:
- for fpath in stream['streams']:
- #for the output files we can't deal with transfering files with
- #paths. Condor will deliver those files into the initialdir, not
- #where we expected.
- if (stream['io'] != 'in' and conf['transfer_files']
- and os.path.split(fpath)[-1] != fpath):
- msg = 'output files with paths are not transferable'
- raise ValueError(msg)
-
- index = cmd_mod.index(fpath)
- fpath = os.path.split(fpath)[-1]
- cmd_mod[index] = fpath
+ if 'fname' not in stream:
+ continue
+ fpath = stream['fname']
+ #for the output files we can't deal with transfering files with
+ #paths. Condor will deliver those files into the initialdir, not
+ #where we expected.
+ if (stream['io'] != 'in' and conf['transfer_files']
+ and os.path.split(fpath)[-1] != fpath):
+ msg = 'output files with paths are not transferable'
+ raise ValueError(msg)
+
+ index = cmd_mod.index(fpath)
+ fpath = os.path.split(fpath)[-1]
+ cmd_mod[index] = fpath
return cmd_mod
def _create_condor_job_file(self, cmd, cmd_def, log_file, runner_conf,
stdout, stderr, stdin):
'Given a cmd and the cmd_def it returns the condor job file'
#streams
streams = get_streams_from_cmd(cmd, cmd_def)
#we need some parameters to write the condor file
parameters = {}
parameters['executable'] = cmd[0]
parameters['log_file'] = log_file
#the cmd shouldn't have absolute path in the files because they will be
#transfered to another node in the condor working dir and they wouldn't
#be found with an absolute path
cmd_no_path = self._remove_paths_from_cmd(cmd, streams, runner_conf)
parameters['arguments'] = ' '.join(cmd_no_path[1:])
if stdout is not None:
parameters['stdout'] = stdout
if stderr is not None:
parameters['stderr'] = stderr
if stdin is not None:
parameters['stdin'] = stdin
transfer_bin = False
if 'transfer_executable' in runner_conf:
transfer_bin = runner_conf['transfer_executable']
parameters['transfer_executable'] = str(transfer_bin)
transfer_files = runner_conf['transfer_executable']
parameters['transfer_files'] = str(transfer_files)
in_fnames = []
for stream in streams:
if stream['io'] == 'in':
- in_fnames.extend(stream['streams'])
+ fname = None
+ if 'fname' in stream:
+ fname = stream['fname']
+ else:
+ fname = stream['fhand'].name
+ in_fnames.append(fname)
parameters['input_fnames'] = in_fnames
#now we can create the job file
condor_job_file = NamedTemporaryFile()
write_condor_job_file(condor_job_file, parameters=parameters)
return condor_job_file
def _update_retcode(self):
'It updates the retcode looking at the log file, it returns the retcode'
for line in open(self._log_file.name):
if 'return value' in line:
ret = line.split('return value')[1].strip().strip(')')
self._retcode = int(ret)
return self._retcode
def poll(self):
'It checks if condor has run ower condor cluster'
cluster_number = self._cluster_number
cmd = ['condor_q', cluster_number,
'-format', '"%d.\n"', 'ClusterId']
stdout, stderr, retcode = call(cmd)
if retcode:
msg = 'There was a problem with condor_q: ' + stderr
raise RuntimeError(msg)
if cluster_number not in stdout:
#the job is finished
return self._update_retcode()
return self._retcode
def wait(self):
'It waits until the condor job is finished'
stderr, retcode = call(['condor_wait', self._log_file.name])[1:]
if retcode:
msg = 'There was a problem with condor_wait: ' + stderr
raise RuntimeError(msg)
return self._update_retcode()
def kill(self):
'It runs condor_rm for the condor job'
stderr, retcode = call(['condor_rm', self.pid])[1:]
if retcode:
msg = 'There was a problem with condor_rm: ' + stderr
raise RuntimeError(msg)
return self._update_retcode()
def terminate(self):
'It runs condor_rm for the condor job'
self.kill()
+
+def get_default_splits():
+ 'It returns a suggested number of splits for this Popen runner'
+ stdout, stderr, retcode = call(['condor_status', '-total'])
+ if retcode:
+ msg = 'There was a problem with condor_status: ' + stderr
+ raise RuntimeError(msg)
+ for line in stdout.splitlines():
+ line = line.strip().lower()
+ if line.startswith('total') and 'owner' not in line:
+ return int(line.split()[1]) * 2
diff --git a/psubprocess/prunner.py b/psubprocess/prunner.py
index 2b8ced7..51aca48 100644
--- a/psubprocess/prunner.py
+++ b/psubprocess/prunner.py
@@ -1,541 +1,567 @@
'''It launches parallel processes with an interface similar to Popen.
It divides jobs into subjobs and launches the subjobs.
Created on 16/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
from subprocess import Popen as StdPopen
import os, tempfile, shutil, copy
from psubprocess.streams import get_streams_from_cmd, STDOUT, STDERR, STDIN
+from psubprocess import condor_runner
+
+RUNNER_MODULES ={}
+RUNNER_MODULES['condor_runner'] = condor_runner
class NamedTemporaryDir(object):
'''This class creates temporary directories '''
#pylint: disable-msg=W0622
#we redifine the build in dir because temfile uses that inteface
def __init__(self, dir=None):
'''It initiates the class.'''
self._name = tempfile.mkdtemp(dir=dir)
def get_name(self):
'Returns path to the dict'
return self._name
name = property(get_name)
def close(self):
'''It removes the temp dir'''
if os.path.exists(self._name):
shutil.rmtree(self._name)
def __del__(self):
'''It removes de temp dir when instance is removed and the garbaje
colector decides it'''
self.close()
def NamedTemporaryFile(dir=None, delete=False, suffix=''):
'''It creates a temporary file that won't be deleted when close
This behaviour can be done with tempfile.NamedTemporaryFile in python > 2.6
'''
#pylint: disable-msg=W0613
#delete is not being used, it's there as a reminder, once we start to use
#python 2.6 this function should be removed
#pylint: disable-msg=C0103
#pylint: disable-msg=W0622
#We want to mimick tempfile.NamedTemporaryFile
fpath = tempfile.mkstemp(dir=dir, suffix=suffix)[1]
return open(fpath, 'w')
def _calculate_divisions(num_items, splits):
'''It calculates how many items should be in every split to divide
the num_items into splits.
Not all splits will have an equal number of items, it will return a tuple
with two tuples inside:
((num_fragments_1, num_items_1), (num_fragments_2, num_items_2))
splits = num_fragments_1 + num_fragments_2
num_items_1 = num_items_2 + 1
num_fragments_1 could be equal to 0.
This is the best way to create as many splits as possible as similar as
possible.
'''
if splits >= num_items:
return ((0, 1), (splits, 1))
num_fragments1 = num_items % splits
num_fragments2 = splits - num_fragments1
num_items2 = num_items // splits
num_items1 = num_items2 + 1
res = ((num_fragments1, num_items1), (num_fragments2, num_items2))
return res
-def _write_file(dir, contents, suffix, return_fname):
- '''It creates a new file with the given contents. It returns the path'''
- #pylint: disable-msg=W0622
- #we're redefining the built-in dir because is the clearest interface,
- #and because this interface is used by tempdir
- ofh = NamedTemporaryFile(dir=dir, delete=False, suffix=suffix)
- ofh.write(contents)
- ofh.flush()
- if return_fname:
- #the file won't be deleted, just closed,
- #it will be deleted because is created in a
- #temporary directory
- file_ = ofh.name
- ofh.close()
+def _items_in_file(fhand, expression_kind, expression):
+ '''Given an fhand and an expression it yields the items cutting where the
+ line matches the expression'''
+ sofar = fhand.readline()
+ for line in fhand:
+ if ((expression_kind == 'str' and expression in line) or
+ expression.search(line)):
+ yield sofar
+ sofar = line
+ else:
+ sofar += line
else:
- file_ = ofh
- return file_
+ #the last item
+ yield sofar
def _create_file_splitter_with_re(expression):
'''Given an expression it creates a file splitter.
The expression can be a regex or an str.
The item in the file will be defined everytime a line matches the
expression.
'''
expression_kind = None
if isinstance(expression, str):
expression_kind = 'str'
else:
expression_kind = 're'
def splitter(file_, work_dirs):
'''It splits the given file into several splits.
Every split will be located in one of the work_dirs, although it is not
guaranteed to create as many splits as work dirs. If in the file there
are less items than work_dirs some work_dirs will be left empty.
It returns a list with the fpaths or fhands for the splitted files.
file_ can be an fhand or an fname.
'''
#the file_ can be an fname or an fhand. which one is it?
file_is_str = None
if isinstance(file_, str):
fname = file_
file_is_str = True
else:
fname = file_.name
file_is_str = False
#how many splits do we want?
nsplits = len(work_dirs)
#how many items are in the file? We assume that all files have the same
#number of items
nitems = 0
for line in open(fname, 'r'):
if ((expression_kind == 'str' and expression in line) or
expression.search(line)):
nitems += 1
#how many splits a we going to create? and how many items will be in
#every split
#if there are more items than splits we create as many splits as items
if nsplits > nitems:
nsplits = nitems
(nsplits1, nitems1), (nsplits2, nitems2) = _calculate_divisions(nitems,
nsplits)
#we have to create nsplits1 files with nitems1 in it and nsplits2 files
#with nitems2 items in it
- splits_made = 0
- new_fpaths = []
+ new_files = []
fhand = open(fname, 'r')
- for index_splits, nsplits in enumerate((nsplits1, nsplits2)):
- nitems = (nitems1, nitems2)[index_splits]
+ items = _items_in_file(fhand, expression_kind, expression)
+ splits_made = 0
+ for nsplits, nitems in ((nsplits1, nitems1), (nsplits2, nitems2)):
#we have to create nsplits files with nitems in it
- #we just want to run the for nsplits times, we don't need the
- #index variable
+ #we don't need the split_index for anything
#pylint: disable-msg=W0612
- for index in range(nsplits):
- items_sofar = 0
- sofar = fhand.readline()
+ for split_index in range(nsplits):
suffix = os.path.splitext(fname)[-1]
- splits_made = 0
- for line in fhand:
- #has the file the required pattern?
- if ((expression_kind == 'str' and expression in line) or
- expression.search(line)):
- items_sofar += 1
- if items_sofar >= nitems:
- #which is the work dir in which this file
- #should be located?
- work_dir = work_dirs[splits_made]
- ofile_ = _write_file(work_dir.name, sofar, suffix,
- file_is_str)
- new_fpaths.append(ofile_)
- sofar = line
- items_sofar = 0
- splits_made += 1
- else:
- sofar += line
- else:
- sofar += line
- #now we write the last file
work_dir = work_dirs[splits_made]
- ofname = _write_file(work_dir.name, sofar, suffix, file_is_str)
- new_fpaths.append(ofname)
- return new_fpaths
+ ofh = NamedTemporaryFile(dir=work_dir.name, delete=False,
+ suffix=suffix)
+ for item_index in range(nitems):
+ ofh.write(items.next())
+ ofh.flush()
+ if file_is_str:
+ new_files.append(ofh.name)
+ ofh.close()
+ else:
+ new_files.append(ofh)
+ splits_made += 1
+ return new_files
return splitter
def _output_splitter(file_, work_dirs):
'''It creates one output file for every splits.
Every split will be located in one of the work_dirs.
It returns a list with the fpaths for the new output files.
'''
#the file_ can be an fname or an fhand. which one is it?
file_is_str = None
if isinstance(file_, str):
fname = file_
file_is_str = True
else:
fname = file_.name
file_is_str = False
#how many splits do we want?
nsplits = len(work_dirs)
new_fpaths = []
#we have to create nsplits
for split_index in range(nsplits):
suffix = os.path.splitext(fname)[-1]
work_dir = work_dirs[split_index]
#we use delete=False because this temp file is in a temp dir that will
#be completely deleted. If we use delete=True we get an error because
#the file might be already deleted when its __del__ method is called
ofh = NamedTemporaryFile(dir=work_dir.name, suffix=suffix,
delete=False)
#the file will be deleted
#what do we need the fname or the fhand?
if file_is_str:
#it will be deleted because we just need the name in the temporary
#directory. tempfile.mktemp would be better for this use, but it is
#deprecated
new_fpaths.append(ofh.name)
ofh.close()
else:
new_fpaths.append(ofh)
return new_fpaths
def default_cat_joiner(out_file_, in_files_):
'''It joins the given in files into the given out file.
It works with fnames or fhands.
'''
#are we working with fhands or fnames?
file_is_str = None
if isinstance(out_file_, str):
file_is_str = True
else:
file_is_str = False
#the output fhand
if file_is_str:
out_fhand = open(out_file_, 'w')
else:
out_fhand = open(out_file_.name, 'w')
for in_file_ in in_files_:
#the input fhand
if file_is_str:
in_fhand = open(in_file_, 'r')
else:
in_fhand = open(in_file_.name, 'r')
for line in in_fhand:
out_fhand.write(line)
in_fhand.close()
out_fhand.close()
class Popen(object):
'It paralellizes the given processes divinding them into subprocesses.'
def __init__(self, cmd, cmd_def=None, runner=None, stdout=None, stderr=None,
stdin=None, splits=None):
'''
Constructor
'''
#we want the same interface as subprocess.popen
#pylint: disable-msg=R0913
self._retcode = None
self._outputs_collected = False
#some defaults
#if the runner is not given, we use subprocess.Popen
if runner is None:
runner = StdPopen
+ if cmd_def is None:
+ if stdin is not None:
+ raise ValueError('No cmd_def given but stdin present')
+ cmd_def = []
#if the number of splits is not given we calculate them
if splits is None:
splits = self.default_splits(runner)
#we need a work dir to create the temporary split files
self._work_dir = NamedTemporaryDir()
#the main job
self._job = {'cmd': cmd, 'work_dir': self._work_dir}
#we create the new subjobs
self._jobs = self._split_jobs(cmd, cmd_def, splits, self._work_dir,
stdout=stdout, stderr=stderr, stdin=stdin)
#launch every subjobs
self._launch_jobs(self._jobs, runner=runner)
@staticmethod
def _launch_jobs(jobs, runner):
'It launches all jobs and it adds its popen instance to them'
jobs['popens'] = []
cwd = os.getcwd()
for job_index, (cmd, streams, work_dir) in enumerate(zip(jobs['cmds'],
jobs['streams'], jobs['work_dirs'])):
#the std stream can be present or not
stdin, stdout, stderr = None, None, None
if jobs['stdins']:
stdin = jobs['stdins'][job_index]
if jobs['stdouts']:
stdout = jobs['stdouts'][job_index]
if jobs['stderrs']:
stderr = jobs['stderrs'][job_index]
#for every job we go to its dir to launch it
os.chdir(work_dir.name)
+ #we have to be sure that stdin is open for read
+ if stdin:
+ stdin = open(stdin.name)
#we launch the job
if runner == StdPopen:
popen = runner(cmd, stdout=stdout, stderr=stderr, stdin=stdin)
else:
popen = runner(cmd, cmd_def=streams, stdout=stdout,
stderr=stderr, stdin=stdin)
#we record it's popen instane
jobs['popens'].append(popen)
os.chdir(cwd)
def _split_jobs(self, cmd, cmd_def, splits, work_dir, stdout=None,
stderr=None, stdin=None,):
''''I creates one job for every split.
Every job has a cmd, work_dir and streams, this info is in the jobs dict
with the keys: cmds, work_dirs, streams
'''
#too many arguments, but similar interface to our __init__
#pylint: disable-msg=R0913
#pylint: disable-msg=R0914
#the main job streams
main_job_streams = get_streams_from_cmd(cmd, cmd_def, stdout=stdout,
stderr=stderr, stdin=stdin)
self._job['streams'] = main_job_streams
streams, work_dirs = self._split_streams(main_job_streams, splits,
work_dir.name)
#now we have to create a new cmd with the right in and out streams for
#every split
cmds, stdins, stdouts, stderrs = self._create_cmds(cmd, streams)
jobs = {'cmds': cmds, 'work_dirs': work_dirs, 'streams': streams,
'stdins':stdins, 'stdouts':stdouts, 'stderrs':stderrs}
return jobs
@staticmethod
def _create_cmds(cmd, streams):
'''Given a base cmd and a steams list it creates one modified cmds for
every stream'''
#the streams is a list of streams
streamss = streams
cmds = []
stdouts = []
stdins = []
stderrs = []
for streams in streamss:
new_cmd = copy.deepcopy(cmd)
for stream in streams:
#is the stream in the cmd or in is a std one?
location = stream['cmd_location']
- if location == STDIN:
+ if location is None:
+ continue
+ elif location == STDIN:
stdins.append(stream['fhand'])
elif location == STDOUT:
stdouts.append(stream['fhand'])
elif location == STDERR:
stderrs.append(stream['fhand'])
else:
#we modify the cmd[location] with the new file
#we use the fname and no path because the jobs will be
#launched from the job working dir
location = stream['cmd_location']
fpath = stream['fname']
fname = os.path.split(fpath)[-1]
new_cmd[location] = fname
cmds.append(new_cmd)
return cmds, stdins, stdouts, stderrs
@staticmethod
def _split_streams(streams, splits, work_dir):
'''Given a list of streams it splits every stream in the given number of
splits'''
#which are the input and output streams?
input_stream_indexes = []
output_stream_indexes = []
for index, stream in enumerate(streams):
if stream['io'] == 'in':
input_stream_indexes.append(index)
elif stream['io'] == 'out':
output_stream_indexes.append(index)
#we create one work dir for every split
work_dirs = []
for index in range(splits):
work_dirs.append(NamedTemporaryDir(dir=work_dir))
#we have to do first the input files because the number of splits could
#be changed by them
#we split the input stream files into several splits
+ #we have to sort the input_stream_indexes, first we should take the ones
+ #that have an input file to be split
+ def to_be_split_first(stream1, stream2):
+ 'It sorts the streams, the ones to be split go first'
+ split1 = None
+ split2 = None
+ for split, stream in ((split1, stream1), (split2, stream2)):
+ #maybe they shouldn't be split
+ if 'special' in stream and 'no_split' in stream['special']:
+ split = False
+ #maybe the have no file to split
+ if (('fhand' in stream and stream['fhand'] is None) or
+ ('fname' in stream and stream['fname'] is None) or
+ ('fname' not in stream and 'fhand' not in stream)):
+ split = False
+ elif (('fhand' in stream and stream['fhand'] is not None) or
+ ('fname' in stream and stream['fname'] is not None)):
+ split = True
+ return int(split1) - int(split2)
+ input_stream_indexes = sorted(input_stream_indexes, to_be_split_first)
+
first = True
split_files = {}
for index in input_stream_indexes:
stream = streams[index]
#splitter
+ if 'splitter' not in stream:
+ msg = 'An splitter should be provided for every input stream'
+ msg += 'missing for: ' + str(stream)
+ raise ValueError(msg)
splitter = stream['splitter']
#the splitter can be a re, in that case with create the function
if '__call__' not in dir(splitter):
splitter = _create_file_splitter_with_re(splitter)
#we split the input files in the splits, every file will be in one
#of the given work_dirs
#the stream can have fname or fhands
if 'fhand' in stream:
- fname = stream['fhand'].name
+ file_ = stream['fhand']
else:
- fname = stream['fname']
- files = splitter(fname, work_dirs)
+ file_ = stream['fname']
+ if file_ is None:
+ #the stream migth have no file associated
+ files = [None] * len(work_dirs)
+ else:
+ files = splitter(file_, work_dirs)
#the files len can be different than splits, in that case we modify
#the splits or we raise an error
if len(files) != splits:
if first:
splits = len(files)
#we discard the empty temporary dirs
work_dirs = work_dirs[0:splits]
else:
msg = 'Not all input files were divided in the same number'
msg += ' of splits'
raise RuntimeError(msg)
first = False
split_files[index] = files #a list of files for every in stream
#we split the ouptut stream files into several splits
for index in output_stream_indexes:
stream = streams[index]
#for th output we just create the new names, but we don't split
#any file
if 'fhand' in stream:
fname = stream['fhand']
else:
fname = stream['fname']
files = _output_splitter(fname, work_dirs)
split_files[index] = files #a list of files for every in stream
new_streamss = []
#we need one new stream for every split
for split_index in range(splits):
#the streams for one job
new_streams = []
for stream_index, stream in enumerate(streams):
#we duplicate the original stream
new_stream = stream.copy()
#we set the new files
if 'fhand' in stream:
new_stream['fhand'] = split_files[stream_index][split_index]
else:
new_stream['fname'] = split_files[stream_index][split_index]
new_streams.append(new_stream)
new_streamss.append(new_streams)
return new_streamss, work_dirs
@staticmethod
def default_splits(runner):
'Given a runner it returns the number of splits recommended by default'
if runner is StdPopen:
#the number of processors
return os.sysconf('SC_NPROCESSORS_ONLN')
else:
- return runner.default_splits()
+ module = runner.__module__.split('.')[-1]
+ module = RUNNER_MODULES[module]
+ return module.get_default_splits()
def wait(self):
'It waits for all the works to finnish'
#we wait till all jobs finish
for job in self._jobs['popens']:
job.wait()
#now that all jobs have finished we join the results
self._collect_output_streams()
#we join now the retcodes
self._collect_retcodes()
return self._retcode
def _collect_output_streams(self):
'''It joins all the output streams into the output files and it removes
the work dirs'''
if self._outputs_collected:
return
#for each file in the main job cmd
for stream_index, stream in enumerate(self._job['streams']):
if stream['io'] == 'in':
#now we're dealing only with output files
continue
#every subjob has a part to join for this output stream
part_out_fnames = []
for streams in self._jobs['streams']:
this_stream = streams[stream_index]
if 'fname' in this_stream:
part_out_fnames.append(this_stream['fname'])
else:
part_out_fnames.append(this_stream['fhand'])
#we need a function to join this stream
joiner = None
if joiner in stream:
joiner = stream['joiner']
else:
joiner = default_cat_joiner
if 'fname' in stream:
out_file = stream['fname']
else:
out_file = stream['fhand']
default_cat_joiner(out_file, part_out_fnames)
#now we can delete the tempdirs
for work_dir in self._jobs['work_dirs']:
work_dir.close()
self._outputs_collected = True
def _collect_retcodes(self):
'It gathers the retcodes from all processes'
retcode = None
for popen in self._jobs['popens']:
job_retcode = popen.returncode
if job_retcode is None:
#if some job is yet to be finished the main job is not finished
retcode = None
break
elif job_retcode != 0:
#if one job has finnished badly the main job is badly finished
retcode = job_retcode
break
#it should be 0 at this point
retcode = job_retcode
#if the retcode is not None the jobs have finished and we have to
#collect the outputs
if retcode is not None:
self._collect_output_streams()
self._retcode = retcode
return retcode
def _get_returncode(self):
'It returns the return code'
if self._retcode is None:
self._collect_retcodes()
return self._retcode
returncode = property(_get_returncode)
\ No newline at end of file
diff --git a/psubprocess/streams.py b/psubprocess/streams.py
index 47000ae..4191f64 100644
--- a/psubprocess/streams.py
+++ b/psubprocess/streams.py
@@ -1,102 +1,109 @@
'''
Created on 13/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of project.
# project is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# project 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with project. If not, see <http://www.gnu.org/licenses/>.
STDIN = 'stdin'
STDOUT = 'stdout'
STDERR = 'stderr'
def _find_param_def_in_cmd(cmd, param_def):
'''Given a cmd and a parameter definition it returns the index of the param
in the cmd.
If the param is not found in the cmd it will raise a ValueError.
'''
options = param_def['options']
#options could be a list or an item
if not isinstance(options, list) and not isinstance(options, tuple):
options = (options,)
#the standard options with command line options
for index, item in enumerate(cmd):
if item in options:
return index
raise ValueError('Parameter not found in the given cmd')
def _positive_int(index, sequence):
'''It returns the same int index, but positive.'''
if index is None:
return None
elif index < 0:
return len(sequence) + index
return index
def get_streams_from_cmd(cmd, cmd_def, stdout=None, stdin=None, stderr=None):
'Given a cmd and a cmd definition it returns the streams'
streams = []
for param_def in cmd_def:
options = param_def['options']
- stream_values = []
+ stream_values = None
#where is this stream located in the cmd?
location = None
#we have to look for the stream in the cmd
#where is the parameter in the cmd list?
#if the param options is not an int, its a list of strings
if isinstance(options, int):
#for PRE_ARG (1) and POST_ARG (-1)
#we take 1 unit because the options should be 1 to the right
#of the value
index = _positive_int(options, cmd) - 1
+ elif options == STDIN:
+ index = STDIN
else:
#look for param in cmd
try:
index = _find_param_def_in_cmd(cmd, param_def)
except ValueError:
index = None
#get the stream values
- if index is not None:
+ if index == STDIN:
+ location = STDIN
+ stream_values = stdin
+ elif index is not None:
location = index + 1
stream_values = cmd[location]
#create the result dict
stream = param_def.copy()
- stream['fname'] = stream_values
+ if location is STDIN:
+ stream['fhand'] = stream_values
+ else:
+ stream['fname'] = stream_values
stream['cmd_location'] = location
streams.append(stream)
- #We have to add also the stdin, stdout and stderr
- for stream_name, fhand in ((STDIN, stdin), (STDOUT, stdout),
- (STDERR, stderr)):
+ #We have to add also the stdout and stderr
+ for stream_name, fhand in ((STDOUT, stdout), (STDERR, stderr)):
if fhand is None:
continue
io_value = None
if stream_name == STDIN:
io_value = 'in'
else:
io_value = 'out'
stream = {}
stream['fhand'] = fhand
stream['io'] = io_value
stream['cmd_location'] = stream_name
streams.append(stream)
return streams
\ No newline at end of file
diff --git a/test/cmd_def_test.py b/test/cmd_def_test.py
index 84677ab..1faffd7 100644
--- a/test/cmd_def_test.py
+++ b/test/cmd_def_test.py
@@ -1,149 +1,150 @@
'''
Created on 13/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
import unittest
from psubprocess.streams import (get_streams_from_cmd,
STDIN, STDOUT, STDERR)
#What's a stream
#
#A command takes some input streams and creates some ouput streams
#An stream is a file-like object or a directory. In fact an stream can be
#composed by several files (e.g. a seq and a qual file that should be splitted
#together)
#
#Kinds of streams in a cmd
#cmd arg1 arg2 -i opt1 opt2 -j opt3 arg3 < stdin > stdout stderr retcode
#in this general command there are several types of streams:
# - previous arguments. arguments (without options) located before the first
# option (like arg1 and arg2)
# - options with one option, like opt3
# - options with several arguments, like -i that has opt1 and opt2
# - arguments (aka post_arguments). arguments located after the last option
# - stdin, stdout, stderr and retcode. The standard ones.
#
#How to define the streams
#An stream is defined by a dict with the following keys: options, io, splitter,
#value, special, location. All of them are optional except the options.
#Options: It defines in which options or arguments is the stream found. It
#should by just a value or a tuple.
#Options kinds:
# - -i the stream will be located after the parameter -i
# - (-o, --output) the stream will be after -o or --output
# - PRE_ARG right after the cmd and before the first parameter
# - POST_ARG after the last option
# - STDIN
# - STDOUT
# - STDERR
#io: It defines if it's an input or an output stream for the cmd
#splitter: It defines how the stream should be split. There are three ways of
#definint it:
# - an str that will be used to scan through the in streams, every
# line with the str in in will be considered a token start
# e.g '>' for the blast files
# - a re every line with a match will be considered a token start
# - a function the function should take the stream an return an
# iterator with the tokens
#joiner: A function that should take the out streams for all jobs and return
#the joined stream. If not given the output stream will be just concatenated.
#value: the value for the stream, this stream will not define the value in the
#command line, it will be implicit
#special: It defines some special treaments for the streams.
# - no_split It shouldn't be split
# - no_transfer It shouldn't be transfer to all nodes
# - no_abspath Its path shouldn't be converted to absolute
# - create It should be created before running the command
# - no_support An error should be raised if used.
#cmd_locations: If the location is not given the assumed location will be 0.
#That means that the stream will be located in the 0 position after the option.
#It can be either an int or an slice. In the slice case several substreams will
#be taken together in the stream. Useful for instance for the case of two fasta
#files with the seq an qual that should be split together and transfered
#together.
def _check_streams(streams, expected_streams):
'It checks that streams meet the requirements set by the expected streams'
for stream, expected_stream in zip(streams, expected_streams):
for key in expected_stream:
assert stream[key] == expected_stream[key]
class StreamsFromCmdTest(unittest.TestCase):
'It tests that we can get the input and output files from the cmd'
@staticmethod
def test_simple_case():
'It tests the most simple cases'
#a simple case
cmd = ['hola', '-i', 'caracola.txt']
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'}]
expected_streams = [{'fname': 'caracola.txt', 'io':'in',
'cmd_location':2}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
#a parameter not found in the cmd
cmd = ['hola', '-i', 'caracola.txt']
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
{'options': ('-j', '--input2'), 'io': 'in'}]
expected_streams = [{'fname': 'caracola.txt', 'io':'in',
'cmd_location': 2}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
@staticmethod
def test_arguments():
'It test that it works with cmd arguments, not options'
#the options we want is in the pre_argv, after the binary
cmd = ['hola', 'hola.txt', '-i', 'caracola.txt']
cmd_def = [{'options': 1, 'io': 'in'}]
expected_streams = [{'fname': 'hola.txt', 'io':'in',
'cmd_location':1}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
#the option we want is at the end of the cmd
cmd = ['hola', '-i', 'caracola.txt', 'hola.txt']
cmd_def = [{'options': -1, 'io': 'in'}]
expected_streams = [{'fname': 'hola.txt', 'io':'in',
'cmd_location':3}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
@staticmethod
def test_stdin():
'We want stdin, stdout and stderr as streams'
#stdin
cmd = ['hola']
- cmd_def = []
+ cmd_def = [{'options':STDIN, 'io': 'in'}]
stdout = 'stdout' #in the real world they will be files
stderr = 'stderr'
stdin = 'stdin'
- expected_streams = [{'fhand': stdin, 'io':'in', 'cmd_location':STDIN},
+ expected_streams = [{'fhand': stdin, 'io':'in', 'cmd_location':STDIN},
{'fhand': stdout, 'io':'out', 'cmd_location':STDOUT},
{'fhand': stderr, 'io':'out', 'cmd_location':STDERR}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def, stdout=stdout,
stderr=stderr, stdin=stdin)
_check_streams(streams, expected_streams)
+
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
\ No newline at end of file
diff --git a/test/condor_runner_test.py b/test/condor_runner_test.py
index 38dacb9..3a6e2b9 100644
--- a/test/condor_runner_test.py
+++ b/test/condor_runner_test.py
@@ -1,170 +1,181 @@
'''
Created on 14/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
import unittest
from tempfile import NamedTemporaryFile
from StringIO import StringIO
import os
-from psubprocess.condor_runner import write_condor_job_file, Popen
+from psubprocess.condor_runner import (write_condor_job_file, Popen,
+ get_default_splits)
from test_utils import create_test_binary
class CondorRunnerTest(unittest.TestCase):
'It tests the condor runner'
@staticmethod
def test_write_condor_job_file():
'It tests that we can write a condor job file with the right parameters'
fhand1 = NamedTemporaryFile()
fhand2 = NamedTemporaryFile()
flog = NamedTemporaryFile()
stderr_ = NamedTemporaryFile()
stdout_ = NamedTemporaryFile()
stdin_ = NamedTemporaryFile()
expected = '''Executable = bin
Arguments = "-i %s -j %s"
Universe = vanilla
Log = %s
When_to_transfer_output = ON_EXIT
Getenv = True
Transfer_executable = True
Transfer_input_files = %s,%s
Should_transfer_files = IF_NEEDED
Output = %s
Error = %s
Input = %s
Queue
''' % (fhand1.name, fhand2.name, flog.name, fhand1.name, fhand2.name,
stdout_.name, stderr_.name, stdin_.name)
fhand = StringIO()
parameters = {'executable':'bin', 'log_file':flog,
'input_fnames':[fhand1.name, fhand2.name],
'arguments':'-i %s -j %s' % (fhand1.name, fhand2.name),
'transfer_executable':True, 'transfer_files':True,
'stdout':stdout_, 'stderr':stderr_, 'stdin':stdin_}
write_condor_job_file(fhand, parameters=parameters)
condor = fhand.getvalue()
assert condor == expected
@staticmethod
def test_run_condor_stdout():
'It test that we can run condor job and retrieve stdout and stderr'
bin = create_test_binary()
#a simple job
- cmd = [bin.name]
+ cmd = [bin]
cmd.extend(['-o', 'hola', '-e', 'caracola'])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stderr=stderr)
assert popen.wait() == 0 #waits till finishes and looks to the retcode
assert open(stdout.name).read() == 'hola'
assert open(stderr.name).read() == 'caracola'
+ os.remove(bin)
@staticmethod
def test_run_condor_stdin():
'It test that we can run condor job with stdin'
bin = create_test_binary()
#a simple job
- cmd = [bin.name]
+ cmd = [bin]
cmd.extend(['-s'])
stdin = NamedTemporaryFile()
stdout = NamedTemporaryFile()
stdin.write('hola')
stdin.flush()
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stdin=stdin)
assert popen.wait() == 0 #waits till finishes and looks to the retcode
assert open(stdout.name).read() == 'hola'
+ os.remove(bin)
@staticmethod
def test_run_condor_retcode():
'It test that we can run condor job and get the retcode'
bin = create_test_binary()
#a simple job
- cmd = [bin.name]
+ cmd = [bin]
cmd.extend(['-r', '10'])
popen = Popen(cmd, runner_conf={'transfer_executable':True})
assert popen.wait() == 10 #waits till finishes and looks to the retcode
+ os.remove(bin)
@staticmethod
def test_run_condor_in_file():
'It test that we can run condor job with an input file'
bin = create_test_binary()
in_file = NamedTemporaryFile()
in_file.write('hola')
in_file.flush()
- cmd = [bin.name]
+ cmd = [bin]
cmd.extend(['-i', in_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'}]
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stderr=stderr, cmd_def=cmd_def)
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(stdout.name).read() == 'hola'
+ os.remove(bin)
def test_run_condor_in_out_file(self):
'It test that we can run condor job with an output file'
bin = create_test_binary()
in_file = NamedTemporaryFile()
in_file.write('hola')
in_file.flush()
out_file = open('output.txt', 'w')
- cmd = [bin.name]
+ cmd = [bin]
cmd.extend(['-i', in_file.name, '-t', out_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
{'options': ('-t', '--output'), 'io': 'out'}]
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stderr=stderr, cmd_def=cmd_def)
popen.wait()
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(out_file.name).read() == 'hola'
os.remove(out_file.name)
#and output file with path won't be allowed unless the transfer file
#mechanism is not used
out_file = NamedTemporaryFile()
- cmd = [bin.name]
+ cmd = [bin]
cmd.extend(['-i', in_file.name, '-t', out_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
{'options': ('-t', '--output'), 'io': 'out'}]
try:
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stderr=stderr, cmd_def=cmd_def)
self.fail('ValueError expected')
#pylint: disable-msg=W0704
except ValueError:
pass
+ os.remove(bin)
+ @staticmethod
+ def test_default_splits():
+ 'It tests that we can get a suggested number of splits'
+ assert get_default_splits() > 0
+ assert isinstance(get_default_splits(), int)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
\ No newline at end of file
diff --git a/test/prunner_test.py b/test/prunner_test.py
index 86b886f..60b85b0 100644
--- a/test/prunner_test.py
+++ b/test/prunner_test.py
@@ -1,53 +1,152 @@
'''
Created on 16/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
import unittest
from tempfile import NamedTemporaryFile
import os
from psubprocess import Popen
+from psubprocess.streams import STDIN
from test_utils import create_test_binary
class PRunnerTest(unittest.TestCase):
'It test that we can parallelize processes'
@staticmethod
- def test_basic_behaviour():
+ def test_file_in():
'It tests the most basic behaviour'
bin = create_test_binary()
- #a simple job
+ #with infile
in_file = NamedTemporaryFile()
in_file.write('hola')
in_file.flush()
cmd = [bin]
cmd.extend(['-i', in_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''}]
popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def)
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(stdout.name).read() == 'hola'
+ in_file.close()
os.remove(bin)
+ @staticmethod
+ def test_job_no_in_stream():
+ 'It test that a job with no in stream is run splits times'
+ bin = create_test_binary()
+
+ cmd = [bin]
+ cmd.extend(['-o', 'hola', '-e', 'caracola'])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''}]
+ splits = 4
+ popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def,
+ splits=splits)
+ assert popen.wait() == 0 #waits till finishes and looks to the retcod
+ assert open(stdout.name).read() == 'hola' * splits
+ assert open(stderr.name).read() == 'caracola' * splits
+ os.remove(bin)
+
+ @staticmethod
+ def test_stdin():
+ 'It test that stdin works as input'
+ bin = create_test_binary()
+
+ #with stdin
+ content = 'hola1\nhola2\nhola3\nhola4\nhola5\nhola6\nhola7\nhola8\n'
+ content += 'hola9\nhola10|n'
+ stdin = NamedTemporaryFile()
+ stdin.write(content)
+ stdin.flush()
+
+ cmd = [bin]
+ cmd.extend(['-s'])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ cmd_def = [{'options':STDIN, 'io': 'in', 'splitter':''}]
+ popen = Popen(cmd, stdout=stdout, stderr=stderr, stdin=stdin,
+ cmd_def=cmd_def)
+ assert popen.wait() == 0 #waits till finishes and looks to the retcod
+ assert open(stdout.name).read() == content
+ assert open(stderr.name).read() == ''
+ os.remove(bin)
+
+ @staticmethod
+ def test_infile_outfile():
+ 'It tests that we can set an input file and an output file'
+ bin = create_test_binary()
+ #with infile
+ in_file = NamedTemporaryFile()
+ content = 'hola1\nhola2\nhola3\nhola4\nhola5\nhola6\nhola7\nhola8\n'
+ content += 'hola9\nhola10|n'
+ in_file.write(content)
+ in_file.flush()
+ out_file = NamedTemporaryFile()
+
+ cmd = [bin]
+ cmd.extend(['-i', in_file.name, '-t', out_file.name])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''},
+ {'options': ('-t', '--output'), 'io': 'out'}]
+ popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def)
+ assert popen.wait() == 0 #waits till finishes and looks to the retcod
+ assert not open(stdout.name).read()
+ assert not open(stderr.name).read()
+ assert open(out_file.name).read() == content
+ in_file.close()
+ os.remove(bin)
+
+ @staticmethod
+ def test_infile_outfile_condor():
+ 'It tests that we can set an input file and an output file'
+ bin = create_test_binary()
+ #with infile
+ in_file = NamedTemporaryFile()
+ content = 'hola1\nhola2\nhola3\nhola4\nhola5\nhola6\nhola7\nhola8\n'
+ content += 'hola9\nhola10|n'
+ in_file.write(content)
+ in_file.flush()
+ out_file = NamedTemporaryFile()
+
+ cmd = [bin]
+ cmd.extend(['-i', in_file.name, '-t', out_file.name])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''},
+ {'options': ('-t', '--output'), 'io': 'out'}]
+ from psubprocess import CondorPopen
+ popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def,
+ runner=CondorPopen)
+ assert popen.wait() == 0 #waits till finishes and looks to the retcod
+ assert not open(stdout.name).read()
+ assert not open(stderr.name).read()
+ assert open(out_file.name).read() == content
+ in_file.close()
+ os.remove(bin)
+
+
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
\ No newline at end of file
|
JoseBlanca/psubprocess
|
1f9156362f04255a7e95d50d1ff61670f4055cbc
|
Implemented basic parallelization support into prunner. Now the basic test works
|
diff --git a/psubprocess/prunner.py b/psubprocess/prunner.py
index ba3fe09..2b8ced7 100644
--- a/psubprocess/prunner.py
+++ b/psubprocess/prunner.py
@@ -1,471 +1,541 @@
'''It launches parallel processes with an interface similar to Popen.
It divides jobs into subjobs and launches the subjobs.
Created on 16/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
from subprocess import Popen as StdPopen
import os, tempfile, shutil, copy
from psubprocess.streams import get_streams_from_cmd, STDOUT, STDERR, STDIN
class NamedTemporaryDir(object):
'''This class creates temporary directories '''
#pylint: disable-msg=W0622
#we redifine the build in dir because temfile uses that inteface
def __init__(self, dir=None):
'''It initiates the class.'''
self._name = tempfile.mkdtemp(dir=dir)
def get_name(self):
'Returns path to the dict'
return self._name
name = property(get_name)
def close(self):
'''It removes the temp dir'''
if os.path.exists(self._name):
shutil.rmtree(self._name)
def __del__(self):
'''It removes de temp dir when instance is removed and the garbaje
colector decides it'''
self.close()
def NamedTemporaryFile(dir=None, delete=False, suffix=''):
'''It creates a temporary file that won't be deleted when close
This behaviour can be done with tempfile.NamedTemporaryFile in python > 2.6
'''
+ #pylint: disable-msg=W0613
+ #delete is not being used, it's there as a reminder, once we start to use
+ #python 2.6 this function should be removed
+ #pylint: disable-msg=C0103
+ #pylint: disable-msg=W0622
+ #We want to mimick tempfile.NamedTemporaryFile
fpath = tempfile.mkstemp(dir=dir, suffix=suffix)[1]
return open(fpath, 'w')
def _calculate_divisions(num_items, splits):
'''It calculates how many items should be in every split to divide
the num_items into splits.
Not all splits will have an equal number of items, it will return a tuple
with two tuples inside:
((num_fragments_1, num_items_1), (num_fragments_2, num_items_2))
splits = num_fragments_1 + num_fragments_2
num_items_1 = num_items_2 + 1
num_fragments_1 could be equal to 0.
This is the best way to create as many splits as possible as similar as
possible.
'''
if splits >= num_items:
return ((0, 1), (splits, 1))
num_fragments1 = num_items % splits
num_fragments2 = splits - num_fragments1
num_items2 = num_items // splits
num_items1 = num_items2 + 1
res = ((num_fragments1, num_items1), (num_fragments2, num_items2))
return res
-def _write_file(dir, contents, suffix):
+def _write_file(dir, contents, suffix, return_fname):
'''It creates a new file with the given contents. It returns the path'''
+ #pylint: disable-msg=W0622
+ #we're redefining the built-in dir because is the clearest interface,
+ #and because this interface is used by tempdir
ofh = NamedTemporaryFile(dir=dir, delete=False, suffix=suffix)
ofh.write(contents)
- #the file won't be deleted, just closed,
- #it will be deleted because is created in a
- #temporary directory
- fname = ofh.name
ofh.flush()
- ofh.close()
- return fname
+ if return_fname:
+ #the file won't be deleted, just closed,
+ #it will be deleted because is created in a
+ #temporary directory
+ file_ = ofh.name
+ ofh.close()
+ else:
+ file_ = ofh
+ return file_
def _create_file_splitter_with_re(expression):
'''Given an expression it creates a file splitter.
The expression can be a regex or an str.
The item in the file will be defined everytime a line matches the
expression.
'''
expression_kind = None
if isinstance(expression, str):
expression_kind = 'str'
else:
expression_kind = 're'
- def splitter(fname, work_dirs):
+ def splitter(file_, work_dirs):
'''It splits the given file into several splits.
Every split will be located in one of the work_dirs, although it is not
guaranteed to create as many splits as work dirs. If in the file there
are less items than work_dirs some work_dirs will be left empty.
- It returns a list with the fpaths for the splitted files.
+ It returns a list with the fpaths or fhands for the splitted files.
+ file_ can be an fhand or an fname.
'''
+ #the file_ can be an fname or an fhand. which one is it?
+ file_is_str = None
+ if isinstance(file_, str):
+ fname = file_
+ file_is_str = True
+ else:
+ fname = file_.name
+ file_is_str = False
+
#how many splits do we want?
nsplits = len(work_dirs)
#how many items are in the file? We assume that all files have the same
#number of items
nitems = 0
for line in open(fname, 'r'):
if ((expression_kind == 'str' and expression in line) or
expression.search(line)):
nitems += 1
#how many splits a we going to create? and how many items will be in
#every split
#if there are more items than splits we create as many splits as items
if nsplits > nitems:
nsplits = nitems
(nsplits1, nitems1), (nsplits2, nitems2) = _calculate_divisions(nitems,
nsplits)
#we have to create nsplits1 files with nitems1 in it and nsplits2 files
#with nitems2 items in it
splits_made = 0
new_fpaths = []
fhand = open(fname, 'r')
for index_splits, nsplits in enumerate((nsplits1, nsplits2)):
nitems = (nitems1, nitems2)[index_splits]
#we have to create nsplits files with nitems in it
+ #we just want to run the for nsplits times, we don't need the
+ #index variable
+ #pylint: disable-msg=W0612
for index in range(nsplits):
items_sofar = 0
sofar = fhand.readline()
suffix = os.path.splitext(fname)[-1]
splits_made = 0
for line in fhand:
#has the file the required pattern?
if ((expression_kind == 'str' and expression in line) or
expression.search(line)):
items_sofar += 1
if items_sofar >= nitems:
- #how many splits do we have now for this file?
- splits_now = splits_made
#which is the work dir in which this file
#should be located?
work_dir = work_dirs[splits_made]
- ofname = _write_file(work_dir.name, sofar, suffix)
- new_fpaths.append(ofname)
+ ofile_ = _write_file(work_dir.name, sofar, suffix,
+ file_is_str)
+ new_fpaths.append(ofile_)
sofar = line
items_sofar = 0
splits_made += 1
else:
sofar += line
else:
sofar += line
#now we write the last file
work_dir = work_dirs[splits_made]
- ofname = _write_file(work_dir.name, sofar, suffix)
+ ofname = _write_file(work_dir.name, sofar, suffix, file_is_str)
new_fpaths.append(ofname)
return new_fpaths
return splitter
-def _output_splitter(fname, work_dirs):
+def _output_splitter(file_, work_dirs):
'''It creates one output file for every splits.
Every split will be located in one of the work_dirs.
It returns a list with the fpaths for the new output files.
'''
+ #the file_ can be an fname or an fhand. which one is it?
+ file_is_str = None
+ if isinstance(file_, str):
+ fname = file_
+ file_is_str = True
+ else:
+ fname = file_.name
+ file_is_str = False
#how many splits do we want?
nsplits = len(work_dirs)
new_fpaths = []
#we have to create nsplits
for split_index in range(nsplits):
suffix = os.path.splitext(fname)[-1]
work_dir = work_dirs[split_index]
- ofh = tempfile.NamedTemporaryFile(dir=work_dir.name, suffix=suffix)
+ #we use delete=False because this temp file is in a temp dir that will
+ #be completely deleted. If we use delete=True we get an error because
+ #the file might be already deleted when its __del__ method is called
+ ofh = NamedTemporaryFile(dir=work_dir.name, suffix=suffix,
+ delete=False)
#the file will be deleted
- #it will be deleted because we just need the name in the temporary
- #directory. tempfile.mktemp would be better for this use, but it is
- #deprecated
- new_fpaths.append(ofh.name)
- ofh.close()
+ #what do we need the fname or the fhand?
+ if file_is_str:
+ #it will be deleted because we just need the name in the temporary
+ #directory. tempfile.mktemp would be better for this use, but it is
+ #deprecated
+ new_fpaths.append(ofh.name)
+ ofh.close()
+ else:
+ new_fpaths.append(ofh)
return new_fpaths
-def default_cat_joiner(out_fname, in_fnames):
+def default_cat_joiner(out_file_, in_files_):
'''It joins the given in files into the given out file.
- It requieres fnames, not fhands.
+ It works with fnames or fhands.
'''
- out_fhand = open(out_fname, 'w')
- for in_fname in in_fnames:
- in_fhand = open(in_fname, 'r')
+ #are we working with fhands or fnames?
+ file_is_str = None
+ if isinstance(out_file_, str):
+ file_is_str = True
+ else:
+ file_is_str = False
+
+ #the output fhand
+ if file_is_str:
+ out_fhand = open(out_file_, 'w')
+ else:
+ out_fhand = open(out_file_.name, 'w')
+ for in_file_ in in_files_:
+ #the input fhand
+ if file_is_str:
+ in_fhand = open(in_file_, 'r')
+ else:
+ in_fhand = open(in_file_.name, 'r')
for line in in_fhand:
out_fhand.write(line)
in_fhand.close()
out_fhand.close()
class Popen(object):
'It paralellizes the given processes divinding them into subprocesses.'
-
- def __init__(self, cmd, cmd_def=None, runner=None, runner_conf=None,
- stdout=None, stderr=None, stdin=None, splits=None):
+ def __init__(self, cmd, cmd_def=None, runner=None, stdout=None, stderr=None,
+ stdin=None, splits=None):
'''
Constructor
'''
+ #we want the same interface as subprocess.popen
+ #pylint: disable-msg=R0913
self._retcode = None
self._outputs_collected = False
#some defaults
#if the runner is not given, we use subprocess.Popen
if runner is None:
runner = StdPopen
#if the number of splits is not given we calculate them
if splits is None:
splits = self.default_splits(runner)
#we need a work dir to create the temporary split files
self._work_dir = NamedTemporaryDir()
#the main job
self._job = {'cmd': cmd, 'work_dir': self._work_dir}
#we create the new subjobs
self._jobs = self._split_jobs(cmd, cmd_def, splits, self._work_dir,
stdout=stdout, stderr=stderr, stdin=stdin)
#launch every subjobs
self._launch_jobs(self._jobs, runner=runner)
@staticmethod
def _launch_jobs(jobs, runner):
'It launches all jobs and it adds its popen instance to them'
jobs['popens'] = []
cwd = os.getcwd()
for job_index, (cmd, streams, work_dir) in enumerate(zip(jobs['cmds'],
jobs['streams'], jobs['work_dirs'])):
#the std stream can be present or not
stdin, stdout, stderr = None, None, None
if jobs['stdins']:
stdin = jobs['stdins'][job_index]
if jobs['stdouts']:
- stdouts = jobs['stdouts'][job_index]
+ stdout = jobs['stdouts'][job_index]
if jobs['stderrs']:
stderr = jobs['stderrs'][job_index]
#for every job we go to its dir to launch it
os.chdir(work_dir.name)
#we launch the job
if runner == StdPopen:
popen = runner(cmd, stdout=stdout, stderr=stderr, stdin=stdin)
else:
popen = runner(cmd, cmd_def=streams, stdout=stdout,
stderr=stderr, stdin=stdin)
#we record it's popen instane
jobs['popens'].append(popen)
os.chdir(cwd)
def _split_jobs(self, cmd, cmd_def, splits, work_dir, stdout=None,
stderr=None, stdin=None,):
''''I creates one job for every split.
Every job has a cmd, work_dir and streams, this info is in the jobs dict
with the keys: cmds, work_dirs, streams
'''
+ #too many arguments, but similar interface to our __init__
+ #pylint: disable-msg=R0913
+ #pylint: disable-msg=R0914
#the main job streams
main_job_streams = get_streams_from_cmd(cmd, cmd_def, stdout=stdout,
stderr=stderr, stdin=stdin)
self._job['streams'] = main_job_streams
streams, work_dirs = self._split_streams(main_job_streams, splits,
work_dir.name)
#now we have to create a new cmd with the right in and out streams for
#every split
cmds, stdins, stdouts, stderrs = self._create_cmds(cmd, streams)
jobs = {'cmds': cmds, 'work_dirs': work_dirs, 'streams': streams,
'stdins':stdins, 'stdouts':stdouts, 'stderrs':stderrs}
return jobs
@staticmethod
def _create_cmds(cmd, streams):
'''Given a base cmd and a steams list it creates one modified cmds for
every stream'''
#the streams is a list of streams
streamss = streams
cmds = []
stdouts = []
stdins = []
stderrs = []
for streams in streamss:
new_cmd = copy.deepcopy(cmd)
for stream in streams:
#is the stream in the cmd or in is a std one?
location = stream['cmd_location']
if location == STDIN:
stdins.append(stream['fhand'])
elif location == STDOUT:
stdouts.append(stream['fhand'])
elif location == STDERR:
stderrs.append(stream['fhand'])
else:
#we modify the cmd[location] with the new file
#we use the fname and no path because the jobs will be
#launched from the job working dir
location = stream['cmd_location']
fpath = stream['fname']
fname = os.path.split(fpath)[-1]
new_cmd[location] = fname
- cmds.append(new_cmd)
+ cmds.append(new_cmd)
return cmds, stdins, stdouts, stderrs
@staticmethod
def _split_streams(streams, splits, work_dir):
'''Given a list of streams it splits every stream in the given number of
splits'''
#which are the input and output streams?
input_stream_indexes = []
output_stream_indexes = []
for index, stream in enumerate(streams):
if stream['io'] == 'in':
input_stream_indexes.append(index)
elif stream['io'] == 'out':
output_stream_indexes.append(index)
#we create one work dir for every split
work_dirs = []
for index in range(splits):
work_dirs.append(NamedTemporaryDir(dir=work_dir))
#we have to do first the input files because the number of splits could
#be changed by them
#we split the input stream files into several splits
first = True
split_files = {}
for index in input_stream_indexes:
stream = streams[index]
#splitter
splitter = stream['splitter']
#the splitter can be a re, in that case with create the function
if '__call__' not in dir(splitter):
splitter = _create_file_splitter_with_re(splitter)
#we split the input files in the splits, every file will be in one
#of the given work_dirs
#the stream can have fname or fhands
if 'fhand' in stream:
fname = stream['fhand'].name
else:
fname = stream['fname']
files = splitter(fname, work_dirs)
#the files len can be different than splits, in that case we modify
#the splits or we raise an error
if len(files) != splits:
if first:
splits = len(files)
#we discard the empty temporary dirs
work_dirs = work_dirs[0:splits]
else:
msg = 'Not all input files were divided in the same number'
msg += ' of splits'
raise RuntimeError(msg)
first = False
split_files[index] = files #a list of files for every in stream
#we split the ouptut stream files into several splits
for index in output_stream_indexes:
stream = streams[index]
#for th output we just create the new names, but we don't split
#any file
if 'fhand' in stream:
- fname = stream['fhand'].name
+ fname = stream['fhand']
else:
fname = stream['fname']
files = _output_splitter(fname, work_dirs)
split_files[index] = files #a list of files for every in stream
new_streamss = []
#we need one new stream for every split
for split_index in range(splits):
#the streams for one job
new_streams = []
for stream_index, stream in enumerate(streams):
#we duplicate the original stream
new_stream = stream.copy()
#we set the new files
- new_stream['fhand'] = split_files[stream_index]
+ if 'fhand' in stream:
+ new_stream['fhand'] = split_files[stream_index][split_index]
+ else:
+ new_stream['fname'] = split_files[stream_index][split_index]
new_streams.append(new_stream)
new_streamss.append(new_streams)
return new_streamss, work_dirs
@staticmethod
def default_splits(runner):
'Given a runner it returns the number of splits recommended by default'
if runner is StdPopen:
#the number of processors
return os.sysconf('SC_NPROCESSORS_ONLN')
else:
return runner.default_splits()
def wait(self):
'It waits for all the works to finnish'
#we wait till all jobs finish
for job in self._jobs['popens']:
job.wait()
#now that all jobs have finished we join the results
self._collect_output_streams()
#we join now the retcodes
self._collect_retcodes()
return self._retcode
def _collect_output_streams(self):
'''It joins all the output streams into the output files and it removes
the work dirs'''
if self._outputs_collected:
return
#for each file in the main job cmd
for stream_index, stream in enumerate(self._job['streams']):
- if stream['io'] != 'in':
+ if stream['io'] == 'in':
#now we're dealing only with output files
continue
#every subjob has a part to join for this output stream
part_out_fnames = []
for streams in self._jobs['streams']:
- part_out_fnames.append(streams[stream_index]['fname'])
+ this_stream = streams[stream_index]
+ if 'fname' in this_stream:
+ part_out_fnames.append(this_stream['fname'])
+ else:
+ part_out_fnames.append(this_stream['fhand'])
#we need a function to join this stream
joiner = None
if joiner in stream:
joiner = stream['joiner']
else:
joiner = default_cat_joiner
- default_cat_joiner(stream['fname'], part_out_fnames)
+ if 'fname' in stream:
+ out_file = stream['fname']
+ else:
+ out_file = stream['fhand']
+ default_cat_joiner(out_file, part_out_fnames)
#now we can delete the tempdirs
for work_dir in self._jobs['work_dirs']:
work_dir.close()
self._outputs_collected = True
def _collect_retcodes(self):
'It gathers the retcodes from all processes'
retcode = None
for popen in self._jobs['popens']:
job_retcode = popen.returncode
if job_retcode is None:
#if some job is yet to be finished the main job is not finished
retcode = None
break
elif job_retcode != 0:
#if one job has finnished badly the main job is badly finished
retcode = job_retcode
break
#it should be 0 at this point
retcode = job_retcode
#if the retcode is not None the jobs have finished and we have to
#collect the outputs
if retcode is not None:
self._collect_output_streams()
self._retcode = retcode
return retcode
def _get_returncode(self):
'It returns the return code'
if self._retcode is None:
self._collect_retcodes()
return self._retcode
returncode = property(_get_returncode)
\ No newline at end of file
diff --git a/test/prunner_test.py b/test/prunner_test.py
index 71b78ad..86b886f 100644
--- a/test/prunner_test.py
+++ b/test/prunner_test.py
@@ -1,56 +1,53 @@
'''
Created on 16/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
import unittest
from tempfile import NamedTemporaryFile
import os
from psubprocess import Popen
from test_utils import create_test_binary
class PRunnerTest(unittest.TestCase):
'It test that we can parallelize processes'
@staticmethod
def test_basic_behaviour():
'It tests the most basic behaviour'
bin = create_test_binary()
#a simple job
in_file = NamedTemporaryFile()
in_file.write('hola')
in_file.flush()
cmd = [bin]
cmd.extend(['-i', in_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''}]
popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def)
- print open(stderr.name).read()
- print open(stdout.name).read()
- print popen.wait()
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(stdout.name).read() == 'hola'
os.remove(bin)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
\ No newline at end of file
|
JoseBlanca/psubprocess
|
67f2f03566b0a3050a5042b7c4bb0fa815dd0d39
|
Implemented basic parallelization support into prunner
|
diff --git a/psubprocess/__init__.py b/psubprocess/__init__.py
index e69de29..0a6bcc0 100644
--- a/psubprocess/__init__.py
+++ b/psubprocess/__init__.py
@@ -0,0 +1,7 @@
+'Some magic to get a nicer interface'
+
+from . import prunner
+from . import condor_runner
+
+Popen = prunner.Popen
+CondorPopen = condor_runner.Popen
\ No newline at end of file
diff --git a/psubprocess/condor_runner.py b/psubprocess/condor_runner.py
index b505d6c..ae94bba 100644
--- a/psubprocess/condor_runner.py
+++ b/psubprocess/condor_runner.py
@@ -1,240 +1,241 @@
-'''
+'''It launches processes using Condor with an interface similar to Popen
+
Created on 14/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
from tempfile import NamedTemporaryFile
import subprocess, signal, os.path
from psubprocess.streams import get_streams_from_cmd
def call(cmd, env=None, stdin=None):
'It calls a command and it returns stdout, stderr and retcode'
def subprocess_setup():
''' Python installs a SIGPIPE handler by default. This is usually not
what non-Python subprocesses expect. Taken from this url:
http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009/07/02#
2009-07-02-python-sigpipe'''
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
if stdin is None:
pstdin = None
else:
pstdin = subprocess.PIPE
process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=env, stdin=pstdin,
preexec_fn=subprocess_setup)
if stdin is None:
stdout, stderr = process.communicate()
else:
# a = stdin.read()
# print a
# stdout, stderr = subprocess.Popen.stdin = stdin
# print stdin.read()
stdout, stderr = process.communicate(stdin)
retcode = process.returncode
return stdout, stderr, retcode
def write_condor_job_file(fhand, parameters):
'It writes a condor job file using the given fhand'
to_print = 'Executable = %s\nArguments = "%s"\nUniverse = vanilla\n' % \
(parameters['executable'], parameters['arguments'])
fhand.write(to_print)
to_print = 'Log = %s\n' % parameters['log_file'].name
fhand.write(to_print)
if parameters['transfer_files']:
to_print = 'When_to_transfer_output = ON_EXIT\n'
fhand.write(to_print)
to_print = 'Getenv = True\n'
fhand.write(to_print)
to_print = 'Transfer_executable = %s\n' % parameters['transfer_executable']
fhand.write(to_print)
if 'input_fnames' in parameters and parameters['input_fnames']:
ins = ','.join(parameters['input_fnames'])
to_print = 'Transfer_input_files = %s\n' % ins
fhand.write(to_print)
if parameters['transfer_files']:
to_print = 'Should_transfer_files = IF_NEEDED\n'
fhand.write(to_print)
if 'stdout' in parameters:
to_print = 'Output = %s\n' % parameters['stdout'].name
fhand.write(to_print)
if 'stderr' in parameters:
to_print = 'Error = %s\n' % parameters['stderr'].name
fhand.write(to_print)
if 'stdin' in parameters:
to_print = 'Input = %s\n' % parameters['stdin'].name
fhand.write(to_print)
to_print = 'Queue\n'
fhand.write(to_print)
fhand.flush()
class Popen(object):
'It launches and controls a condor job'
def __init__(self, cmd, cmd_def=None, runner_conf=None,
stdout=None, stderr=None, stdin=None):
'It launches a condor job'
if cmd_def is None:
cmd_def = []
#runner conf
if runner_conf is None:
runner_conf = {}
#some defaults
if 'transfer_files' not in runner_conf:
runner_conf['transfer_files'] = True
self._log_file = NamedTemporaryFile(suffix='.log')
#create condor job file
condor_job_file = self._create_condor_job_file(cmd, cmd_def,
self._log_file,
runner_conf,
stdout, stderr, stdin)
self._condor_job_file = condor_job_file
#launch condor
self._retcode = None
self._cluster_number = None
self._launch_condor(condor_job_file)
def _launch_condor(self, condor_job_file):
'Given the condor_job_file it launches the condor job'
stdout, stderr, retcode = call(['condor_submit', condor_job_file.name])
if retcode:
msg = 'There was a problem with condor_submit: ' + stderr
raise RuntimeError(msg)
#the condor cluster number is given by condor_submit
#1 job(s) submitted to cluster 15.
for line in stdout.splitlines():
if 'submitted to cluster' in line:
self._cluster_number = line.strip().strip('.').split()[-1]
def _get_pid(self):
'It returns the condor cluster number'
return self._cluster_number
pid = property(_get_pid)
def _get_returncode(self):
'It returns the return code'
return self._retcode
returncode = property(_get_returncode)
@staticmethod
def _remove_paths_from_cmd(cmd, streams, conf):
'''It removes the absolute and relative paths from the cmd,
it returns the modified cmd'''
cmd_mod = cmd[:]
for stream in streams:
for fpath in stream['streams']:
#for the output files we can't deal with transfering files with
#paths. Condor will deliver those files into the initialdir, not
#where we expected.
if (stream['io'] != 'in' and conf['transfer_files']
and os.path.split(fpath)[-1] != fpath):
msg = 'output files with paths are not transferable'
raise ValueError(msg)
index = cmd_mod.index(fpath)
fpath = os.path.split(fpath)[-1]
cmd_mod[index] = fpath
return cmd_mod
def _create_condor_job_file(self, cmd, cmd_def, log_file, runner_conf,
stdout, stderr, stdin):
'Given a cmd and the cmd_def it returns the condor job file'
#streams
streams = get_streams_from_cmd(cmd, cmd_def)
#we need some parameters to write the condor file
parameters = {}
parameters['executable'] = cmd[0]
parameters['log_file'] = log_file
#the cmd shouldn't have absolute path in the files because they will be
#transfered to another node in the condor working dir and they wouldn't
#be found with an absolute path
cmd_no_path = self._remove_paths_from_cmd(cmd, streams, runner_conf)
parameters['arguments'] = ' '.join(cmd_no_path[1:])
if stdout is not None:
parameters['stdout'] = stdout
if stderr is not None:
parameters['stderr'] = stderr
if stdin is not None:
parameters['stdin'] = stdin
transfer_bin = False
if 'transfer_executable' in runner_conf:
transfer_bin = runner_conf['transfer_executable']
parameters['transfer_executable'] = str(transfer_bin)
transfer_files = runner_conf['transfer_executable']
parameters['transfer_files'] = str(transfer_files)
in_fnames = []
for stream in streams:
if stream['io'] == 'in':
in_fnames.extend(stream['streams'])
parameters['input_fnames'] = in_fnames
#now we can create the job file
condor_job_file = NamedTemporaryFile()
write_condor_job_file(condor_job_file, parameters=parameters)
return condor_job_file
def _update_retcode(self):
'It updates the retcode looking at the log file, it returns the retcode'
for line in open(self._log_file.name):
if 'return value' in line:
ret = line.split('return value')[1].strip().strip(')')
self._retcode = int(ret)
return self._retcode
def poll(self):
'It checks if condor has run ower condor cluster'
cluster_number = self._cluster_number
cmd = ['condor_q', cluster_number,
'-format', '"%d.\n"', 'ClusterId']
stdout, stderr, retcode = call(cmd)
if retcode:
msg = 'There was a problem with condor_q: ' + stderr
raise RuntimeError(msg)
if cluster_number not in stdout:
#the job is finished
return self._update_retcode()
return self._retcode
def wait(self):
'It waits until the condor job is finished'
stderr, retcode = call(['condor_wait', self._log_file.name])[1:]
if retcode:
msg = 'There was a problem with condor_wait: ' + stderr
raise RuntimeError(msg)
return self._update_retcode()
def kill(self):
'It runs condor_rm for the condor job'
stderr, retcode = call(['condor_rm', self.pid])[1:]
if retcode:
msg = 'There was a problem with condor_rm: ' + stderr
raise RuntimeError(msg)
return self._update_retcode()
def terminate(self):
'It runs condor_rm for the condor job'
self.kill()
diff --git a/psubprocess/prunner.py b/psubprocess/prunner.py
new file mode 100644
index 0000000..ba3fe09
--- /dev/null
+++ b/psubprocess/prunner.py
@@ -0,0 +1,471 @@
+'''It launches parallel processes with an interface similar to Popen.
+
+It divides jobs into subjobs and launches the subjobs.
+
+Created on 16/07/2009
+
+@author: jose
+'''
+
+# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
+# This file is part of psubprocess.
+# psubprocess is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+
+# psubprocess 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 Affero General Public License for more details.
+
+# You should have received a copy of the GNU Affero General Public License
+# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
+
+from subprocess import Popen as StdPopen
+import os, tempfile, shutil, copy
+
+from psubprocess.streams import get_streams_from_cmd, STDOUT, STDERR, STDIN
+
+class NamedTemporaryDir(object):
+ '''This class creates temporary directories '''
+ #pylint: disable-msg=W0622
+ #we redifine the build in dir because temfile uses that inteface
+ def __init__(self, dir=None):
+ '''It initiates the class.'''
+ self._name = tempfile.mkdtemp(dir=dir)
+ def get_name(self):
+ 'Returns path to the dict'
+ return self._name
+ name = property(get_name)
+ def close(self):
+ '''It removes the temp dir'''
+ if os.path.exists(self._name):
+ shutil.rmtree(self._name)
+ def __del__(self):
+ '''It removes de temp dir when instance is removed and the garbaje
+ colector decides it'''
+ self.close()
+
+def NamedTemporaryFile(dir=None, delete=False, suffix=''):
+ '''It creates a temporary file that won't be deleted when close
+
+ This behaviour can be done with tempfile.NamedTemporaryFile in python > 2.6
+ '''
+ fpath = tempfile.mkstemp(dir=dir, suffix=suffix)[1]
+ return open(fpath, 'w')
+
+def _calculate_divisions(num_items, splits):
+ '''It calculates how many items should be in every split to divide
+ the num_items into splits.
+ Not all splits will have an equal number of items, it will return a tuple
+ with two tuples inside:
+ ((num_fragments_1, num_items_1), (num_fragments_2, num_items_2))
+ splits = num_fragments_1 + num_fragments_2
+ num_items_1 = num_items_2 + 1
+ num_fragments_1 could be equal to 0.
+ This is the best way to create as many splits as possible as similar as
+ possible.
+ '''
+ if splits >= num_items:
+ return ((0, 1), (splits, 1))
+ num_fragments1 = num_items % splits
+ num_fragments2 = splits - num_fragments1
+ num_items2 = num_items // splits
+ num_items1 = num_items2 + 1
+ res = ((num_fragments1, num_items1), (num_fragments2, num_items2))
+ return res
+
+def _write_file(dir, contents, suffix):
+ '''It creates a new file with the given contents. It returns the path'''
+ ofh = NamedTemporaryFile(dir=dir, delete=False, suffix=suffix)
+ ofh.write(contents)
+ #the file won't be deleted, just closed,
+ #it will be deleted because is created in a
+ #temporary directory
+ fname = ofh.name
+ ofh.flush()
+ ofh.close()
+ return fname
+
+def _create_file_splitter_with_re(expression):
+ '''Given an expression it creates a file splitter.
+
+ The expression can be a regex or an str.
+ The item in the file will be defined everytime a line matches the
+ expression.
+ '''
+ expression_kind = None
+ if isinstance(expression, str):
+ expression_kind = 'str'
+ else:
+ expression_kind = 're'
+ def splitter(fname, work_dirs):
+ '''It splits the given file into several splits.
+
+ Every split will be located in one of the work_dirs, although it is not
+ guaranteed to create as many splits as work dirs. If in the file there
+ are less items than work_dirs some work_dirs will be left empty.
+ It returns a list with the fpaths for the splitted files.
+ '''
+ #how many splits do we want?
+ nsplits = len(work_dirs)
+ #how many items are in the file? We assume that all files have the same
+ #number of items
+ nitems = 0
+ for line in open(fname, 'r'):
+ if ((expression_kind == 'str' and expression in line) or
+ expression.search(line)):
+ nitems += 1
+
+ #how many splits a we going to create? and how many items will be in
+ #every split
+ #if there are more items than splits we create as many splits as items
+ if nsplits > nitems:
+ nsplits = nitems
+ (nsplits1, nitems1), (nsplits2, nitems2) = _calculate_divisions(nitems,
+ nsplits)
+ #we have to create nsplits1 files with nitems1 in it and nsplits2 files
+ #with nitems2 items in it
+ splits_made = 0
+ new_fpaths = []
+ fhand = open(fname, 'r')
+ for index_splits, nsplits in enumerate((nsplits1, nsplits2)):
+ nitems = (nitems1, nitems2)[index_splits]
+ #we have to create nsplits files with nitems in it
+ for index in range(nsplits):
+ items_sofar = 0
+ sofar = fhand.readline()
+ suffix = os.path.splitext(fname)[-1]
+ splits_made = 0
+ for line in fhand:
+ #has the file the required pattern?
+ if ((expression_kind == 'str' and expression in line) or
+ expression.search(line)):
+ items_sofar += 1
+ if items_sofar >= nitems:
+ #how many splits do we have now for this file?
+ splits_now = splits_made
+ #which is the work dir in which this file
+ #should be located?
+ work_dir = work_dirs[splits_made]
+ ofname = _write_file(work_dir.name, sofar, suffix)
+ new_fpaths.append(ofname)
+ sofar = line
+ items_sofar = 0
+ splits_made += 1
+ else:
+ sofar += line
+ else:
+ sofar += line
+ #now we write the last file
+ work_dir = work_dirs[splits_made]
+ ofname = _write_file(work_dir.name, sofar, suffix)
+ new_fpaths.append(ofname)
+ return new_fpaths
+ return splitter
+
+def _output_splitter(fname, work_dirs):
+ '''It creates one output file for every splits.
+
+ Every split will be located in one of the work_dirs.
+ It returns a list with the fpaths for the new output files.
+ '''
+ #how many splits do we want?
+ nsplits = len(work_dirs)
+
+ new_fpaths = []
+ #we have to create nsplits
+ for split_index in range(nsplits):
+ suffix = os.path.splitext(fname)[-1]
+ work_dir = work_dirs[split_index]
+ ofh = tempfile.NamedTemporaryFile(dir=work_dir.name, suffix=suffix)
+ #the file will be deleted
+ #it will be deleted because we just need the name in the temporary
+ #directory. tempfile.mktemp would be better for this use, but it is
+ #deprecated
+ new_fpaths.append(ofh.name)
+ ofh.close()
+ return new_fpaths
+
+def default_cat_joiner(out_fname, in_fnames):
+ '''It joins the given in files into the given out file.
+
+ It requieres fnames, not fhands.
+ '''
+ out_fhand = open(out_fname, 'w')
+ for in_fname in in_fnames:
+ in_fhand = open(in_fname, 'r')
+ for line in in_fhand:
+ out_fhand.write(line)
+ in_fhand.close()
+ out_fhand.close()
+
+class Popen(object):
+ 'It paralellizes the given processes divinding them into subprocesses.'
+
+ def __init__(self, cmd, cmd_def=None, runner=None, runner_conf=None,
+ stdout=None, stderr=None, stdin=None, splits=None):
+ '''
+ Constructor
+ '''
+ self._retcode = None
+ self._outputs_collected = False
+ #some defaults
+ #if the runner is not given, we use subprocess.Popen
+ if runner is None:
+ runner = StdPopen
+ #if the number of splits is not given we calculate them
+ if splits is None:
+ splits = self.default_splits(runner)
+
+ #we need a work dir to create the temporary split files
+ self._work_dir = NamedTemporaryDir()
+
+ #the main job
+ self._job = {'cmd': cmd, 'work_dir': self._work_dir}
+ #we create the new subjobs
+ self._jobs = self._split_jobs(cmd, cmd_def, splits, self._work_dir,
+ stdout=stdout, stderr=stderr, stdin=stdin)
+
+ #launch every subjobs
+ self._launch_jobs(self._jobs, runner=runner)
+
+ @staticmethod
+ def _launch_jobs(jobs, runner):
+ 'It launches all jobs and it adds its popen instance to them'
+ jobs['popens'] = []
+ cwd = os.getcwd()
+ for job_index, (cmd, streams, work_dir) in enumerate(zip(jobs['cmds'],
+ jobs['streams'], jobs['work_dirs'])):
+ #the std stream can be present or not
+ stdin, stdout, stderr = None, None, None
+ if jobs['stdins']:
+ stdin = jobs['stdins'][job_index]
+ if jobs['stdouts']:
+ stdouts = jobs['stdouts'][job_index]
+ if jobs['stderrs']:
+ stderr = jobs['stderrs'][job_index]
+ #for every job we go to its dir to launch it
+ os.chdir(work_dir.name)
+ #we launch the job
+ if runner == StdPopen:
+ popen = runner(cmd, stdout=stdout, stderr=stderr, stdin=stdin)
+ else:
+ popen = runner(cmd, cmd_def=streams, stdout=stdout,
+ stderr=stderr, stdin=stdin)
+ #we record it's popen instane
+ jobs['popens'].append(popen)
+ os.chdir(cwd)
+
+ def _split_jobs(self, cmd, cmd_def, splits, work_dir, stdout=None,
+ stderr=None, stdin=None,):
+ ''''I creates one job for every split.
+
+ Every job has a cmd, work_dir and streams, this info is in the jobs dict
+ with the keys: cmds, work_dirs, streams
+ '''
+ #the main job streams
+ main_job_streams = get_streams_from_cmd(cmd, cmd_def, stdout=stdout,
+ stderr=stderr, stdin=stdin)
+ self._job['streams'] = main_job_streams
+
+ streams, work_dirs = self._split_streams(main_job_streams, splits,
+ work_dir.name)
+
+ #now we have to create a new cmd with the right in and out streams for
+ #every split
+ cmds, stdins, stdouts, stderrs = self._create_cmds(cmd, streams)
+
+ jobs = {'cmds': cmds, 'work_dirs': work_dirs, 'streams': streams,
+ 'stdins':stdins, 'stdouts':stdouts, 'stderrs':stderrs}
+ return jobs
+
+ @staticmethod
+ def _create_cmds(cmd, streams):
+ '''Given a base cmd and a steams list it creates one modified cmds for
+ every stream'''
+ #the streams is a list of streams
+ streamss = streams
+ cmds = []
+ stdouts = []
+ stdins = []
+ stderrs = []
+ for streams in streamss:
+ new_cmd = copy.deepcopy(cmd)
+ for stream in streams:
+ #is the stream in the cmd or in is a std one?
+ location = stream['cmd_location']
+ if location == STDIN:
+ stdins.append(stream['fhand'])
+ elif location == STDOUT:
+ stdouts.append(stream['fhand'])
+ elif location == STDERR:
+ stderrs.append(stream['fhand'])
+ else:
+ #we modify the cmd[location] with the new file
+ #we use the fname and no path because the jobs will be
+ #launched from the job working dir
+ location = stream['cmd_location']
+ fpath = stream['fname']
+ fname = os.path.split(fpath)[-1]
+ new_cmd[location] = fname
+ cmds.append(new_cmd)
+ return cmds, stdins, stdouts, stderrs
+
+ @staticmethod
+ def _split_streams(streams, splits, work_dir):
+ '''Given a list of streams it splits every stream in the given number of
+ splits'''
+ #which are the input and output streams?
+ input_stream_indexes = []
+ output_stream_indexes = []
+ for index, stream in enumerate(streams):
+ if stream['io'] == 'in':
+ input_stream_indexes.append(index)
+ elif stream['io'] == 'out':
+ output_stream_indexes.append(index)
+
+ #we create one work dir for every split
+ work_dirs = []
+ for index in range(splits):
+ work_dirs.append(NamedTemporaryDir(dir=work_dir))
+
+ #we have to do first the input files because the number of splits could
+ #be changed by them
+ #we split the input stream files into several splits
+ first = True
+ split_files = {}
+ for index in input_stream_indexes:
+ stream = streams[index]
+ #splitter
+ splitter = stream['splitter']
+ #the splitter can be a re, in that case with create the function
+ if '__call__' not in dir(splitter):
+ splitter = _create_file_splitter_with_re(splitter)
+ #we split the input files in the splits, every file will be in one
+ #of the given work_dirs
+ #the stream can have fname or fhands
+ if 'fhand' in stream:
+ fname = stream['fhand'].name
+ else:
+ fname = stream['fname']
+ files = splitter(fname, work_dirs)
+ #the files len can be different than splits, in that case we modify
+ #the splits or we raise an error
+ if len(files) != splits:
+ if first:
+ splits = len(files)
+ #we discard the empty temporary dirs
+ work_dirs = work_dirs[0:splits]
+ else:
+ msg = 'Not all input files were divided in the same number'
+ msg += ' of splits'
+ raise RuntimeError(msg)
+ first = False
+ split_files[index] = files #a list of files for every in stream
+
+ #we split the ouptut stream files into several splits
+ for index in output_stream_indexes:
+ stream = streams[index]
+ #for th output we just create the new names, but we don't split
+ #any file
+ if 'fhand' in stream:
+ fname = stream['fhand'].name
+ else:
+ fname = stream['fname']
+ files = _output_splitter(fname, work_dirs)
+ split_files[index] = files #a list of files for every in stream
+
+ new_streamss = []
+ #we need one new stream for every split
+ for split_index in range(splits):
+ #the streams for one job
+ new_streams = []
+ for stream_index, stream in enumerate(streams):
+ #we duplicate the original stream
+ new_stream = stream.copy()
+ #we set the new files
+ new_stream['fhand'] = split_files[stream_index]
+ new_streams.append(new_stream)
+ new_streamss.append(new_streams)
+
+ return new_streamss, work_dirs
+
+ @staticmethod
+ def default_splits(runner):
+ 'Given a runner it returns the number of splits recommended by default'
+ if runner is StdPopen:
+ #the number of processors
+ return os.sysconf('SC_NPROCESSORS_ONLN')
+ else:
+ return runner.default_splits()
+
+ def wait(self):
+ 'It waits for all the works to finnish'
+ #we wait till all jobs finish
+ for job in self._jobs['popens']:
+ job.wait()
+ #now that all jobs have finished we join the results
+ self._collect_output_streams()
+ #we join now the retcodes
+ self._collect_retcodes()
+ return self._retcode
+
+ def _collect_output_streams(self):
+ '''It joins all the output streams into the output files and it removes
+ the work dirs'''
+ if self._outputs_collected:
+ return
+ #for each file in the main job cmd
+ for stream_index, stream in enumerate(self._job['streams']):
+ if stream['io'] != 'in':
+ #now we're dealing only with output files
+ continue
+ #every subjob has a part to join for this output stream
+ part_out_fnames = []
+ for streams in self._jobs['streams']:
+ part_out_fnames.append(streams[stream_index]['fname'])
+ #we need a function to join this stream
+ joiner = None
+ if joiner in stream:
+ joiner = stream['joiner']
+ else:
+ joiner = default_cat_joiner
+ default_cat_joiner(stream['fname'], part_out_fnames)
+
+ #now we can delete the tempdirs
+ for work_dir in self._jobs['work_dirs']:
+ work_dir.close()
+
+ self._outputs_collected = True
+
+ def _collect_retcodes(self):
+ 'It gathers the retcodes from all processes'
+ retcode = None
+ for popen in self._jobs['popens']:
+ job_retcode = popen.returncode
+ if job_retcode is None:
+ #if some job is yet to be finished the main job is not finished
+ retcode = None
+ break
+ elif job_retcode != 0:
+ #if one job has finnished badly the main job is badly finished
+ retcode = job_retcode
+ break
+ #it should be 0 at this point
+ retcode = job_retcode
+
+ #if the retcode is not None the jobs have finished and we have to
+ #collect the outputs
+ if retcode is not None:
+ self._collect_output_streams()
+ self._retcode = retcode
+ return retcode
+
+ def _get_returncode(self):
+ 'It returns the return code'
+ if self._retcode is None:
+ self._collect_retcodes()
+ return self._retcode
+ returncode = property(_get_returncode)
\ No newline at end of file
diff --git a/psubprocess/streams.py b/psubprocess/streams.py
index 3ff10f3..47000ae 100644
--- a/psubprocess/streams.py
+++ b/psubprocess/streams.py
@@ -1,110 +1,102 @@
'''
Created on 13/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of project.
# project is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# project 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with project. If not, see <http://www.gnu.org/licenses/>.
STDIN = 'stdin'
STDOUT = 'stdout'
STDERR = 'stderr'
def _find_param_def_in_cmd(cmd, param_def):
'''Given a cmd and a parameter definition it returns the index of the param
in the cmd.
If the param is not found in the cmd it will raise a ValueError.
'''
options = param_def['options']
#options could be a list or an item
if not isinstance(options, list) and not isinstance(options, tuple):
options = (options,)
#the standard options with command line options
for index, item in enumerate(cmd):
if item in options:
return index
raise ValueError('Parameter not found in the given cmd')
def _positive_int(index, sequence):
'''It returns the same int index, but positive.'''
if index is None:
return None
elif index < 0:
return len(sequence) + index
return index
-def get_streams_from_cmd(cmd, cmd_def):
+def get_streams_from_cmd(cmd, cmd_def, stdout=None, stdin=None, stderr=None):
'Given a cmd and a cmd definition it returns the streams'
streams = []
for param_def in cmd_def:
options = param_def['options']
stream_values = []
- #is the parameter defining an std stream?
- for stream in (STDIN, STDOUT, STDERR):
- #options can be an item or an iterable
- if stream == options or ('__in__' in dir(options) and
- stream in options):
- stream_values = [stream]
- #if it isn't an standard stream we have to look for the stream
- if not stream_values:
- #where are the stream values after the parameter?
- if 'cmd_locations' in param_def:
- locations = param_def['cmd_locations']
- else:
- #by the default we want the first item after the parameter
- locations = slice(0, 1)
- #if the location is not a list we make it
- try:
- #pylint: disable-msg=W0104
- #the statement has an effect because we're cheking
- #if the locations is a slice or an int
- locations.stop
- locations.start
- except AttributeError:
- locations = slice(locations, locations + 1)
-
- #where is the parameter in the cmd list?
- #if the param options is not an int or a slice, its a list of
- #strings
- if isinstance(options, int):
- #for PRE_ARG (1) and POST_ARG (-1)
- #we take 1 unit because the options should be 1 to the right
- #of the value
- index = _positive_int(options, cmd) - 1
- else:
- #look for param in cmd
- try:
- index = _find_param_def_in_cmd(cmd, param_def)
- except ValueError:
- index = None
+ #where is this stream located in the cmd?
+ location = None
- #get the stream values
- if index is not None:
- #now we add the index to the location, because the
- #location is relative to where the parameter is found
- locations = slice(locations.start + index + 1,
- locations.stop + index + 1)
+ #we have to look for the stream in the cmd
+ #where is the parameter in the cmd list?
+ #if the param options is not an int, its a list of strings
+ if isinstance(options, int):
+ #for PRE_ARG (1) and POST_ARG (-1)
+ #we take 1 unit because the options should be 1 to the right
+ #of the value
+ index = _positive_int(options, cmd) - 1
+ else:
+ #look for param in cmd
+ try:
+ index = _find_param_def_in_cmd(cmd, param_def)
+ except ValueError:
+ index = None
- stream_values = cmd[locations]
+ #get the stream values
+ if index is not None:
+ location = index + 1
+ stream_values = cmd[location]
#create the result dict
stream = param_def.copy()
- stream['streams'] = stream_values
+ stream['fname'] = stream_values
+ stream['cmd_location'] = location
+ streams.append(stream)
+
+ #We have to add also the stdin, stdout and stderr
+ for stream_name, fhand in ((STDIN, stdin), (STDOUT, stdout),
+ (STDERR, stderr)):
+ if fhand is None:
+ continue
+ io_value = None
+ if stream_name == STDIN:
+ io_value = 'in'
+ else:
+ io_value = 'out'
+ stream = {}
+ stream['fhand'] = fhand
+ stream['io'] = io_value
+ stream['cmd_location'] = stream_name
streams.append(stream)
return streams
\ No newline at end of file
diff --git a/test/cmd_def_test.py b/test/cmd_def_test.py
index fd3828d..84677ab 100644
--- a/test/cmd_def_test.py
+++ b/test/cmd_def_test.py
@@ -1,151 +1,149 @@
'''
Created on 13/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
import unittest
from psubprocess.streams import (get_streams_from_cmd,
STDIN, STDOUT, STDERR)
#What's a stream
#
#A command takes some input streams and creates some ouput streams
#An stream is a file-like object or a directory. In fact an stream can be
#composed by several files (e.g. a seq and a qual file that should be splitted
#together)
#
#Kinds of streams in a cmd
#cmd arg1 arg2 -i opt1 opt2 -j opt3 arg3 < stdin > stdout stderr retcode
#in this general command there are several types of streams:
# - previous arguments. arguments (without options) located before the first
# option (like arg1 and arg2)
# - options with one option, like opt3
# - options with several arguments, like -i that has opt1 and opt2
# - arguments (aka post_arguments). arguments located after the last option
# - stdin, stdout, stderr and retcode. The standard ones.
#
#How to define the streams
#An stream is defined by a dict with the following keys: options, io, splitter,
#value, special, location. All of them are optional except the options.
#Options: It defines in which options or arguments is the stream found. It
#should by just a value or a tuple.
#Options kinds:
# - -i the stream will be located after the parameter -i
# - (-o, --output) the stream will be after -o or --output
# - PRE_ARG right after the cmd and before the first parameter
# - POST_ARG after the last option
# - STDIN
# - STDOUT
# - STDERR
#io: It defines if it's an input or an output stream for the cmd
#splitter: It defines how the stream should be split. There are three ways of
#definint it:
# - an str that will be used to scan through the in streams, every
# line with the str in in will be considered a token start
# e.g '>' for the blast files
# - a re every line with a match will be considered a token start
# - a function the function should take the stream an return an
# iterator with the tokens
#joiner: A function that should take the out streams for all jobs and return
#the joined stream. If not given the output stream will be just concatenated.
#value: the value for the stream, this stream will not define the value in the
#command line, it will be implicit
#special: It defines some special treaments for the streams.
# - no_split It shouldn't be split
# - no_transfer It shouldn't be transfer to all nodes
# - no_abspath Its path shouldn't be converted to absolute
# - create It should be created before running the command
# - no_support An error should be raised if used.
#cmd_locations: If the location is not given the assumed location will be 0.
#That means that the stream will be located in the 0 position after the option.
#It can be either an int or an slice. In the slice case several substreams will
#be taken together in the stream. Useful for instance for the case of two fasta
#files with the seq an qual that should be split together and transfered
#together.
def _check_streams(streams, expected_streams):
'It checks that streams meet the requirements set by the expected streams'
for stream, expected_stream in zip(streams, expected_streams):
for key in expected_stream:
assert stream[key] == expected_stream[key]
class StreamsFromCmdTest(unittest.TestCase):
'It tests that we can get the input and output files from the cmd'
@staticmethod
def test_simple_case():
'It tests the most simple cases'
#a simple case
cmd = ['hola', '-i', 'caracola.txt']
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'}]
- expected_streams = [{'streams': ['caracola.txt'], 'io':'in'}]
- streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
- _check_streams(streams, expected_streams)
-
- #with two files
- cmd = ['hola', '-i', 'seq.txt', 'qual.txt']
- cmd_def = [{'options': ('-i', '--input'), 'io': 'in',
- 'cmd_locations':slice(0, 2)}]
- expected_streams = [{'streams': ['seq.txt', 'qual.txt'],
- 'io':'in'}]
+ expected_streams = [{'fname': 'caracola.txt', 'io':'in',
+ 'cmd_location':2}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
#a parameter not found in the cmd
cmd = ['hola', '-i', 'caracola.txt']
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
{'options': ('-j', '--input2'), 'io': 'in'}]
- expected_streams = [{'streams': ['caracola.txt'], 'io':'in'}]
+ expected_streams = [{'fname': 'caracola.txt', 'io':'in',
+ 'cmd_location': 2}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
@staticmethod
def test_arguments():
'It test that it works with cmd arguments, not options'
#the options we want is in the pre_argv, after the binary
cmd = ['hola', 'hola.txt', '-i', 'caracola.txt']
cmd_def = [{'options': 1, 'io': 'in'}]
- expected_streams = [{'streams': ['hola.txt'], 'io':'in'}]
+ expected_streams = [{'fname': 'hola.txt', 'io':'in',
+ 'cmd_location':1}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
#the option we want is at the end of the cmd
cmd = ['hola', '-i', 'caracola.txt', 'hola.txt']
cmd_def = [{'options': -1, 'io': 'in'}]
- expected_streams = [{'streams': ['hola.txt'], 'io':'in'}]
+ expected_streams = [{'fname': 'hola.txt', 'io':'in',
+ 'cmd_location':3}]
streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
_check_streams(streams, expected_streams)
@staticmethod
def test_stdin():
'We want stdin, stdout and stderr as streams'
#stdin
cmd = ['hola']
- cmd_def = [{'options': STDIN, 'io': 'in'},
- {'options': STDOUT, 'io': 'out'},
- {'options': STDERR, 'io': 'out'}]
- expected_streams = [{'streams': [STDIN], 'io':'in'},
- {'streams': [STDOUT], 'io':'out'},
- {'streams': [STDERR], 'io':'out'}]
- streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
+ cmd_def = []
+ stdout = 'stdout' #in the real world they will be files
+ stderr = 'stderr'
+ stdin = 'stdin'
+
+ expected_streams = [{'fhand': stdin, 'io':'in', 'cmd_location':STDIN},
+ {'fhand': stdout, 'io':'out', 'cmd_location':STDOUT},
+ {'fhand': stderr, 'io':'out', 'cmd_location':STDERR}]
+ streams = get_streams_from_cmd(cmd, cmd_def=cmd_def, stdout=stdout,
+ stderr=stderr, stdin=stdin)
_check_streams(streams, expected_streams)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
\ No newline at end of file
diff --git a/test/condor_runner_test.py b/test/condor_runner_test.py
index 147857d..38dacb9 100644
--- a/test/condor_runner_test.py
+++ b/test/condor_runner_test.py
@@ -1,220 +1,170 @@
'''
Created on 14/07/2009
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of psubprocess.
# psubprocess is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# psubprocess 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
import unittest
from tempfile import NamedTemporaryFile
from StringIO import StringIO
-import os, stat
+import os
from psubprocess.condor_runner import write_condor_job_file, Popen
-
-TEST_BINARY = '''#!/usr/bin/python
-import sys, shutil, os
-
-args = sys.argv
-
-#-o something send something to stdout
-#-e something send something to stderr
-#-i some_file send the file content to sdout
-#-t some_file copy the -i file to -t file
-#-s and stdin write stdin to stout
-#-r a number return this retcode
-
-#are the commands in the argv?
-arg_indexes = {}
-for param in ('-o', '-e', '-i', '-t', '-s', '-r'):
- try:
- arg_indexes[param] = args.index(param)
- except ValueError:
- arg_indexes[param] = None
-
-#stdout, stderr
-if arg_indexes['-o']:
- sys.stdout.write(args[arg_indexes['-o'] + 1])
-if arg_indexes['-e']:
- sys.stderr.write(args[arg_indexes['-e'] + 1])
-#-i -t
-if arg_indexes['-i'] and not arg_indexes['-t']:
- sys.stdout.write(open(args[arg_indexes['-i'] + 1]).read())
-elif arg_indexes['-i'] and arg_indexes['-t']:
- shutil.copy(args[arg_indexes['-i'] + 1], args[arg_indexes['-t'] + 1])
-#stdin
-if arg_indexes['-s']:
- stdin = sys.stdin.read()
- sys.stdout.write(stdin)
-#retcode
-if arg_indexes['-r']:
- retcode = int(args[arg_indexes['-r'] + 1])
-else:
- retcode = 0
-sys.exit(retcode)
-'''
-
-def _create_test_binary():
- 'It creates a file with a test python binary in it'
- fhand = NamedTemporaryFile(suffix='.py')
- fhand.write(TEST_BINARY)
- fhand.flush()
- #it should be executable
- os.chmod(fhand.name, stat.S_IXOTH | stat.S_IRWXU)
- return fhand
+from test_utils import create_test_binary
class CondorRunnerTest(unittest.TestCase):
'It tests the condor runner'
@staticmethod
def test_write_condor_job_file():
'It tests that we can write a condor job file with the right parameters'
fhand1 = NamedTemporaryFile()
fhand2 = NamedTemporaryFile()
flog = NamedTemporaryFile()
stderr_ = NamedTemporaryFile()
stdout_ = NamedTemporaryFile()
stdin_ = NamedTemporaryFile()
expected = '''Executable = bin
Arguments = "-i %s -j %s"
Universe = vanilla
Log = %s
When_to_transfer_output = ON_EXIT
Getenv = True
Transfer_executable = True
Transfer_input_files = %s,%s
Should_transfer_files = IF_NEEDED
Output = %s
Error = %s
Input = %s
Queue
''' % (fhand1.name, fhand2.name, flog.name, fhand1.name, fhand2.name,
stdout_.name, stderr_.name, stdin_.name)
fhand = StringIO()
parameters = {'executable':'bin', 'log_file':flog,
'input_fnames':[fhand1.name, fhand2.name],
'arguments':'-i %s -j %s' % (fhand1.name, fhand2.name),
'transfer_executable':True, 'transfer_files':True,
'stdout':stdout_, 'stderr':stderr_, 'stdin':stdin_}
write_condor_job_file(fhand, parameters=parameters)
condor = fhand.getvalue()
assert condor == expected
@staticmethod
def test_run_condor_stdout():
'It test that we can run condor job and retrieve stdout and stderr'
- bin = _create_test_binary()
+ bin = create_test_binary()
#a simple job
cmd = [bin.name]
cmd.extend(['-o', 'hola', '-e', 'caracola'])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stderr=stderr)
assert popen.wait() == 0 #waits till finishes and looks to the retcode
assert open(stdout.name).read() == 'hola'
assert open(stderr.name).read() == 'caracola'
@staticmethod
def test_run_condor_stdin():
'It test that we can run condor job with stdin'
- bin = _create_test_binary()
+ bin = create_test_binary()
#a simple job
cmd = [bin.name]
cmd.extend(['-s'])
stdin = NamedTemporaryFile()
stdout = NamedTemporaryFile()
stdin.write('hola')
stdin.flush()
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stdin=stdin)
assert popen.wait() == 0 #waits till finishes and looks to the retcode
assert open(stdout.name).read() == 'hola'
@staticmethod
def test_run_condor_retcode():
'It test that we can run condor job and get the retcode'
- bin = _create_test_binary()
+ bin = create_test_binary()
#a simple job
cmd = [bin.name]
cmd.extend(['-r', '10'])
popen = Popen(cmd, runner_conf={'transfer_executable':True})
assert popen.wait() == 10 #waits till finishes and looks to the retcode
@staticmethod
def test_run_condor_in_file():
'It test that we can run condor job with an input file'
- bin = _create_test_binary()
+ bin = create_test_binary()
in_file = NamedTemporaryFile()
in_file.write('hola')
in_file.flush()
cmd = [bin.name]
cmd.extend(['-i', in_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'}]
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stderr=stderr, cmd_def=cmd_def)
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(stdout.name).read() == 'hola'
def test_run_condor_in_out_file(self):
'It test that we can run condor job with an output file'
- bin = _create_test_binary()
+ bin = create_test_binary()
in_file = NamedTemporaryFile()
in_file.write('hola')
in_file.flush()
out_file = open('output.txt', 'w')
cmd = [bin.name]
cmd.extend(['-i', in_file.name, '-t', out_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
{'options': ('-t', '--output'), 'io': 'out'}]
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stderr=stderr, cmd_def=cmd_def)
popen.wait()
assert popen.wait() == 0 #waits till finishes and looks to the retcod
assert open(out_file.name).read() == 'hola'
os.remove(out_file.name)
#and output file with path won't be allowed unless the transfer file
#mechanism is not used
out_file = NamedTemporaryFile()
cmd = [bin.name]
cmd.extend(['-i', in_file.name, '-t', out_file.name])
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
{'options': ('-t', '--output'), 'io': 'out'}]
try:
popen = Popen(cmd, runner_conf={'transfer_executable':True},
stdout=stdout, stderr=stderr, cmd_def=cmd_def)
self.fail('ValueError expected')
#pylint: disable-msg=W0704
except ValueError:
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
\ No newline at end of file
diff --git a/test/prunner_test.py b/test/prunner_test.py
new file mode 100644
index 0000000..71b78ad
--- /dev/null
+++ b/test/prunner_test.py
@@ -0,0 +1,56 @@
+'''
+Created on 16/07/2009
+
+@author: jose
+'''
+
+# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
+# This file is part of psubprocess.
+# psubprocess is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+
+# psubprocess 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 Affero General Public License for more details.
+
+# You should have received a copy of the GNU Affero General Public License
+# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
+
+import unittest
+from tempfile import NamedTemporaryFile
+import os
+
+from psubprocess import Popen
+from test_utils import create_test_binary
+
+class PRunnerTest(unittest.TestCase):
+ 'It test that we can parallelize processes'
+
+ @staticmethod
+ def test_basic_behaviour():
+ 'It tests the most basic behaviour'
+ bin = create_test_binary()
+ #a simple job
+ in_file = NamedTemporaryFile()
+ in_file.write('hola')
+ in_file.flush()
+
+ cmd = [bin]
+ cmd.extend(['-i', in_file.name])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in', 'splitter':''}]
+ popen = Popen(cmd, stdout=stdout, stderr=stderr, cmd_def=cmd_def)
+ print open(stderr.name).read()
+ print open(stdout.name).read()
+ print popen.wait()
+ assert popen.wait() == 0 #waits till finishes and looks to the retcod
+ assert open(stdout.name).read() == 'hola'
+ os.remove(bin)
+
+if __name__ == "__main__":
+ #import sys;sys.argv = ['', 'Test.testName']
+ unittest.main()
\ No newline at end of file
diff --git a/test/test_utils.py b/test/test_utils.py
new file mode 100644
index 0000000..f0f87d2
--- /dev/null
+++ b/test/test_utils.py
@@ -0,0 +1,77 @@
+'''
+Created on 16/07/2009
+
+@author: jose
+'''
+
+# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
+# This file is part of psubprocess.
+# psubprocess is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+
+# psubprocess 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 Affero General Public License for more details.
+
+# You should have received a copy of the GNU Affero General Public License
+# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
+
+from tempfile import NamedTemporaryFile
+import os, stat, shutil
+
+TEST_BINARY = '''#!/usr/bin/env python
+import sys, shutil, os
+
+args = sys.argv
+
+#-o something send something to stdout
+#-e something send something to stderr
+#-i some_file send the file content to sdout
+#-t some_file copy the -i file to -t file
+#-s and stdin write stdin to stout
+#-r a number return this retcode
+
+#are the commands in the argv?
+arg_indexes = {}
+for param in ('-o', '-e', '-i', '-t', '-s', '-r'):
+ try:
+ arg_indexes[param] = args.index(param)
+ except ValueError:
+ arg_indexes[param] = None
+
+#stdout, stderr
+if arg_indexes['-o']:
+ sys.stdout.write(args[arg_indexes['-o'] + 1])
+if arg_indexes['-e']:
+ sys.stderr.write(args[arg_indexes['-e'] + 1])
+#-i -t
+if arg_indexes['-i'] and not arg_indexes['-t']:
+ sys.stdout.write(open(args[arg_indexes['-i'] + 1]).read())
+elif arg_indexes['-i'] and arg_indexes['-t']:
+ shutil.copy(args[arg_indexes['-i'] + 1], args[arg_indexes['-t'] + 1])
+#stdin
+if arg_indexes['-s']:
+ stdin = sys.stdin.read()
+ sys.stdout.write(stdin)
+#retcode
+if arg_indexes['-r']:
+ retcode = int(args[arg_indexes['-r'] + 1])
+else:
+ retcode = 0
+sys.exit(retcode)
+'''
+
+def create_test_binary():
+ 'It creates a file with a test python binary in it'
+ fhand = NamedTemporaryFile(suffix='.py')
+ fhand.write(TEST_BINARY)
+ fhand.flush()
+ os.chmod(fhand.name, stat.S_IXOTH | stat.S_IRWXU)
+ fname = '/tmp/test_cmd.py'
+ shutil.copy(fhand.name, fname)
+ fhand.close()
+ #it should be executable
+ return fname
|
JoseBlanca/psubprocess
|
9453d7c35d915c4426a91bc295a4cc1ec4c86b0e
|
Implemented a condor launcher with an interface similar to subprocess.popen
|
diff --git a/psubprocess/condor_runner.py b/psubprocess/condor_runner.py
new file mode 100644
index 0000000..b505d6c
--- /dev/null
+++ b/psubprocess/condor_runner.py
@@ -0,0 +1,240 @@
+'''
+Created on 14/07/2009
+
+@author: jose
+'''
+
+# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
+# This file is part of psubprocess.
+# psubprocess is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+
+# psubprocess 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 Affero General Public License for more details.
+
+# You should have received a copy of the GNU Affero General Public License
+# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
+
+from tempfile import NamedTemporaryFile
+import subprocess, signal, os.path
+
+from psubprocess.streams import get_streams_from_cmd
+
+def call(cmd, env=None, stdin=None):
+ 'It calls a command and it returns stdout, stderr and retcode'
+ def subprocess_setup():
+ ''' Python installs a SIGPIPE handler by default. This is usually not
+ what non-Python subprocesses expect. Taken from this url:
+ http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009/07/02#
+ 2009-07-02-python-sigpipe'''
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
+
+ if stdin is None:
+ pstdin = None
+ else:
+ pstdin = subprocess.PIPE
+
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, env=env, stdin=pstdin,
+ preexec_fn=subprocess_setup)
+ if stdin is None:
+ stdout, stderr = process.communicate()
+ else:
+# a = stdin.read()
+# print a
+# stdout, stderr = subprocess.Popen.stdin = stdin
+# print stdin.read()
+ stdout, stderr = process.communicate(stdin)
+ retcode = process.returncode
+ return stdout, stderr, retcode
+
+def write_condor_job_file(fhand, parameters):
+ 'It writes a condor job file using the given fhand'
+ to_print = 'Executable = %s\nArguments = "%s"\nUniverse = vanilla\n' % \
+ (parameters['executable'], parameters['arguments'])
+ fhand.write(to_print)
+ to_print = 'Log = %s\n' % parameters['log_file'].name
+ fhand.write(to_print)
+ if parameters['transfer_files']:
+ to_print = 'When_to_transfer_output = ON_EXIT\n'
+ fhand.write(to_print)
+ to_print = 'Getenv = True\n'
+ fhand.write(to_print)
+ to_print = 'Transfer_executable = %s\n' % parameters['transfer_executable']
+ fhand.write(to_print)
+ if 'input_fnames' in parameters and parameters['input_fnames']:
+ ins = ','.join(parameters['input_fnames'])
+ to_print = 'Transfer_input_files = %s\n' % ins
+ fhand.write(to_print)
+ if parameters['transfer_files']:
+ to_print = 'Should_transfer_files = IF_NEEDED\n'
+ fhand.write(to_print)
+ if 'stdout' in parameters:
+ to_print = 'Output = %s\n' % parameters['stdout'].name
+ fhand.write(to_print)
+ if 'stderr' in parameters:
+ to_print = 'Error = %s\n' % parameters['stderr'].name
+ fhand.write(to_print)
+ if 'stdin' in parameters:
+ to_print = 'Input = %s\n' % parameters['stdin'].name
+ fhand.write(to_print)
+ to_print = 'Queue\n'
+ fhand.write(to_print)
+
+ fhand.flush()
+
+class Popen(object):
+ 'It launches and controls a condor job'
+ def __init__(self, cmd, cmd_def=None, runner_conf=None,
+ stdout=None, stderr=None, stdin=None):
+ 'It launches a condor job'
+ if cmd_def is None:
+ cmd_def = []
+
+ #runner conf
+ if runner_conf is None:
+ runner_conf = {}
+ #some defaults
+ if 'transfer_files' not in runner_conf:
+ runner_conf['transfer_files'] = True
+
+ self._log_file = NamedTemporaryFile(suffix='.log')
+ #create condor job file
+ condor_job_file = self._create_condor_job_file(cmd, cmd_def,
+ self._log_file,
+ runner_conf,
+ stdout, stderr, stdin)
+ self._condor_job_file = condor_job_file
+
+ #launch condor
+ self._retcode = None
+ self._cluster_number = None
+ self._launch_condor(condor_job_file)
+
+ def _launch_condor(self, condor_job_file):
+ 'Given the condor_job_file it launches the condor job'
+ stdout, stderr, retcode = call(['condor_submit', condor_job_file.name])
+ if retcode:
+ msg = 'There was a problem with condor_submit: ' + stderr
+ raise RuntimeError(msg)
+ #the condor cluster number is given by condor_submit
+ #1 job(s) submitted to cluster 15.
+ for line in stdout.splitlines():
+ if 'submitted to cluster' in line:
+ self._cluster_number = line.strip().strip('.').split()[-1]
+
+ def _get_pid(self):
+ 'It returns the condor cluster number'
+ return self._cluster_number
+ pid = property(_get_pid)
+
+ def _get_returncode(self):
+ 'It returns the return code'
+ return self._retcode
+ returncode = property(_get_returncode)
+
+ @staticmethod
+ def _remove_paths_from_cmd(cmd, streams, conf):
+ '''It removes the absolute and relative paths from the cmd,
+ it returns the modified cmd'''
+ cmd_mod = cmd[:]
+ for stream in streams:
+ for fpath in stream['streams']:
+ #for the output files we can't deal with transfering files with
+ #paths. Condor will deliver those files into the initialdir, not
+ #where we expected.
+ if (stream['io'] != 'in' and conf['transfer_files']
+ and os.path.split(fpath)[-1] != fpath):
+ msg = 'output files with paths are not transferable'
+ raise ValueError(msg)
+
+ index = cmd_mod.index(fpath)
+ fpath = os.path.split(fpath)[-1]
+ cmd_mod[index] = fpath
+ return cmd_mod
+
+ def _create_condor_job_file(self, cmd, cmd_def, log_file, runner_conf,
+ stdout, stderr, stdin):
+ 'Given a cmd and the cmd_def it returns the condor job file'
+ #streams
+ streams = get_streams_from_cmd(cmd, cmd_def)
+ #we need some parameters to write the condor file
+ parameters = {}
+ parameters['executable'] = cmd[0]
+ parameters['log_file'] = log_file
+ #the cmd shouldn't have absolute path in the files because they will be
+ #transfered to another node in the condor working dir and they wouldn't
+ #be found with an absolute path
+ cmd_no_path = self._remove_paths_from_cmd(cmd, streams, runner_conf)
+ parameters['arguments'] = ' '.join(cmd_no_path[1:])
+ if stdout is not None:
+ parameters['stdout'] = stdout
+ if stderr is not None:
+ parameters['stderr'] = stderr
+ if stdin is not None:
+ parameters['stdin'] = stdin
+
+ transfer_bin = False
+ if 'transfer_executable' in runner_conf:
+ transfer_bin = runner_conf['transfer_executable']
+ parameters['transfer_executable'] = str(transfer_bin)
+
+ transfer_files = runner_conf['transfer_executable']
+ parameters['transfer_files'] = str(transfer_files)
+
+ in_fnames = []
+ for stream in streams:
+ if stream['io'] == 'in':
+ in_fnames.extend(stream['streams'])
+ parameters['input_fnames'] = in_fnames
+
+ #now we can create the job file
+ condor_job_file = NamedTemporaryFile()
+ write_condor_job_file(condor_job_file, parameters=parameters)
+ return condor_job_file
+
+ def _update_retcode(self):
+ 'It updates the retcode looking at the log file, it returns the retcode'
+ for line in open(self._log_file.name):
+ if 'return value' in line:
+ ret = line.split('return value')[1].strip().strip(')')
+ self._retcode = int(ret)
+ return self._retcode
+
+ def poll(self):
+ 'It checks if condor has run ower condor cluster'
+ cluster_number = self._cluster_number
+ cmd = ['condor_q', cluster_number,
+ '-format', '"%d.\n"', 'ClusterId']
+ stdout, stderr, retcode = call(cmd)
+ if retcode:
+ msg = 'There was a problem with condor_q: ' + stderr
+ raise RuntimeError(msg)
+ if cluster_number not in stdout:
+ #the job is finished
+ return self._update_retcode()
+ return self._retcode
+
+ def wait(self):
+ 'It waits until the condor job is finished'
+ stderr, retcode = call(['condor_wait', self._log_file.name])[1:]
+ if retcode:
+ msg = 'There was a problem with condor_wait: ' + stderr
+ raise RuntimeError(msg)
+ return self._update_retcode()
+
+ def kill(self):
+ 'It runs condor_rm for the condor job'
+ stderr, retcode = call(['condor_rm', self.pid])[1:]
+ if retcode:
+ msg = 'There was a problem with condor_rm: ' + stderr
+ raise RuntimeError(msg)
+ return self._update_retcode()
+
+ def terminate(self):
+ 'It runs condor_rm for the condor job'
+ self.kill()
diff --git a/test/condor_runner_test.py b/test/condor_runner_test.py
new file mode 100644
index 0000000..147857d
--- /dev/null
+++ b/test/condor_runner_test.py
@@ -0,0 +1,220 @@
+'''
+Created on 14/07/2009
+
+@author: jose
+'''
+
+# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
+# This file is part of psubprocess.
+# psubprocess is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+
+# psubprocess 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 Affero General Public License for more details.
+
+# You should have received a copy of the GNU Affero General Public License
+# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
+
+import unittest
+from tempfile import NamedTemporaryFile
+from StringIO import StringIO
+import os, stat
+
+from psubprocess.condor_runner import write_condor_job_file, Popen
+
+TEST_BINARY = '''#!/usr/bin/python
+import sys, shutil, os
+
+args = sys.argv
+
+#-o something send something to stdout
+#-e something send something to stderr
+#-i some_file send the file content to sdout
+#-t some_file copy the -i file to -t file
+#-s and stdin write stdin to stout
+#-r a number return this retcode
+
+#are the commands in the argv?
+arg_indexes = {}
+for param in ('-o', '-e', '-i', '-t', '-s', '-r'):
+ try:
+ arg_indexes[param] = args.index(param)
+ except ValueError:
+ arg_indexes[param] = None
+
+#stdout, stderr
+if arg_indexes['-o']:
+ sys.stdout.write(args[arg_indexes['-o'] + 1])
+if arg_indexes['-e']:
+ sys.stderr.write(args[arg_indexes['-e'] + 1])
+#-i -t
+if arg_indexes['-i'] and not arg_indexes['-t']:
+ sys.stdout.write(open(args[arg_indexes['-i'] + 1]).read())
+elif arg_indexes['-i'] and arg_indexes['-t']:
+ shutil.copy(args[arg_indexes['-i'] + 1], args[arg_indexes['-t'] + 1])
+#stdin
+if arg_indexes['-s']:
+ stdin = sys.stdin.read()
+ sys.stdout.write(stdin)
+#retcode
+if arg_indexes['-r']:
+ retcode = int(args[arg_indexes['-r'] + 1])
+else:
+ retcode = 0
+sys.exit(retcode)
+'''
+
+def _create_test_binary():
+ 'It creates a file with a test python binary in it'
+ fhand = NamedTemporaryFile(suffix='.py')
+ fhand.write(TEST_BINARY)
+ fhand.flush()
+ #it should be executable
+ os.chmod(fhand.name, stat.S_IXOTH | stat.S_IRWXU)
+ return fhand
+
+class CondorRunnerTest(unittest.TestCase):
+ 'It tests the condor runner'
+ @staticmethod
+ def test_write_condor_job_file():
+ 'It tests that we can write a condor job file with the right parameters'
+ fhand1 = NamedTemporaryFile()
+ fhand2 = NamedTemporaryFile()
+ flog = NamedTemporaryFile()
+ stderr_ = NamedTemporaryFile()
+ stdout_ = NamedTemporaryFile()
+ stdin_ = NamedTemporaryFile()
+ expected = '''Executable = bin
+Arguments = "-i %s -j %s"
+Universe = vanilla
+Log = %s
+When_to_transfer_output = ON_EXIT
+Getenv = True
+Transfer_executable = True
+Transfer_input_files = %s,%s
+Should_transfer_files = IF_NEEDED
+Output = %s
+Error = %s
+Input = %s
+Queue
+''' % (fhand1.name, fhand2.name, flog.name, fhand1.name, fhand2.name,
+ stdout_.name, stderr_.name, stdin_.name)
+ fhand = StringIO()
+ parameters = {'executable':'bin', 'log_file':flog,
+ 'input_fnames':[fhand1.name, fhand2.name],
+ 'arguments':'-i %s -j %s' % (fhand1.name, fhand2.name),
+ 'transfer_executable':True, 'transfer_files':True,
+ 'stdout':stdout_, 'stderr':stderr_, 'stdin':stdin_}
+ write_condor_job_file(fhand, parameters=parameters)
+ condor = fhand.getvalue()
+ assert condor == expected
+
+ @staticmethod
+ def test_run_condor_stdout():
+ 'It test that we can run condor job and retrieve stdout and stderr'
+ bin = _create_test_binary()
+ #a simple job
+ cmd = [bin.name]
+ cmd.extend(['-o', 'hola', '-e', 'caracola'])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ popen = Popen(cmd, runner_conf={'transfer_executable':True},
+ stdout=stdout, stderr=stderr)
+ assert popen.wait() == 0 #waits till finishes and looks to the retcode
+ assert open(stdout.name).read() == 'hola'
+ assert open(stderr.name).read() == 'caracola'
+
+ @staticmethod
+ def test_run_condor_stdin():
+ 'It test that we can run condor job with stdin'
+ bin = _create_test_binary()
+ #a simple job
+ cmd = [bin.name]
+ cmd.extend(['-s'])
+ stdin = NamedTemporaryFile()
+ stdout = NamedTemporaryFile()
+ stdin.write('hola')
+ stdin.flush()
+ popen = Popen(cmd, runner_conf={'transfer_executable':True},
+ stdout=stdout, stdin=stdin)
+ assert popen.wait() == 0 #waits till finishes and looks to the retcode
+ assert open(stdout.name).read() == 'hola'
+
+ @staticmethod
+ def test_run_condor_retcode():
+ 'It test that we can run condor job and get the retcode'
+ bin = _create_test_binary()
+ #a simple job
+ cmd = [bin.name]
+ cmd.extend(['-r', '10'])
+ popen = Popen(cmd, runner_conf={'transfer_executable':True})
+ assert popen.wait() == 10 #waits till finishes and looks to the retcode
+
+ @staticmethod
+ def test_run_condor_in_file():
+ 'It test that we can run condor job with an input file'
+ bin = _create_test_binary()
+
+ in_file = NamedTemporaryFile()
+ in_file.write('hola')
+ in_file.flush()
+
+ cmd = [bin.name]
+ cmd.extend(['-i', in_file.name])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in'}]
+ popen = Popen(cmd, runner_conf={'transfer_executable':True},
+ stdout=stdout, stderr=stderr, cmd_def=cmd_def)
+
+ assert popen.wait() == 0 #waits till finishes and looks to the retcod
+ assert open(stdout.name).read() == 'hola'
+
+ def test_run_condor_in_out_file(self):
+ 'It test that we can run condor job with an output file'
+ bin = _create_test_binary()
+
+ in_file = NamedTemporaryFile()
+ in_file.write('hola')
+ in_file.flush()
+ out_file = open('output.txt', 'w')
+
+ cmd = [bin.name]
+ cmd.extend(['-i', in_file.name, '-t', out_file.name])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
+ {'options': ('-t', '--output'), 'io': 'out'}]
+ popen = Popen(cmd, runner_conf={'transfer_executable':True},
+ stdout=stdout, stderr=stderr, cmd_def=cmd_def)
+ popen.wait()
+ assert popen.wait() == 0 #waits till finishes and looks to the retcod
+ assert open(out_file.name).read() == 'hola'
+ os.remove(out_file.name)
+
+ #and output file with path won't be allowed unless the transfer file
+ #mechanism is not used
+ out_file = NamedTemporaryFile()
+
+ cmd = [bin.name]
+ cmd.extend(['-i', in_file.name, '-t', out_file.name])
+ stdout = NamedTemporaryFile()
+ stderr = NamedTemporaryFile()
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
+ {'options': ('-t', '--output'), 'io': 'out'}]
+ try:
+ popen = Popen(cmd, runner_conf={'transfer_executable':True},
+ stdout=stdout, stderr=stderr, cmd_def=cmd_def)
+ self.fail('ValueError expected')
+ #pylint: disable-msg=W0704
+ except ValueError:
+ pass
+
+
+if __name__ == "__main__":
+ #import sys;sys.argv = ['', 'Test.testName']
+ unittest.main()
\ No newline at end of file
|
JoseBlanca/psubprocess
|
0c4e014200c04f41662719f19c919635e927ddce
|
Now we can get the streams from the command line and the command line definition
|
diff --git a/psubprocess/streams.py b/psubprocess/streams.py
new file mode 100644
index 0000000..3ff10f3
--- /dev/null
+++ b/psubprocess/streams.py
@@ -0,0 +1,110 @@
+'''
+Created on 13/07/2009
+
+@author: jose
+'''
+
+# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
+# This file is part of project.
+# project is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+
+# project 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 Affero General Public License for more details.
+
+# You should have received a copy of the GNU Affero General Public License
+# along with project. If not, see <http://www.gnu.org/licenses/>.
+
+STDIN = 'stdin'
+STDOUT = 'stdout'
+STDERR = 'stderr'
+
+def _find_param_def_in_cmd(cmd, param_def):
+ '''Given a cmd and a parameter definition it returns the index of the param
+ in the cmd.
+
+ If the param is not found in the cmd it will raise a ValueError.
+ '''
+ options = param_def['options']
+ #options could be a list or an item
+ if not isinstance(options, list) and not isinstance(options, tuple):
+ options = (options,)
+
+ #the standard options with command line options
+ for index, item in enumerate(cmd):
+ if item in options:
+ return index
+ raise ValueError('Parameter not found in the given cmd')
+
+def _positive_int(index, sequence):
+ '''It returns the same int index, but positive.'''
+ if index is None:
+ return None
+ elif index < 0:
+ return len(sequence) + index
+ return index
+
+def get_streams_from_cmd(cmd, cmd_def):
+ 'Given a cmd and a cmd definition it returns the streams'
+ streams = []
+ for param_def in cmd_def:
+ options = param_def['options']
+ stream_values = []
+ #is the parameter defining an std stream?
+ for stream in (STDIN, STDOUT, STDERR):
+ #options can be an item or an iterable
+ if stream == options or ('__in__' in dir(options) and
+ stream in options):
+ stream_values = [stream]
+ #if it isn't an standard stream we have to look for the stream
+ if not stream_values:
+ #where are the stream values after the parameter?
+ if 'cmd_locations' in param_def:
+ locations = param_def['cmd_locations']
+ else:
+ #by the default we want the first item after the parameter
+ locations = slice(0, 1)
+ #if the location is not a list we make it
+ try:
+ #pylint: disable-msg=W0104
+ #the statement has an effect because we're cheking
+ #if the locations is a slice or an int
+ locations.stop
+ locations.start
+ except AttributeError:
+ locations = slice(locations, locations + 1)
+
+ #where is the parameter in the cmd list?
+ #if the param options is not an int or a slice, its a list of
+ #strings
+ if isinstance(options, int):
+ #for PRE_ARG (1) and POST_ARG (-1)
+ #we take 1 unit because the options should be 1 to the right
+ #of the value
+ index = _positive_int(options, cmd) - 1
+ else:
+ #look for param in cmd
+ try:
+ index = _find_param_def_in_cmd(cmd, param_def)
+ except ValueError:
+ index = None
+
+ #get the stream values
+ if index is not None:
+ #now we add the index to the location, because the
+ #location is relative to where the parameter is found
+ locations = slice(locations.start + index + 1,
+ locations.stop + index + 1)
+
+ stream_values = cmd[locations]
+
+ #create the result dict
+ stream = param_def.copy()
+ stream['streams'] = stream_values
+ streams.append(stream)
+
+ return streams
\ No newline at end of file
diff --git a/test/cmd_def_test.py b/test/cmd_def_test.py
new file mode 100644
index 0000000..fd3828d
--- /dev/null
+++ b/test/cmd_def_test.py
@@ -0,0 +1,151 @@
+'''
+Created on 13/07/2009
+
+@author: jose
+'''
+
+# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
+# This file is part of psubprocess.
+# psubprocess is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+
+# psubprocess 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 Affero General Public License for more details.
+
+# You should have received a copy of the GNU Affero General Public License
+# along with psubprocess. If not, see <http://www.gnu.org/licenses/>.
+
+import unittest
+
+from psubprocess.streams import (get_streams_from_cmd,
+ STDIN, STDOUT, STDERR)
+
+#What's a stream
+#
+#A command takes some input streams and creates some ouput streams
+#An stream is a file-like object or a directory. In fact an stream can be
+#composed by several files (e.g. a seq and a qual file that should be splitted
+#together)
+#
+#Kinds of streams in a cmd
+#cmd arg1 arg2 -i opt1 opt2 -j opt3 arg3 < stdin > stdout stderr retcode
+#in this general command there are several types of streams:
+# - previous arguments. arguments (without options) located before the first
+# option (like arg1 and arg2)
+# - options with one option, like opt3
+# - options with several arguments, like -i that has opt1 and opt2
+# - arguments (aka post_arguments). arguments located after the last option
+# - stdin, stdout, stderr and retcode. The standard ones.
+#
+#How to define the streams
+#An stream is defined by a dict with the following keys: options, io, splitter,
+#value, special, location. All of them are optional except the options.
+#Options: It defines in which options or arguments is the stream found. It
+#should by just a value or a tuple.
+#Options kinds:
+# - -i the stream will be located after the parameter -i
+# - (-o, --output) the stream will be after -o or --output
+# - PRE_ARG right after the cmd and before the first parameter
+# - POST_ARG after the last option
+# - STDIN
+# - STDOUT
+# - STDERR
+#io: It defines if it's an input or an output stream for the cmd
+#splitter: It defines how the stream should be split. There are three ways of
+#definint it:
+# - an str that will be used to scan through the in streams, every
+# line with the str in in will be considered a token start
+# e.g '>' for the blast files
+# - a re every line with a match will be considered a token start
+# - a function the function should take the stream an return an
+# iterator with the tokens
+#joiner: A function that should take the out streams for all jobs and return
+#the joined stream. If not given the output stream will be just concatenated.
+#value: the value for the stream, this stream will not define the value in the
+#command line, it will be implicit
+#special: It defines some special treaments for the streams.
+# - no_split It shouldn't be split
+# - no_transfer It shouldn't be transfer to all nodes
+# - no_abspath Its path shouldn't be converted to absolute
+# - create It should be created before running the command
+# - no_support An error should be raised if used.
+#cmd_locations: If the location is not given the assumed location will be 0.
+#That means that the stream will be located in the 0 position after the option.
+#It can be either an int or an slice. In the slice case several substreams will
+#be taken together in the stream. Useful for instance for the case of two fasta
+#files with the seq an qual that should be split together and transfered
+#together.
+
+def _check_streams(streams, expected_streams):
+ 'It checks that streams meet the requirements set by the expected streams'
+ for stream, expected_stream in zip(streams, expected_streams):
+ for key in expected_stream:
+ assert stream[key] == expected_stream[key]
+
+class StreamsFromCmdTest(unittest.TestCase):
+ 'It tests that we can get the input and output files from the cmd'
+ @staticmethod
+ def test_simple_case():
+ 'It tests the most simple cases'
+ #a simple case
+ cmd = ['hola', '-i', 'caracola.txt']
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in'}]
+ expected_streams = [{'streams': ['caracola.txt'], 'io':'in'}]
+ streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
+ _check_streams(streams, expected_streams)
+
+ #with two files
+ cmd = ['hola', '-i', 'seq.txt', 'qual.txt']
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in',
+ 'cmd_locations':slice(0, 2)}]
+ expected_streams = [{'streams': ['seq.txt', 'qual.txt'],
+ 'io':'in'}]
+ streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
+ _check_streams(streams, expected_streams)
+
+ #a parameter not found in the cmd
+ cmd = ['hola', '-i', 'caracola.txt']
+ cmd_def = [{'options': ('-i', '--input'), 'io': 'in'},
+ {'options': ('-j', '--input2'), 'io': 'in'}]
+ expected_streams = [{'streams': ['caracola.txt'], 'io':'in'}]
+ streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
+ _check_streams(streams, expected_streams)
+
+ @staticmethod
+ def test_arguments():
+ 'It test that it works with cmd arguments, not options'
+ #the options we want is in the pre_argv, after the binary
+ cmd = ['hola', 'hola.txt', '-i', 'caracola.txt']
+ cmd_def = [{'options': 1, 'io': 'in'}]
+ expected_streams = [{'streams': ['hola.txt'], 'io':'in'}]
+ streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
+ _check_streams(streams, expected_streams)
+
+ #the option we want is at the end of the cmd
+ cmd = ['hola', '-i', 'caracola.txt', 'hola.txt']
+ cmd_def = [{'options': -1, 'io': 'in'}]
+ expected_streams = [{'streams': ['hola.txt'], 'io':'in'}]
+ streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
+ _check_streams(streams, expected_streams)
+
+ @staticmethod
+ def test_stdin():
+ 'We want stdin, stdout and stderr as streams'
+ #stdin
+ cmd = ['hola']
+ cmd_def = [{'options': STDIN, 'io': 'in'},
+ {'options': STDOUT, 'io': 'out'},
+ {'options': STDERR, 'io': 'out'}]
+ expected_streams = [{'streams': [STDIN], 'io':'in'},
+ {'streams': [STDOUT], 'io':'out'},
+ {'streams': [STDERR], 'io':'out'}]
+ streams = get_streams_from_cmd(cmd, cmd_def=cmd_def)
+ _check_streams(streams, expected_streams)
+
+if __name__ == "__main__":
+ #import sys;sys.argv = ['', 'Test.testName']
+ unittest.main()
\ No newline at end of file
|
JoseBlanca/psubprocess
|
acd5097fa98b663f55737766b5f774cbcc16a38e
|
Module and test folders created
|
diff --git a/psubprocess/__init__.py b/psubprocess/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/test/__init__.py b/test/__init__.py
new file mode 100644
index 0000000..e69de29
|
Guid75/renamah
|
258038a5ea58e0beb35451021bad031dc7470511
|
better assert message
|
diff --git a/renamah/paths.cpp b/renamah/paths.cpp
index 1614ea7..a12edad 100644
--- a/renamah/paths.cpp
+++ b/renamah/paths.cpp
@@ -1,71 +1,70 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QDir>
#include <QCoreApplication>
#include <QDesktopServices>
#include "global.h"
#include "paths.h"
QString Paths::sharePath()
{
QDir appDir(QCoreApplication::applicationDirPath());
- if (Global::devMode()) {
+ if (Global::devMode())
return QDir(appDir.filePath("../share/renamah")).canonicalPath();
- }
if (Global::localMode())
return appDir.absolutePath();
#if defined(Q_OS_LINUX)
return QDir(appDir.filePath("/usr/share/renamah")).canonicalPath();
#else
return appDir.absolutePath();
#endif
}
QString Paths::libPath()
{
QDir appDir(QCoreApplication::applicationDirPath());
if (Global::devMode()) {
return QDir(appDir.filePath("../lib/renamah")).canonicalPath();
}
if (Global::localMode())
return appDir.absolutePath();
#if defined(Q_OS_LINUX)
return QDir(appDir.filePath("/usr/lib/renamah")).canonicalPath();
#else
return appDir.absolutePath();
#endif
}
QString Paths::profilePath()
{
if (Global::devMode() || Global::localMode())
return QDir(QCoreApplication::applicationDirPath()).filePath(qApp->applicationName());
return QDesktopServices::storageLocation(QDesktopServices::DataLocation);
}
diff --git a/renamah/widget_modifiers.cpp b/renamah/widget_modifiers.cpp
index db2e10c..8daf6fb 100644
--- a/renamah/widget_modifiers.cpp
+++ b/renamah/widget_modifiers.cpp
@@ -1,252 +1,252 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QMessageBox>
#include <QMouseEvent>
#include <QHeaderView>
#include <QMetaProperty>
#include "modifier_delegate.h"
#include "widget_modifiers.h"
WidgetModifiers::WidgetModifiers(QWidget *parent)
: QWidget(parent),
_modifierManager(0),
_modifierModel(0) {
setupUi(this);
connect(&signalMapperAddModifier, SIGNAL(mapped(const QString &)),
this, SLOT(addModifier(const QString &)));
pushButtonAdd->setMenu(&menuAddModifier);
connect(&menuAddModifier, SIGNAL(aboutToShow()), this, SLOT(aboutToShowAddModifierMenu()));
treeView->setItemDelegate(new ModifierDelegate);
labelAddModifier->installEventFilter(this);
treeView->viewport()->installEventFilter(this);
treeView->installEventFilter(this);
}
void WidgetModifiers::init(ModifierManager *modifierManager, ModifierModel &modifierModel) {
_modifierManager = modifierManager;
_modifierModel = &modifierModel;
retranslate();
treeView->setModel(_modifierModel);
connect(_modifierModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
this, SLOT(modifiersInserted(const QModelIndex &, int, int)));
treeView->header()->setResizeMode(0, QHeaderView::ResizeToContents);
treeView->header()->setResizeMode(1, QHeaderView::ResizeToContents);
connect(treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(currentModifierChanged(const QModelIndex &, const QModelIndex &)));
currentModifierChanged(QModelIndex(), QModelIndex());
}
void WidgetModifiers::retranslate() {
labelAddModifier->setText(tr("Add a new %1").arg(_modifierManager->modifierTypeName()));
core::Modifier *modifier = currentModifier();
if (!modifier)
return;
core::ModifierFactory *factory = modifier->factory();
labelModifierCaption->setText(factory->info().caption());
labelModifierDescription->setText(factory->info().description());
}
void WidgetModifiers::on_pushButtonRemove_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
_modifierModel->removeModifier(index);
}
void WidgetModifiers::on_pushButtonUp_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
if (!index.row())
return;
_modifierModel->moveModifier(index.row(), index.row() - 1);
}
void WidgetModifiers::on_pushButtonDown_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
if (index.row() == _modifierModel->rowCount() - 1)
return;
_modifierModel->moveModifier(index.row(), index.row() + 1);
}
void WidgetModifiers::aboutToShowAddModifierMenu() {
menuAddModifier.clear();
foreach (core::ModifierFactory *factory, _modifierManager->factories())
{
QAction *action = menuAddModifier.addAction(factory->info().caption() + " (" + factory->info().description() + ")");
connect(action, SIGNAL(triggered()), &signalMapperAddModifier, SLOT(map()));
signalMapperAddModifier.setMapping(action, factory->info().name());
}
}
void WidgetModifiers::addModifier(const QString &factoryName) {
core::ModifierFactory *factory = _modifierManager->factoryByName(factoryName);
- Q_ASSERT_X(factory, "WidgetModifiers::addModifierClicked()", "<factoryName> seems to have no factory correspondant");
+ Q_ASSERT_X(factory, "WidgetModifiers::addModifierClicked()", qPrintable(QString("%1 factory not found, maybe a plugin location problem").arg(factoryName)));
_modifierModel->addModifier(factory->makeModifier());
stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
}
void WidgetModifiers::currentModifierChanged(const QModelIndex ¤t, const QModelIndex &previous) {
if (previous.isValid())
{
core::Modifier *previousModifier = _modifierModel->modifier(previous);
core::ModifierFactory *previousFactory = previousModifier->factory();
if (_configWidget)
{
previousFactory->deleteConfigurationWidget(_configWidget);
_configWidget = 0;
}
}
if (!current.isValid())
{
stackedWidgetConfiguration->setCurrentWidget(pageNoModifiers);
currentModifierChanged(0);
return;
}
stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
core::Modifier *modifier = _modifierModel->modifier(current);
core::ModifierFactory *factory = modifier->factory();
_configWidget = modifier->factory()->makeConfigurationWidget(modifier);
if (_configWidget)
{
setConfigWidget(_configWidget);
frameConfiguration->setVisible(true);
labelModifierCaption->setText(factory->info().caption());
labelModifierDescription->setText(factory->info().description());
connect(modifier, SIGNAL(settingsChanged()), this, SLOT(widgetModifierChanged()));
}
currentModifierChanged(modifier);
}
bool WidgetModifiers::eventFilter(QObject *obj, QEvent *ev) {
if (obj == labelAddModifier && ev->type() == QEvent::MouseButtonPress)
{
QMouseEvent *event = static_cast<QMouseEvent*>(ev);
menuAddModifier.popup(event->globalPos());
} else if (obj == treeView->viewport() && ev->type() == QEvent::MouseButtonPress)
{
QMouseEvent *event = static_cast<QMouseEvent*>(ev);
QPoint p = event->pos();
QModelIndex index = treeView->indexAt(p);
if (index.column() == ModifierModel::colMode)
{
if (modifierStateRect(index).contains(p))
_modifierModel->toggleModifierState(_modifierModel->modifier(index));
else
{
if (modifierOnlyRect(index).contains(p))
_modifierModel->toggleExclusiveState(_modifierModel->modifier(index));
}
}
} else if (obj == treeView && ev->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(ev);
if (keyEvent->key() == Qt::Key_Delete)
{
on_pushButtonRemove_clicked();
}
}
return QWidget::eventFilter(obj, ev);
}
QRect WidgetModifiers::modifierStateRect(const QModelIndex &index) const {
QRect indexRect = treeView->visualRect(index);
QRect res(indexRect.left(), indexRect.top(), 16, 16);
if (indexRect.width() > 32)
res.translate((indexRect.width() - 32) / 2, 0);
if (indexRect.height() > 16)
res.translate(0, (indexRect.height() - 16) / 2);
return res;
}
QRect WidgetModifiers::modifierOnlyRect(const QModelIndex &index) const {
QRect indexRect = treeView->visualRect(index);
QRect res(indexRect.left() + 16, indexRect.top(), 16, 16);
if (indexRect.width() > 32)
res.translate((indexRect.width() - 32) / 2, 0);
if (indexRect.height() > 16)
res.translate(0, (indexRect.height() - 16) / 2);
return res;
}
void WidgetModifiers::widgetModifierChanged() {
if (treeView->currentIndex().isValid())
{
_modifierModel->refreshLayout();
treeView->update(treeView->currentIndex());
}
}
core::Modifier *WidgetModifiers::currentModifier() const {
return _modifierModel->modifier(treeView->currentIndex());
}
void WidgetModifiers::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi(this);
retranslate();
} else
QWidget::changeEvent(event);
}
void WidgetModifiers::newProfile() {
if (_modifierModel->rowCount())
treeView->setCurrentIndex(_modifierModel->index(0, 0));
}
void WidgetModifiers::modifiersInserted(const QModelIndex &parent, int start, int end) {
treeView->setCurrentIndex(_modifierModel->index(start));
}
|
Guid75/renamah
|
f28154f09473a84f5e016ac9d5eeee21f2042300
|
no INSTALL target for win32
|
diff --git a/libcore/CMakeLists.txt b/libcore/CMakeLists.txt
index e99e12b..292d067 100644
--- a/libcore/CMakeLists.txt
+++ b/libcore/CMakeLists.txt
@@ -1,40 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(LIBCORE_SOURCES
interfaces/modifier_config_widget.cpp
interfaces/modifier.cpp
)
SET(LIBCORE_FORMS)
QT4_WRAP_UI(LIBCORE_FORMS_H ${LIBCORE_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(LIBCORE_MOCH
interfaces/modifier_config_widget.h
interfaces/modifier.h
interfaces/filter.h
interfaces/action.h
)
ADD_DEFINITIONS(-DRENAMAH_LIBCORE_LIBRARY)
QT4_WRAP_CPP(LIBCORE_MOC ${LIBCORE_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
ADD_LIBRARY(renamahcore SHARED ${LIBCORE_SOURCES} ${LIBCORE_FORMS_H} ${LIBCORE_MOC})
IF(WIN32)
TARGET_LINK_LIBRARIES(renamahcore ${QT_LIBRARIES})
ENDIF(WIN32)
-INSTALL(TARGETS renamahcore
- LIBRARY DESTINATION lib)
+IF(NOT WIN32)
+ INSTALL(TARGETS renamahcore
+ LIBRARY DESTINATION lib)
+ENDIF(NOT WIN32)
|
Guid75/renamah
|
ed80e32fa052810ea80be8a8d6e09934cadc5585
|
Added CMakeLists.txt.user in ignore section
|
diff --git a/.gitignore b/.gitignore
index 7b5a6de..591fdb4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,11 +1,12 @@
*.qm
ui_*
moc_*
*.cxx
Makefile
CMakeFiles
*~
CMakeCache.txt
cmake_install.cmake
bin/renamah
-bin/libcore.so
\ No newline at end of file
+bin/libcore.so
+CMakeLists.txt.user
\ No newline at end of file
|
Guid75/renamah
|
6e390765bfd4ca782742211df1933b4e40a18e05
|
For win32 (mingw)
|
diff --git a/libcore/CMakeLists.txt b/libcore/CMakeLists.txt
index e312852..e99e12b 100644
--- a/libcore/CMakeLists.txt
+++ b/libcore/CMakeLists.txt
@@ -1,40 +1,40 @@
INCLUDE(${QT_USE_FILE})
SET(LIBCORE_SOURCES
interfaces/modifier_config_widget.cpp
interfaces/modifier.cpp
)
SET(LIBCORE_FORMS)
QT4_WRAP_UI(LIBCORE_FORMS_H ${LIBCORE_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(LIBCORE_MOCH
interfaces/modifier_config_widget.h
interfaces/modifier.h
interfaces/filter.h
interfaces/action.h
)
ADD_DEFINITIONS(-DRENAMAH_LIBCORE_LIBRARY)
QT4_WRAP_CPP(LIBCORE_MOC ${LIBCORE_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
ADD_LIBRARY(renamahcore SHARED ${LIBCORE_SOURCES} ${LIBCORE_FORMS_H} ${LIBCORE_MOC})
-IF(MSVC)
+IF(WIN32)
TARGET_LINK_LIBRARIES(renamahcore ${QT_LIBRARIES})
-ENDIF(MSVC)
+ENDIF(WIN32)
INSTALL(TARGETS renamahcore
LIBRARY DESTINATION lib)
diff --git a/plugins/casefilter/CMakeLists.txt b/plugins/casefilter/CMakeLists.txt
index b485ed4..e187400 100644
--- a/plugins/casefilter/CMakeLists.txt
+++ b/plugins/casefilter/CMakeLists.txt
@@ -1,44 +1,44 @@
INCLUDE(${QT_USE_FILE})
SET(CASEFILTER_SOURCES
case_filter_factory.cpp
case_filter.cpp
config_widget.cpp
)
SET(CASEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CASEFILTER_FORMS_H ${CASEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CASEFILTER_MOCH
case_filter.h
case_filter_factory.h
config_widget.h
)
QT4_WRAP_CPP(CASEFILTER_MOC ${CASEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS} ${CASEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_casefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(casefilter SHARED ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS_H} ${CASEFILTER_MOC})
-IF(MSVC)
- TARGET_LINK_LIBRARIES(casefilter core ${QT_LIBRARIES})
-ENDIF(MSVC)
+IF(WIN32)
+ TARGET_LINK_LIBRARIES(casefilter renamahcore ${QT_LIBRARIES})
+ENDIF(WIN32)
ADD_DEPENDENCIES(casefilter translations_casefilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/commandaction/CMakeLists.txt b/plugins/commandaction/CMakeLists.txt
index 8c8f5fc..9dff6cf 100644
--- a/plugins/commandaction/CMakeLists.txt
+++ b/plugins/commandaction/CMakeLists.txt
@@ -1,48 +1,48 @@
INCLUDE(${QT_USE_FILE})
SET(COMMANDACTION_SOURCES
command_action_factory.cpp
command_action.cpp
config_widget.cpp
process_handler.cpp
)
SET(COMMANDACTION_FORMS
config_widget.ui
)
QT4_WRAP_UI(COMMANDACTION_FORMS_H ${COMMANDACTION_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(COMMANDACTION_MOCH
command_action.h
command_action_factory.h
config_widget.h
process_handler.h
)
QT4_WRAP_CPP(COMMANDACTION_MOC ${COMMANDACTION_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS} ${COMMANDACTION_MOCH})
ADD_CUSTOM_TARGET(translations_commandaction DEPENDS ${QM_FILES})
ADD_LIBRARY(commandaction SHARED ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
-IF(MSVC)
- TARGET_LINK_LIBRARIES(commandaction core ${QT_LIBRARIES})
-ENDIF(MSVC)
+IF(WIN32)
+ TARGET_LINK_LIBRARIES(commandaction renamahcore ${QT_LIBRARIES})
+ENDIF(WIN32)
ADD_DEPENDENCIES(commandaction translations_commandaction)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/cutterfilter/CMakeLists.txt b/plugins/cutterfilter/CMakeLists.txt
index 3b9cda5..a1825e0 100644
--- a/plugins/cutterfilter/CMakeLists.txt
+++ b/plugins/cutterfilter/CMakeLists.txt
@@ -1,43 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(CUTTERFILTER_SOURCES
cutter_filter_factory.cpp
cutter_filter.cpp
config_widget.cpp
)
SET(CUTTERFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CUTTERFILTER_FORMS_H ${CUTTERFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CUTTERFILTER_MOCH
cutter_filter.h
cutter_filter_factory.h
config_widget.h
)
QT4_WRAP_CPP(CUTTERFILTER_MOC ${CUTTERFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS} ${CUTTERFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_cutterfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(cutterfilter SHARED ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS_H} ${CUTTERFILTER_MOC})
-IF(MSVC)
- TARGET_LINK_LIBRARIES(cutterfilter core ${QT_LIBRARIES})
-ENDIF(MSVC)
+IF(WIN32)
+ TARGET_LINK_LIBRARIES(cutterfilter renamahcore ${QT_LIBRARIES})
+ENDIF(WIN32)
ADD_DEPENDENCIES(cutterfilter translations_cutterfilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/datefilter/CMakeLists.txt b/plugins/datefilter/CMakeLists.txt
index 8721b98..9a891cc 100644
--- a/plugins/datefilter/CMakeLists.txt
+++ b/plugins/datefilter/CMakeLists.txt
@@ -1,45 +1,45 @@
INCLUDE(${QT_USE_FILE})
SET(DATEFILTER_SOURCES
date_filter_factory.cpp
date_filter.cpp
config_widget.cpp
)
SET(DATEFILTER_FORMS
config_widget.ui
help_widget.ui
)
QT4_WRAP_UI(DATEFILTER_FORMS_H ${DATEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(DATEFILTER_MOCH
date_filter.h
date_filter_factory.h
config_widget.h
)
QT4_WRAP_CPP(DATEFILTER_MOC ${DATEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS} ${DATEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_datefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(datefilter SHARED ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS_H} ${DATEFILTER_MOC})
-IF(MSVC)
- TARGET_LINK_LIBRARIES(datefilter core ${QT_LIBRARIES})
-ENDIF(MSVC)
+IF(WIN32)
+ TARGET_LINK_LIBRARIES(datefilter renamahcore ${QT_LIBRARIES})
+ENDIF(WIN32)
ADD_DEPENDENCIES(datefilter translations_datefilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/numberingfilter/CMakeLists.txt b/plugins/numberingfilter/CMakeLists.txt
index 20a905d..67a5694 100644
--- a/plugins/numberingfilter/CMakeLists.txt
+++ b/plugins/numberingfilter/CMakeLists.txt
@@ -1,43 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(NUMBERINGFILTER_SOURCES
numbering_filter_factory.cpp
numbering_filter.cpp
config_widget.cpp
)
SET(NUMBERINGFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(NUMBERINGFILTER_FORMS_H ${NUMBERINGFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(NUMBERINGFILTER_MOCH
numbering_filter.h
numbering_filter_factory.h
config_widget.h
)
QT4_WRAP_CPP(NUMBERINGFILTER_MOC ${NUMBERINGFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS} ${NUMBERINGFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_numberingfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(numberingfilter SHARED ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS_H} ${NUMBERINGFILTER_MOC})
-IF(MSVC)
- TARGET_LINK_LIBRARIES(numberingfilter core ${QT_LIBRARIES})
-ENDIF(MSVC)
+IF(WIN32)
+ TARGET_LINK_LIBRARIES(numberingfilter renamahcore ${QT_LIBRARIES})
+ENDIF(WIN32)
ADD_DEPENDENCIES(numberingfilter translations_numberingfilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/replacefilter/CMakeLists.txt b/plugins/replacefilter/CMakeLists.txt
index 07c3953..e14b884 100644
--- a/plugins/replacefilter/CMakeLists.txt
+++ b/plugins/replacefilter/CMakeLists.txt
@@ -1,43 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(REPLACEFILTER_SOURCES
replace_filter_factory.cpp
replace_filter.cpp
config_widget.cpp
)
SET(REPLACEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(REPLACEFILTER_FORMS_H ${REPLACEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(REPLACEFILTER_MOCH
replace_filter.h
replace_filter_factory.h
config_widget.h
)
QT4_WRAP_CPP(REPLACEFILTER_MOC ${REPLACEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS} ${REPLACEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_replacefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(replacefilter SHARED ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS_H} ${REPLACEFILTER_MOC})
-IF(MSVC)
- TARGET_LINK_LIBRARIES(replacefilter core ${QT_LIBRARIES})
-ENDIF(MSVC)
+IF(WIN32)
+ TARGET_LINK_LIBRARIES(replacefilter renamahcore ${QT_LIBRARIES})
+ENDIF(WIN32)
ADD_DEPENDENCIES(replacefilter translations_replacefilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/renamah/CMakeLists.txt b/renamah/CMakeLists.txt
index add9b19..0424741 100644
--- a/renamah/CMakeLists.txt
+++ b/renamah/CMakeLists.txt
@@ -1,112 +1,111 @@
SET(QT_USE_QTXML TRUE)
# SET(QT_USE_QTNETWORK TRUE)
INCLUDE(${QT_USE_FILE})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(RENAMAH_SOURCES
main.cpp
main_window.cpp
form_twinning.cpp
simple_dir_model.cpp
twinning_widget.cpp
widget_simple.cpp
file_model.cpp
filter_model.cpp
filter_manager.cpp
plugin_manager.cpp
form_last_operations.cpp
task_manager.cpp
modifier_delegate.cpp
led_widget.cpp
processor.cpp
widget_modifiers.cpp
modifier_manager.cpp
modifier_model.cpp
finalizer_model.cpp
action_manager.cpp
widget_extension_policy.cpp
extension_policy.cpp
widget_filters.cpp
widget_actions.cpp
dialog_manual_rename.cpp
profile.cpp
undo_manager.cpp
global.cpp
paths.cpp
)
SET(RENAMAH_FORMS
main_window.ui
form_twinning.ui
widget_simple.ui
form_last_operations.ui
widget_modifiers.ui
widget_extension_policy.ui
dialog_manual_rename.ui
)
QT4_WRAP_UI(RENAMAH_FORMS_H ${RENAMAH_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/staticlibs)
SET(RENAMAH_MOCH
main_window.h
form_twinning.h
simple_dir_model.h
twinning_widget.h
widget_simple.h
file_model.h
filter_model.h
form_last_operations.h
modifier_delegate.h
led_widget.h
processor.h
widget_modifiers.h
modifier_model.h
finalizer_model.h
widget_extension_policy.h
widget_filters.h
widget_actions.h
dialog_manual_rename.h
undo_manager.h
)
# Translations stuff
COMPUTE_QM_FILES(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH})
ADD_CUSTOM_TARGET(translations_renamah DEPENDS ${QM_FILES})
QT4_WRAP_CPP(RENAMAH_MOC ${RENAMAH_MOCH})
QT4_ADD_RESOURCES(RENAMAH_RES renamah.qrc)
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
ADD_EXECUTABLE(renamah ${RENAMAH_SOURCES} ${RENAMAH_FORMS_H} ${RENAMAH_MOC} ${RENAMAH_RES})
ADD_DEPENDENCIES(renamah translations_renamah)
TARGET_LINK_LIBRARIES(
renamah renamahcore ${QT_LIBRARIES}
- )
-
+)
INSTALL(TARGETS renamah
RUNTIME DESTINATION bin)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/)
#INSTALL(DIRECTORY share/applications
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
#INSTALL(DIRECTORY share/pixmaps
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
|
Guid75/renamah
|
207198087792c0f6a1372b2cf7ac8f3585354eb8
|
reindentation (spaces) for QtCreator
|
diff --git a/renamah/action_manager.cpp b/renamah/action_manager.cpp
index 4ecdee6..d69955f 100644
--- a/renamah/action_manager.cpp
+++ b/renamah/action_manager.cpp
@@ -1,29 +1,29 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 "action_manager.h"
ActionManager *ActionManager::_instance = 0;
ActionManager &ActionManager::instance()
{
- if (!_instance)
- _instance = new ActionManager;
+ if (!_instance)
+ _instance = new ActionManager;
- return *_instance;
+ return *_instance;
}
diff --git a/renamah/action_manager.h b/renamah/action_manager.h
index ae2dd9f..b7366dd 100644
--- a/renamah/action_manager.h
+++ b/renamah/action_manager.h
@@ -1,35 +1,35 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef ACTION_MANAGER_H
#define ACTION_MANAGER_H
#include "modifier_manager.h"
class ActionManager : public ModifierManager
{
public:
- static ActionManager &instance();
+ static ActionManager &instance();
- QString modifierTypeName() { return QObject::tr("action"); }
+ QString modifierTypeName() { return QObject::tr("action"); }
private:
- static ActionManager *_instance;
+ static ActionManager *_instance;
};
#endif
diff --git a/renamah/dialog_manual_rename.cpp b/renamah/dialog_manual_rename.cpp
index b82e4fc..2a390d1 100644
--- a/renamah/dialog_manual_rename.cpp
+++ b/renamah/dialog_manual_rename.cpp
@@ -1,50 +1,50 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QMessageBox>
#include "dialog_manual_rename.h"
DialogManualRename::DialogManualRename(QWidget *parent)
- : QDialog(parent),
- _automaticRename(false)
+ : QDialog(parent),
+ _automaticRename(false)
{
- setupUi(this);
+ setupUi(this);
}
void DialogManualRename::init(const QString &originalFileName, const QString &newFileName)
{
- _originalFileName = originalFileName;
- lineEdit->setText(newFileName);
- lineEdit->selectAll();
+ _originalFileName = originalFileName;
+ lineEdit->setText(newFileName);
+ lineEdit->selectAll();
}
void DialogManualRename::on_pushButtonAutomatic_clicked()
{
- _automaticRename = true;
- accept();
+ _automaticRename = true;
+ accept();
}
void DialogManualRename::on_pushButtonOriginal_clicked()
{
- if (QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to set the original filename?"), QMessageBox::Yes | QMessageBox::Cancel) !=
- QMessageBox::Yes)
- return;
+ if (QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to set the original filename?"), QMessageBox::Yes | QMessageBox::Cancel) !=
+ QMessageBox::Yes)
+ return;
- lineEdit->setText(_originalFileName);
+ lineEdit->setText(_originalFileName);
}
diff --git a/renamah/dialog_manual_rename.h b/renamah/dialog_manual_rename.h
index 8c6eafb..3c556bb 100644
--- a/renamah/dialog_manual_rename.h
+++ b/renamah/dialog_manual_rename.h
@@ -1,45 +1,45 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef DIALOG_MANUAL_RENAME_H
#define DIALOG_MANUAL_RENAME_H
#include "ui_dialog_manual_rename.h"
class DialogManualRename : public QDialog, private Ui::DialogManualRename
{
- Q_OBJECT
+ Q_OBJECT
public:
- DialogManualRename(QWidget *parent = 0);
+ DialogManualRename(QWidget *parent = 0);
- void init(const QString &originalFileName, const QString &newFileName);
+ void init(const QString &originalFileName, const QString &newFileName);
- bool automaticRename() const { return _automaticRename; }
- QString fileName() const { return lineEdit->text(); }
+ bool automaticRename() const { return _automaticRename; }
+ QString fileName() const { return lineEdit->text(); }
private:
- QString _originalFileName;
- bool _automaticRename;
+ QString _originalFileName;
+ bool _automaticRename;
private slots:
- void on_pushButtonAutomatic_clicked();
- void on_pushButtonOriginal_clicked();
+ void on_pushButtonAutomatic_clicked();
+ void on_pushButtonOriginal_clicked();
};
#endif
diff --git a/renamah/extension_policy.cpp b/renamah/extension_policy.cpp
index 759eb9d..66aeea3 100644
--- a/renamah/extension_policy.cpp
+++ b/renamah/extension_policy.cpp
@@ -1,59 +1,59 @@
#include "extension_policy.h"
QString ExtensionPolicy::applyFilterOnFilePath(const core::Filter &filter, int fileIndex, const QString &filePath,
- const QString &originalFilePath) const
+ const QString &originalFilePath) const
{
- QDir dir = QFileInfo(filePath).dir();
+ QDir dir = QFileInfo(filePath).dir();
- if (_filterPolicy == FilterAll)
- return dir.filePath(filter.apply(core::FilterFileInfo(originalFilePath, QFileInfo(filePath).fileName(), fileIndex)));
+ if (_filterPolicy == FilterAll)
+ return dir.filePath(filter.apply(core::FilterFileInfo(originalFilePath, QFileInfo(filePath).fileName(), fileIndex)));
- QString baseName, extension;
- getBaseNameAndExtension(filePath, baseName, extension);
+ QString baseName, extension;
+ getBaseNameAndExtension(filePath, baseName, extension);
- switch (_filterPolicy)
- {
- case FilterBaseName: return getFilePath(filter.apply(core::FilterFileInfo(originalFilePath, baseName, fileIndex)), extension, dir);
- case FilterExtension: return getFilePath(baseName, filter.apply(core::FilterFileInfo(originalFilePath, extension, fileIndex)), dir);
- default: return "";
- }
+ switch (_filterPolicy)
+ {
+ case FilterBaseName: return getFilePath(filter.apply(core::FilterFileInfo(originalFilePath, baseName, fileIndex)), extension, dir);
+ case FilterExtension: return getFilePath(baseName, filter.apply(core::FilterFileInfo(originalFilePath, extension, fileIndex)), dir);
+ default: return "";
+ }
}
void ExtensionPolicy::getBaseNameAndExtension(const QString &filePath, QString &baseName, QString &extension) const
{
- QFileInfo fileInfo(filePath);
-
- switch (_extensionDefinition)
+ QFileInfo fileInfo(filePath);
+
+ switch (_extensionDefinition)
+ {
+ case LastPoint:
+ baseName = fileInfo.completeBaseName();
+ extension = fileInfo.suffix();
+ break;
+ case FirstPoint:
+ baseName = fileInfo.baseName();
+ extension = fileInfo.completeSuffix();
+ break;
+ case NthPointFromRight:
{
- case LastPoint:
- baseName = fileInfo.completeBaseName();
- extension = fileInfo.suffix();
- break;
- case FirstPoint:
- baseName = fileInfo.baseName();
- extension = fileInfo.completeSuffix();
- break;
- case NthPointFromRight:
- {
- QString fileName = fileInfo.fileName();
- int point = qMin(_nthPointFromRight + 1, fileName.count('.') + 1);
- baseName = fileName.section('.', 0, - point);
- extension = fileName.section('.', - point + 1, -1);
- break;
- }
- default:;
+ QString fileName = fileInfo.fileName();
+ int point = qMin(_nthPointFromRight + 1, fileName.count('.') + 1);
+ baseName = fileName.section('.', 0, - point);
+ extension = fileName.section('.', - point + 1, -1);
+ break;
}
+ default:;
+ }
}
QString ExtensionPolicy::getFilePath(const QString &baseName, const QString &extension, const QDir &dir) const
{
- if (extension == "")
- return dir.absoluteFilePath(baseName);
- else
- return dir.absoluteFilePath(baseName + "." + extension);
+ if (extension == "")
+ return dir.absoluteFilePath(baseName);
+ else
+ return dir.absoluteFilePath(baseName + "." + extension);
}
void ExtensionPolicy::reset()
{
- *this = ExtensionPolicy();
+ *this = ExtensionPolicy();
}
diff --git a/renamah/extension_policy.h b/renamah/extension_policy.h
index 7cdac06..1fd445d 100644
--- a/renamah/extension_policy.h
+++ b/renamah/extension_policy.h
@@ -1,57 +1,57 @@
#ifndef EXTENSION_POLICY_H
#define EXTENSION_POLICY_H
#include <QDir>
#include <interfaces/filter.h>
class ExtensionPolicy
{
public:
- enum FilterPolicy {
- FilterBaseName,
- FilterExtension,
- FilterAll
- };
+ enum FilterPolicy {
+ FilterBaseName,
+ FilterExtension,
+ FilterAll
+ };
- enum ExtensionDefinition {
- FirstPoint,
- LastPoint,
- NthPointFromRight
- };
+ enum ExtensionDefinition {
+ FirstPoint,
+ LastPoint,
+ NthPointFromRight
+ };
- ExtensionPolicy() :
- _filterPolicy(FilterBaseName),
- _extensionDefinition(LastPoint),
- _nthPointFromRight(1) {}
+ ExtensionPolicy() :
+ _filterPolicy(FilterBaseName),
+ _extensionDefinition(LastPoint),
+ _nthPointFromRight(1) {}
- FilterPolicy filterPolicy() const { return _filterPolicy; }
- void setFilterPolicy(FilterPolicy value) { _filterPolicy = value; }
+ FilterPolicy filterPolicy() const { return _filterPolicy; }
+ void setFilterPolicy(FilterPolicy value) { _filterPolicy = value; }
- ExtensionDefinition extensionDefinition() const { return _extensionDefinition; }
- void setExtensionDefinition(ExtensionDefinition value) { _extensionDefinition = value; }
+ ExtensionDefinition extensionDefinition() const { return _extensionDefinition; }
+ void setExtensionDefinition(ExtensionDefinition value) { _extensionDefinition = value; }
- int nthPointFromRight() const { return _nthPointFromRight; }
- void setNthPointFromRight(int value) { _nthPointFromRight = value; }
+ int nthPointFromRight() const { return _nthPointFromRight; }
+ void setNthPointFromRight(int value) { _nthPointFromRight = value; }
- bool operator==(const ExtensionPolicy &other) const {
- return _filterPolicy == other._filterPolicy &&
- _extensionDefinition == other._extensionDefinition &&
- _nthPointFromRight == other._nthPointFromRight;
- }
+ bool operator==(const ExtensionPolicy &other) const {
+ return _filterPolicy == other._filterPolicy &&
+ _extensionDefinition == other._extensionDefinition &&
+ _nthPointFromRight == other._nthPointFromRight;
+ }
- QString applyFilterOnFilePath(const core::Filter &filter, int fileIndex, const QString &filePath, const QString &originalFilePath) const;
+ QString applyFilterOnFilePath(const core::Filter &filter, int fileIndex, const QString &filePath, const QString &originalFilePath) const;
- /*! Reset to default settings */
- void reset();
+ /*! Reset to default settings */
+ void reset();
private:
- FilterPolicy _filterPolicy;
- ExtensionDefinition _extensionDefinition;
- int _nthPointFromRight;
+ FilterPolicy _filterPolicy;
+ ExtensionDefinition _extensionDefinition;
+ int _nthPointFromRight;
- void getBaseNameAndExtension(const QString &filePath, QString &baseName, QString &extension) const;
- QString getFilePath(const QString &baseName, const QString &extension, const QDir &dir) const;
+ void getBaseNameAndExtension(const QString &filePath, QString &baseName, QString &extension) const;
+ QString getFilePath(const QString &baseName, const QString &extension, const QDir &dir) const;
};
#endif
diff --git a/renamah/file_model.cpp b/renamah/file_model.cpp
index 2291d59..6caf09c 100644
--- a/renamah/file_model.cpp
+++ b/renamah/file_model.cpp
@@ -1,383 +1,383 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QFileInfo>
#include <QPair>
#include <QIcon>
#include <QMimeData>
#include <QDateTime>
#include "filter_model.h"
#include "file_model.h"
FileModel *FileModel::_instance = 0;
FileModel &FileModel::instance()
{
- if (!_instance)
- _instance = new FileModel;
+ if (!_instance)
+ _instance = new FileModel;
- return *_instance;
+ return *_instance;
}
int FileModel::rowCount(const QModelIndex &parent) const
{
- return _originals.count();
+ return _originals.count();
}
int FileModel::columnCount(const QModelIndex &parent) const
{
- return 2;
+ return 2;
}
QVariant FileModel::data(const QModelIndex &index, int role) const
{
- QString original = _originals[index.row()];
- QFileInfo originalFileInfo(original);
- QString renamed;
- bool manual = false;
-
- if (_manualMapping.find(original) != _manualMapping.end()) {
- manual = true;
- renamed = _manualMapping[original];
- }
- else if (_renamedMapping.find(original) != _renamedMapping.end())
- renamed = _renamedMapping[original];
- else
- {
- renamed = FilterModel::instance().apply(original, index.row());
- const_cast<QMap<QString,QString> &>(_renamedMapping)[original] = renamed;
- }
-
- switch (role)
- {
- case Qt::DisplayRole:
- switch (index.column())
- {
- case 0: return originalFileInfo.fileName();
- case 1: return QFileInfo(renamed).fileName();
- default:;
- }
- break;
+ QString original = _originals[index.row()];
+ QFileInfo originalFileInfo(original);
+ QString renamed;
+ bool manual = false;
+
+ if (_manualMapping.find(original) != _manualMapping.end()) {
+ manual = true;
+ renamed = _manualMapping[original];
+ }
+ else if (_renamedMapping.find(original) != _renamedMapping.end())
+ renamed = _renamedMapping[original];
+ else
+ {
+ renamed = FilterModel::instance().apply(original, index.row());
+ const_cast<QMap<QString,QString> &>(_renamedMapping)[original] = renamed;
+ }
+
+ switch (role)
+ {
+ case Qt::DisplayRole:
+ switch (index.column())
+ {
+ case 0: return originalFileInfo.fileName();
+ case 1: return QFileInfo(renamed).fileName();
+ default:;
+ }
+ break;
case Qt::ForegroundRole:
- switch (index.column())
- {
- case 1:
- if (manual)
- return Qt::red;
- else if (renamed != original)
- return Qt::blue;
- break;
- default:;
- }
- break;
+ switch (index.column())
+ {
+ case 1:
+ if (manual)
+ return Qt::red;
+ else if (renamed != original)
+ return Qt::blue;
+ break;
+ default:;
+ }
+ break;
case Qt::DecorationRole:
- if (index.column() == 1) {
- if (manual)
- return QIcon(":/images/hand.png");
- else if (renamed != original)
- return QIcon(":/images/automatic.png");
- else
- return QIcon(":/images/blank.png");
- }
+ if (index.column() == 1) {
+ if (manual)
+ return QIcon(":/images/hand.png");
+ else if (renamed != original)
+ return QIcon(":/images/automatic.png");
+ else
+ return QIcon(":/images/blank.png");
+ }
default:;
}
- return QVariant();
+ return QVariant();
}
QVariant FileModel::headerData(int section, Qt::Orientation orientation, int role) const
{
- if (role == Qt::DisplayRole)
- switch (section)
- {
- case 0: return tr("Original");
- case 1: return tr("Renamed");
- default:;
- }
- return QVariant();
+ if (role == Qt::DisplayRole)
+ switch (section)
+ {
+ case 0: return tr("Original");
+ case 1: return tr("Renamed");
+ default:;
+ }
+ return QVariant();
}
void FileModel::addFile(const QString &filePath)
{
- if (_originals.indexOf(filePath) >= 0)
- return;
+ if (_originals.indexOf(filePath) >= 0)
+ return;
- beginInsertRows(QModelIndex(), _originals.count(), _originals.count());
- _originals << filePath;
- endInsertRows();
- invalidate();
+ beginInsertRows(QModelIndex(), _originals.count(), _originals.count());
+ _originals << filePath;
+ endInsertRows();
+ invalidate();
}
bool FileModel::removeRows(int row, int count, const QModelIndex &parent)
{
- if (row < 0 || row > rowCount() - 1 ||
- row + count < 0 || row + count > rowCount())
- return false;
+ if (row < 0 || row > rowCount() - 1 ||
+ row + count < 0 || row + count > rowCount())
+ return false;
- beginRemoveRows(parent, row, row + count - 1);
+ beginRemoveRows(parent, row, row + count - 1);
- while (count)
- {
- QString fileName = _originals[row];
- _originals.removeAt(row);
- _renamedMapping.remove(fileName);
- _manualMapping.remove(fileName);
+ while (count)
+ {
+ QString fileName = _originals[row];
+ _originals.removeAt(row);
+ _renamedMapping.remove(fileName);
+ _manualMapping.remove(fileName);
- count--;
- }
+ count--;
+ }
- endRemoveRows();
- invalidate();
+ endRemoveRows();
+ invalidate();
}
void FileModel::invalidate() {
- _renamedMapping.clear();
+ _renamedMapping.clear();
- if (rowCount())
- emit dataChanged(index(0, 1), index(rowCount() - 1, 1));
+ if (rowCount())
+ emit dataChanged(index(0, 1), index(rowCount() - 1, 1));
}
QString FileModel::originalFileName(const QModelIndex &index) const {
- if (index.row() < 0 || index.row() >= rowCount())
- return "";
+ if (index.row() < 0 || index.row() >= rowCount())
+ return "";
- return _originals[index.row()];
+ return _originals[index.row()];
}
QString FileModel::renamedFileName(const QModelIndex &index) const {
- if (index.row() < 0 || index.row() >= rowCount())
- return "";
-
- QString original = _originals[index.row()];
- if (_manualMapping.find(original) != _manualMapping.end())
- return _manualMapping[original];
- else
- return FilterModel::instance().apply(original, index.row());
+ if (index.row() < 0 || index.row() >= rowCount())
+ return "";
+
+ QString original = _originals[index.row()];
+ if (_manualMapping.find(original) != _manualMapping.end())
+ return _manualMapping[original];
+ else
+ return FilterModel::instance().apply(original, index.row());
}
void FileModel::setManualRenaming(const QModelIndex &index, const QString &renamedFileName) {
- QString original = originalFileName(index);
- if (original == "")
- return;
+ QString original = originalFileName(index);
+ if (original == "")
+ return;
- _manualMapping[original] = renamedFileName;
- _renamedMapping.remove(original);
+ _manualMapping[original] = renamedFileName;
+ _renamedMapping.remove(original);
- emit dataChanged(this->index(index.row(), 0), this->index(index.row(), columnCount() - 1));
+ emit dataChanged(this->index(index.row(), 0), this->index(index.row(), columnCount() - 1));
}
void FileModel::removeManualRenaming(const QModelIndex &index) {
- QString original = originalFileName(index);
- if (original == "")
- return;
+ QString original = originalFileName(index);
+ if (original == "")
+ return;
- _manualMapping.remove(original);
- _renamedMapping.remove(original);
+ _manualMapping.remove(original);
+ _renamedMapping.remove(original);
- emit dataChanged(this->index(index.row(), 0), this->index(index.row(), columnCount() - 1));
+ emit dataChanged(this->index(index.row(), 0), this->index(index.row(), columnCount() - 1));
}
Qt::ItemFlags FileModel::flags(const QModelIndex &index) const {
- Qt::ItemFlags flags = QAbstractListModel::flags(index);
+ Qt::ItemFlags flags = QAbstractListModel::flags(index);
- if (index.isValid())
- return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
- else
- return Qt::ItemIsDropEnabled | flags;
+ if (index.isValid())
+ return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
+ else
+ return Qt::ItemIsDropEnabled | flags;
}
Qt::DropActions FileModel::supportedDropActions() const {
- return Qt::MoveAction;
+ return Qt::MoveAction;
}
#define MIMETYPE QLatin1String("file-rows")
QStringList FileModel::mimeTypes() const {
- QStringList types;
- types << MIMETYPE;
- return types;
+ QStringList types;
+ types << MIMETYPE;
+ return types;
}
QMimeData *FileModel::mimeData(const QModelIndexList &indexes) const {
- QMimeData *mimeData = new QMimeData;
- QByteArray encodedData;
-
- QDataStream stream(&encodedData, QIODevice::WriteOnly);
-
- QList<int> rowsToMove;
- foreach (QModelIndex index, indexes) {
- if (index.isValid()) {
- if (rowsToMove.indexOf(index.row()) < 0) {
- rowsToMove << index.row();
- stream << index.row();
- }
- }
- }
-
- mimeData->setData(MIMETYPE, encodedData);
- return mimeData;
+ QMimeData *mimeData = new QMimeData;
+ QByteArray encodedData;
+
+ QDataStream stream(&encodedData, QIODevice::WriteOnly);
+
+ QList<int> rowsToMove;
+ foreach (QModelIndex index, indexes) {
+ if (index.isValid()) {
+ if (rowsToMove.indexOf(index.row()) < 0) {
+ rowsToMove << index.row();
+ stream << index.row();
+ }
+ }
+ }
+
+ mimeData->setData(MIMETYPE, encodedData);
+ return mimeData;
}
bool FileModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
- if (action == Qt::IgnoreAction)
- return false;
-
- _dropRows.clear();
-
- // Get the rows to move
- QList<int> rowsToMove;
- QByteArray inData = data->data(MIMETYPE);
- QDataStream stream(inData);
- while (!stream.atEnd()) {
- int r;
- stream >> r;
- rowsToMove << r;
- }
- qSort(rowsToMove);
-
- QStringList filesToMove;
- int insertionIndex = row;
- int parentInsertionIndex = parent.isValid() ? parent.row() : -1;
- foreach (int rowIndex, rowsToMove) {
- if (rowIndex < row)
- insertionIndex--;
- if (rowIndex < parent.row()) {
- parentInsertionIndex--;
- }
- filesToMove << _originals[rowIndex];
- }
-
- for (int i = 0; i < rowsToMove.count(); ++i) {
- _originals.removeAt(rowsToMove[i] - i);
- }
-
- if (insertionIndex != -1) {
- if (insertionIndex >= rowCount()) {
- foreach (const QString &fileName, filesToMove) {
- _dropRows << _originals.count();
- _originals << fileName;
- }
- } else {
- int i = 0;
- foreach (const QString &fileName, filesToMove) {
- _dropRows << insertionIndex + i;
- _originals.insert(insertionIndex + i, fileName);
- i++;
- }
- }
- } else if (parent.isValid()) {
- if (parentInsertionIndex == parent.row()) {
- int i = 0;
- foreach (const QString &fileName, filesToMove) {
- _dropRows << parentInsertionIndex + i;
- _originals.insert(parentInsertionIndex + i, fileName);
- i++;
- }
- } else {
- int i = 0;
- foreach (const QString &fileName, filesToMove) {
- _dropRows << parentInsertionIndex + i + 1;
- _originals.insert(parentInsertionIndex + i + 1, fileName);
- i++;
- }
- }
- } else if (!parent.isValid()) {
- foreach (const QString &fileName, filesToMove) {
- _dropRows << _originals.count();
- _originals << fileName;
- }
- }
-
- invalidate();
-
- emit dropDone();
-
- return false;
+ if (action == Qt::IgnoreAction)
+ return false;
+
+ _dropRows.clear();
+
+ // Get the rows to move
+ QList<int> rowsToMove;
+ QByteArray inData = data->data(MIMETYPE);
+ QDataStream stream(inData);
+ while (!stream.atEnd()) {
+ int r;
+ stream >> r;
+ rowsToMove << r;
+ }
+ qSort(rowsToMove);
+
+ QStringList filesToMove;
+ int insertionIndex = row;
+ int parentInsertionIndex = parent.isValid() ? parent.row() : -1;
+ foreach (int rowIndex, rowsToMove) {
+ if (rowIndex < row)
+ insertionIndex--;
+ if (rowIndex < parent.row()) {
+ parentInsertionIndex--;
+ }
+ filesToMove << _originals[rowIndex];
+ }
+
+ for (int i = 0; i < rowsToMove.count(); ++i) {
+ _originals.removeAt(rowsToMove[i] - i);
+ }
+
+ if (insertionIndex != -1) {
+ if (insertionIndex >= rowCount()) {
+ foreach (const QString &fileName, filesToMove) {
+ _dropRows << _originals.count();
+ _originals << fileName;
+ }
+ } else {
+ int i = 0;
+ foreach (const QString &fileName, filesToMove) {
+ _dropRows << insertionIndex + i;
+ _originals.insert(insertionIndex + i, fileName);
+ i++;
+ }
+ }
+ } else if (parent.isValid()) {
+ if (parentInsertionIndex == parent.row()) {
+ int i = 0;
+ foreach (const QString &fileName, filesToMove) {
+ _dropRows << parentInsertionIndex + i;
+ _originals.insert(parentInsertionIndex + i, fileName);
+ i++;
+ }
+ } else {
+ int i = 0;
+ foreach (const QString &fileName, filesToMove) {
+ _dropRows << parentInsertionIndex + i + 1;
+ _originals.insert(parentInsertionIndex + i + 1, fileName);
+ i++;
+ }
+ }
+ } else if (!parent.isValid()) {
+ foreach (const QString &fileName, filesToMove) {
+ _dropRows << _originals.count();
+ _originals << fileName;
+ }
+ }
+
+ invalidate();
+
+ emit dropDone();
+
+ return false;
}
void FileModel::upRows(const QModelIndexList &indexes) {
- if (!indexes.count())
- return;
+ if (!indexes.count())
+ return;
- _dropRows.clear();
+ _dropRows.clear();
- QList<int> rows;
- foreach (const QModelIndex &index, indexes)
- rows << index.row();
+ QList<int> rows;
+ foreach (const QModelIndex &index, indexes)
+ rows << index.row();
- qSort(rows);
+ qSort(rows);
- if (rows[0] <= 0)
- return;
+ if (rows[0] <= 0)
+ return;
- foreach (int row, rows) {
- _originals.move(row, row - 1);
- _dropRows << row - 1;
- }
+ foreach (int row, rows) {
+ _originals.move(row, row - 1);
+ _dropRows << row - 1;
+ }
- invalidate();
+ invalidate();
}
void FileModel::downRows(const QModelIndexList &indexes) {
- if (!indexes.count())
- return;
+ if (!indexes.count())
+ return;
- _dropRows.clear();
+ _dropRows.clear();
- QList<int> rows;
- foreach (const QModelIndex &index, indexes)
- rows << index.row();
+ QList<int> rows;
+ foreach (const QModelIndex &index, indexes)
+ rows << index.row();
- qSort(rows.begin(), rows.end(), qGreater<int>());
+ qSort(rows.begin(), rows.end(), qGreater<int>());
- if (rows[0] >= _originals.count() - 1)
- return;
+ if (rows[0] >= _originals.count() - 1)
+ return;
- foreach (int row, rows) {
- _originals.move(row, row + 1);
- _dropRows << row + 1;
- }
+ foreach (int row, rows) {
+ _originals.move(row, row + 1);
+ _dropRows << row + 1;
+ }
- invalidate();
+ invalidate();
}
bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
{
- return s1.toLower() < s2.toLower();
+ return s1.toLower() < s2.toLower();
}
bool modificationDateLessThan(const QString &fileName1, const QString &fileName2)
{
- return QFileInfo(fileName1).lastModified() < QFileInfo(fileName2).lastModified();
+ return QFileInfo(fileName1).lastModified() < QFileInfo(fileName2).lastModified();
}
void FileModel::sort(SortType sortType) {
- switch (sortType) {
- case SortByName:
- qSort(_originals.begin(), _originals.end(), caseInsensitiveLessThan);
- invalidate();
- break;
- case SortByModificationDate:
- qSort(_originals.begin(), _originals.end(), modificationDateLessThan);
- invalidate();
- break;
- default:;
- }
+ switch (sortType) {
+ case SortByName:
+ qSort(_originals.begin(), _originals.end(), caseInsensitiveLessThan);
+ invalidate();
+ break;
+ case SortByModificationDate:
+ qSort(_originals.begin(), _originals.end(), modificationDateLessThan);
+ invalidate();
+ break;
+ default:;
+ }
}
diff --git a/renamah/file_model.h b/renamah/file_model.h
index 314c885..53bd0b3 100644
--- a/renamah/file_model.h
+++ b/renamah/file_model.h
@@ -1,79 +1,79 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FILE_MODEL_H
#define FILE_MODEL_H
#include <QAbstractListModel>
#include <QStringList>
class FileModel : public QAbstractListModel
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum SortType {
- SortByName,
- SortByModificationDate
- };
+ enum SortType {
+ SortByName,
+ SortByModificationDate
+ };
- static FileModel &instance();
+ static FileModel &instance();
- /*! Add a file in the model */
- void addFile(const QString &filePath);
+ /*! Add a file in the model */
+ void addFile(const QString &filePath);
- QString originalFileName(const QModelIndex &index) const;
- QString renamedFileName(const QModelIndex &index) const;
+ QString originalFileName(const QModelIndex &index) const;
+ QString renamedFileName(const QModelIndex &index) const;
- void setManualRenaming(const QModelIndex &index, const QString &renamedFileName);
- void removeManualRenaming(const QModelIndex &index);
+ void setManualRenaming(const QModelIndex &index, const QString &renamedFileName);
+ void removeManualRenaming(const QModelIndex &index);
- const QList<int> &dropRows() const { return _dropRows; }
- void upRows(const QModelIndexList &indexes);
- void downRows(const QModelIndexList &indexes);
- void sort(SortType sortType);
+ const QList<int> &dropRows() const { return _dropRows; }
+ void upRows(const QModelIndexList &indexes);
+ void downRows(const QModelIndexList &indexes);
+ void sort(SortType sortType);
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
- bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
- Qt::ItemFlags flags(const QModelIndex &index) const;
- Qt::DropActions supportedDropActions() const;
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ int columnCount(const QModelIndex &parent = QModelIndex()) const;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+ QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
+ bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
+ Qt::ItemFlags flags(const QModelIndex &index) const;
+ Qt::DropActions supportedDropActions() const;
+ QStringList mimeTypes() const;
+ QMimeData *mimeData(const QModelIndexList &indexes) const;
+ bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
public slots:
- /*!
- * \brief (re-)Apply filters on files and eventually generate renamed files
- */
- void invalidate();
+ /*!
+ * \brief (re-)Apply filters on files and eventually generate renamed files
+ */
+ void invalidate();
signals:
- void dropDone(); /*!< called when the drop have been successfully done */
+ void dropDone(); /*!< called when the drop have been successfully done */
private:
- static FileModel *_instance;
- QStringList _originals;
- QMap<QString,QString> _renamedMapping;
- QMap<QString,QString> _manualMapping;
- QList<int> _dropRows;
+ static FileModel *_instance;
+ QStringList _originals;
+ QMap<QString,QString> _renamedMapping;
+ QMap<QString,QString> _manualMapping;
+ QList<int> _dropRows;
};
#endif
diff --git a/renamah/filter_manager.cpp b/renamah/filter_manager.cpp
index 3dfa651..4ff3fd4 100644
--- a/renamah/filter_manager.cpp
+++ b/renamah/filter_manager.cpp
@@ -1,29 +1,29 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 "filter_manager.h"
FilterManager *FilterManager::_instance = 0;
FilterManager &FilterManager::instance()
{
- if (!_instance)
- _instance = new FilterManager;
+ if (!_instance)
+ _instance = new FilterManager;
- return *_instance;
+ return *_instance;
}
diff --git a/renamah/filter_manager.h b/renamah/filter_manager.h
index d1b76ce..63a44c0 100644
--- a/renamah/filter_manager.h
+++ b/renamah/filter_manager.h
@@ -1,35 +1,35 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FILTER_MANAGER_H
#define FILTER_MANAGER_H
#include "modifier_manager.h"
class FilterManager : public ModifierManager
{
public:
- static FilterManager &instance();
+ static FilterManager &instance();
- QString modifierTypeName() { return QObject::tr("filter"); }
+ QString modifierTypeName() { return QObject::tr("filter"); }
private:
- static FilterManager *_instance;
+ static FilterManager *_instance;
};
#endif
diff --git a/renamah/filter_model.cpp b/renamah/filter_model.cpp
index 72162b2..c242f0b 100644
--- a/renamah/filter_model.cpp
+++ b/renamah/filter_model.cpp
@@ -1,107 +1,107 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QFileInfo>
#include <interfaces/filter_factory.h>
#include "filter_manager.h"
#include "filter_model.h"
FilterModel *FilterModel::_instance = 0;
FilterModel &FilterModel::instance()
{
- if (!_instance)
- _instance = new FilterModel;
+ if (!_instance)
+ _instance = new FilterModel;
- return *_instance;
+ return *_instance;
}
FilterModel::FilterModel()
- : ModifierModel(&FilterManager::instance())
+ : ModifierModel(&FilterManager::instance())
{
}
QString FilterModel::apply(const QString &filePath, int fileIndex) const
{
- QList<core::Filter*> filters;
- if (exclusiveModifier())
- filters << static_cast<core::Filter*>(exclusiveModifier());
- else
- foreach (core::Modifier *modifier, _modifiers)
- {
- if (_modifierStates[modifier])
- filters << static_cast<core::Filter*>(modifier);
- }
-
- QDir dir = QFileInfo(filePath).dir();
- QString tmpFilePath = filePath;
- foreach (core::Filter *filter, filters)
- {
- if (localExtensionPolicyStates[filter])
- tmpFilePath = localExtensionPolicies[filter].applyFilterOnFilePath(*filter, fileIndex, tmpFilePath, filePath);
- else
- tmpFilePath = _extensionPolicy.applyFilterOnFilePath(*filter, fileIndex, tmpFilePath, filePath);
- }
-
- return tmpFilePath;
+ QList<core::Filter*> filters;
+ if (exclusiveModifier())
+ filters << static_cast<core::Filter*>(exclusiveModifier());
+ else
+ foreach (core::Modifier *modifier, _modifiers)
+ {
+ if (_modifierStates[modifier])
+ filters << static_cast<core::Filter*>(modifier);
+ }
+
+ QDir dir = QFileInfo(filePath).dir();
+ QString tmpFilePath = filePath;
+ foreach (core::Filter *filter, filters)
+ {
+ if (localExtensionPolicyStates[filter])
+ tmpFilePath = localExtensionPolicies[filter].applyFilterOnFilePath(*filter, fileIndex, tmpFilePath, filePath);
+ else
+ tmpFilePath = _extensionPolicy.applyFilterOnFilePath(*filter, fileIndex, tmpFilePath, filePath);
+ }
+
+ return tmpFilePath;
}
void FilterModel::setExtensionPolicy(const ExtensionPolicy &policy)
{
- if (policy == _extensionPolicy)
- return;
+ if (policy == _extensionPolicy)
+ return;
- _extensionPolicy = policy;
+ _extensionPolicy = policy;
- emit modifiersChanged();
+ emit modifiersChanged();
}
bool FilterModel::isLocalExtensionPolicyEnabled(core::Filter *filter) const {
- return localExtensionPolicyStates[filter];
+ return localExtensionPolicyStates[filter];
}
void FilterModel::setLocalExtensionPolicyEnabled(core::Filter *filter, bool state)
{
- localExtensionPolicyStates[filter] = state;
- emit modifiersChanged();
+ localExtensionPolicyStates[filter] = state;
+ emit modifiersChanged();
}
ExtensionPolicy FilterModel::localExtensionPolicy(core::Filter *filter) const
{
- return localExtensionPolicies[filter];
+ return localExtensionPolicies[filter];
}
void FilterModel::setLocalExtensionPolicy(core::Filter *filter, const ExtensionPolicy &policy)
{
- QMap<core::Filter*, ExtensionPolicy>::iterator it = localExtensionPolicies.find(filter);
- if (it == localExtensionPolicies.end())
- localExtensionPolicies.insert(filter, policy);
- else
- *it = policy;
- emit modifiersChanged();
+ QMap<core::Filter*, ExtensionPolicy>::iterator it = localExtensionPolicies.find(filter);
+ if (it == localExtensionPolicies.end())
+ localExtensionPolicies.insert(filter, policy);
+ else
+ *it = policy;
+ emit modifiersChanged();
}
void FilterModel::clear() {
- localExtensionPolicies.clear();
- localExtensionPolicyStates.clear();
- _extensionPolicy = ExtensionPolicy();
+ localExtensionPolicies.clear();
+ localExtensionPolicyStates.clear();
+ _extensionPolicy = ExtensionPolicy();
- ModifierModel::clear();
+ ModifierModel::clear();
}
diff --git a/renamah/filter_model.h b/renamah/filter_model.h
index a2c68b1..0f6b933 100644
--- a/renamah/filter_model.h
+++ b/renamah/filter_model.h
@@ -1,58 +1,58 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FILTER_MODEL_H
#define FILTER_MODEL_H
#include <QDir>
#include "extension_policy.h"
#include "modifier_model.h"
class FilterModel : public ModifierModel
{
- Q_OBJECT
+ Q_OBJECT
public:
- static FilterModel &instance();
+ static FilterModel &instance();
- /*! Returns the filtered result of the file path parameter */
- QString apply(const QString &filePath, int fileIndex) const;
+ /*! Returns the filtered result of the file path parameter */
+ QString apply(const QString &filePath, int fileIndex) const;
- void clear();
+ void clear();
- const ExtensionPolicy &extensionPolicy() const { return _extensionPolicy; }
- void setExtensionPolicy(const ExtensionPolicy &policy);
+ const ExtensionPolicy &extensionPolicy() const { return _extensionPolicy; }
+ void setExtensionPolicy(const ExtensionPolicy &policy);
- bool isLocalExtensionPolicyEnabled(core::Filter *filter) const;
- void setLocalExtensionPolicyEnabled(core::Filter *filter, bool state);
+ bool isLocalExtensionPolicyEnabled(core::Filter *filter) const;
+ void setLocalExtensionPolicyEnabled(core::Filter *filter, bool state);
- ExtensionPolicy localExtensionPolicy(core::Filter *filter) const;
- void setLocalExtensionPolicy(core::Filter *filter, const ExtensionPolicy &policy);
+ ExtensionPolicy localExtensionPolicy(core::Filter *filter) const;
+ void setLocalExtensionPolicy(core::Filter *filter, const ExtensionPolicy &policy);
private:
- FilterModel();
+ FilterModel();
- static FilterModel *_instance;
+ static FilterModel *_instance;
- ExtensionPolicy _extensionPolicy;
- QMap<core::Filter*, ExtensionPolicy> localExtensionPolicies;
- QMap<core::Filter*, bool> localExtensionPolicyStates;
+ ExtensionPolicy _extensionPolicy;
+ QMap<core::Filter*, ExtensionPolicy> localExtensionPolicies;
+ QMap<core::Filter*, bool> localExtensionPolicyStates;
};
#endif
diff --git a/renamah/finalizer_model.cpp b/renamah/finalizer_model.cpp
index 9abf6b7..b5c4f75 100644
--- a/renamah/finalizer_model.cpp
+++ b/renamah/finalizer_model.cpp
@@ -1,56 +1,56 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <interfaces/action.h>
#include "action_manager.h"
#include "finalizer_model.h"
FinalizerModel *FinalizerModel::_instance = 0;
FinalizerModel &FinalizerModel::instance()
{
- if (!_instance)
- _instance = new FinalizerModel;
+ if (!_instance)
+ _instance = new FinalizerModel;
- return *_instance;
+ return *_instance;
}
FinalizerModel::FinalizerModel()
- : ModifierModel(&ActionManager::instance())
+ : ModifierModel(&ActionManager::instance())
{
}
void FinalizerModel::apply(const QString &fileName) const
{
- if (exclusiveModifier())
- {
- static_cast<core::Action*>(exclusiveModifier())->apply(fileName);
- return;
- }
-
- foreach (core::Modifier *modifier, _modifiers)
- {
- core::Action *action = static_cast<core::Action*>(modifier);
- if (_modifierStates[modifier])
- {
- action->apply(fileName);
- }
- }
+ if (exclusiveModifier())
+ {
+ static_cast<core::Action*>(exclusiveModifier())->apply(fileName);
+ return;
+ }
+
+ foreach (core::Modifier *modifier, _modifiers)
+ {
+ core::Action *action = static_cast<core::Action*>(modifier);
+ if (_modifierStates[modifier])
+ {
+ action->apply(fileName);
+ }
+ }
}
diff --git a/renamah/finalizer_model.h b/renamah/finalizer_model.h
index c4716f4..0176d49 100644
--- a/renamah/finalizer_model.h
+++ b/renamah/finalizer_model.h
@@ -1,40 +1,40 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FINALIZER_MODEL_H
#define FINALIZER_MODEL_H
#include "modifier_model.h"
class FinalizerModel : public ModifierModel
{
- Q_OBJECT
+ Q_OBJECT
public:
- static FinalizerModel &instance();
+ static FinalizerModel &instance();
- /*! Apply finalizers on the file in argument */
- void apply(const QString &fileName) const;
+ /*! Apply finalizers on the file in argument */
+ void apply(const QString &fileName) const;
private:
- FinalizerModel();
+ FinalizerModel();
- static FinalizerModel *_instance;
+ static FinalizerModel *_instance;
};
#endif
diff --git a/renamah/form_last_operations.cpp b/renamah/form_last_operations.cpp
index 9c77e85..1f83ed8 100644
--- a/renamah/form_last_operations.cpp
+++ b/renamah/form_last_operations.cpp
@@ -1,57 +1,57 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QDateTime>
#include "processor.h"
#include "form_last_operations.h"
FormLastOperations::FormLastOperations(QWidget *parent)
- : QWidget(parent)
+ : QWidget(parent)
{
- setupUi(this);
-
- connect(&Processor::instance(), SIGNAL(taskSuccess(const QString &, const QString &)),
- this, SLOT(taskSuccess(const QString &, const QString &)));
- connect(&Processor::instance(), SIGNAL(taskFailure(const QString &, const QString &, const QString &)),
- this, SLOT(taskFailure(const QString &, const QString &, const QString &)));
- connect(&Processor::instance(), SIGNAL(started()),
- this, SLOT(processorStarted()));
- connect(&Processor::instance(), SIGNAL(percentProgress(int)),
- this, SLOT(processorPercentProgress(int)));
+ setupUi(this);
+
+ connect(&Processor::instance(), SIGNAL(taskSuccess(const QString &, const QString &)),
+ this, SLOT(taskSuccess(const QString &, const QString &)));
+ connect(&Processor::instance(), SIGNAL(taskFailure(const QString &, const QString &, const QString &)),
+ this, SLOT(taskFailure(const QString &, const QString &, const QString &)));
+ connect(&Processor::instance(), SIGNAL(started()),
+ this, SLOT(processorStarted()));
+ connect(&Processor::instance(), SIGNAL(percentProgress(int)),
+ this, SLOT(processorPercentProgress(int)));
}
void FormLastOperations::taskSuccess(const QString &original, const QString &renamed)
{
- plainTextEditResults->appendHtml(QString("<span style=\"color:#0000AA\"><b>%1</b></span>: %2 --> %3 : <span style=\"color:#00AA00\"><b>SUCCESS</b></span>").arg(Processor::instance().destinationOperationName()).arg(original).arg(renamed));
+ plainTextEditResults->appendHtml(QString("<span style=\"color:#0000AA\"><b>%1</b></span>: %2 --> %3 : <span style=\"color:#00AA00\"><b>SUCCESS</b></span>").arg(Processor::instance().destinationOperationName()).arg(original).arg(renamed));
}
void FormLastOperations::taskFailure(const QString &original, const QString &renamed, const QString &errorMsg)
{
- plainTextEditResults->appendHtml(QString("<span style=\"color:#0000AA\"><b>%1</b></span>: %2 -> %3 : <span style=\"color:#AA0000\"><b>FAILURE</b></span> (%4)").arg(Processor::instance().destinationOperationName()).arg(original).arg(renamed).arg(errorMsg));
+ plainTextEditResults->appendHtml(QString("<span style=\"color:#0000AA\"><b>%1</b></span>: %2 -> %3 : <span style=\"color:#AA0000\"><b>FAILURE</b></span> (%4)").arg(Processor::instance().destinationOperationName()).arg(original).arg(renamed).arg(errorMsg));
}
void FormLastOperations::processorStarted()
{
- plainTextEditResults->appendHtml(QString("<u><b>Renaming session started at %1</b></u>").arg(QDateTime::currentDateTime().toString()));
+ plainTextEditResults->appendHtml(QString("<u><b>Renaming session started at %1</b></u>").arg(QDateTime::currentDateTime().toString()));
}
void FormLastOperations::processorPercentProgress(int percent)
{
- progressBar->setValue(percent);
+ progressBar->setValue(percent);
}
diff --git a/renamah/form_last_operations.h b/renamah/form_last_operations.h
index fd13c97..32f9327 100644
--- a/renamah/form_last_operations.h
+++ b/renamah/form_last_operations.h
@@ -1,38 +1,38 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FORM_LAST_OPERATIONS_H
#define FORM_LAST_OPERATIONS_H
#include "ui_form_last_operations.h"
class FormLastOperations : public QWidget, private Ui::FormLastOperations
{
- Q_OBJECT
+ Q_OBJECT
public:
- FormLastOperations(QWidget *parent = 0);
+ FormLastOperations(QWidget *parent = 0);
private slots:
- void taskSuccess(const QString &original, const QString &renamed);
- void taskFailure(const QString &original, const QString &renamed, const QString &errorMsg);
- void processorStarted();
- void processorPercentProgress(int percent);
+ void taskSuccess(const QString &original, const QString &renamed);
+ void taskFailure(const QString &original, const QString &renamed, const QString &errorMsg);
+ void processorStarted();
+ void processorPercentProgress(int percent);
};
#endif
diff --git a/renamah/form_twinning.cpp b/renamah/form_twinning.cpp
index 206aa45..66b73b1 100644
--- a/renamah/form_twinning.cpp
+++ b/renamah/form_twinning.cpp
@@ -1,465 +1,465 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QDir>
#include <QKeyEvent>
#include <QFileDialog>
#include <QMouseEvent>
#include <QScrollBar>
#include "form_twinning.h"
FormTwinning::FormTwinning(QWidget *parent)
- : QWidget(parent),
- _chainedDir(true)
+ : QWidget(parent),
+ _chainedDir(true)
{
- setupUi(this);
+ setupUi(this);
- init();
+ init();
}
bool FormTwinning::eventFilter(QObject *watched, QEvent *event)
{
- switch (event->type())
- {
- case QEvent::KeyPress:
- {
- QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
- if (keyEvent->key() == Qt::Key_Return)
- {
- if (watched == lineEditLeftDir)
+ switch (event->type())
+ {
+ case QEvent::KeyPress:
+ {
+ QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
+ if (keyEvent->key() == Qt::Key_Return)
+ {
+ if (watched == lineEditLeftDir)
validateLeftDir();
- else if (watched == lineEditRightDir)
+ else if (watched == lineEditRightDir)
validateRightDir();
- else if (watched == comboBoxLeftExtension)
+ else if (watched == comboBoxLeftExtension)
validateLeftExtension();
- else if (watched == comboBoxRightExtension)
+ else if (watched == comboBoxRightExtension)
validateRightExtension();
- }
- }
- break;
- case QEvent::MouseButtonDblClick:
- {
- QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
- if (watched == treeViewLeft->viewport())
- {
- QModelIndex index = treeViewLeft->indexAt(mouseEvent->pos());
- if (index.isValid() && _leftModel->fileInfo(index).isDir())
- {
+ }
+ }
+ break;
+ case QEvent::MouseButtonDblClick:
+ {
+ QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
+ if (watched == treeViewLeft->viewport())
+ {
+ QModelIndex index = treeViewLeft->indexAt(mouseEvent->pos());
+ if (index.isValid() && _leftModel->fileInfo(index).isDir())
+ {
lineEditLeftDir->setText(_leftModel->filePath(index));
validateLeftDir();
- }
- } else if (watched == treeViewRight->viewport())
- {
- QModelIndex index = treeViewRight->indexAt(mouseEvent->pos());
- if (index.isValid() && _rightModel->fileInfo(index).isDir())
- {
+ }
+ } else if (watched == treeViewRight->viewport())
+ {
+ QModelIndex index = treeViewRight->indexAt(mouseEvent->pos());
+ if (index.isValid() && _rightModel->fileInfo(index).isDir())
+ {
lineEditRightDir->setText(_rightModel->filePath(index));
validateRightDir();
- }
- }
- }
- break;
- default:;
- }
-
- return QWidget::eventFilter(watched, event);
+ }
+ }
+ }
+ break;
+ default:;
+ }
+
+ return QWidget::eventFilter(watched, event);
}
void FormTwinning::init()
{
- lineEditLeftDir->installEventFilter(this);
- lineEditRightDir->installEventFilter(this);
- comboBoxLeftExtension->installEventFilter(this);
- comboBoxRightExtension->installEventFilter(this);
- treeViewLeft->viewport()->installEventFilter(this);
- treeViewRight->viewport()->installEventFilter(this);
- connect(treeViewLeft->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(leftTreeVerticalScrollBarValueChanged(int)));
- connect(treeViewRight->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(rightTreeVerticalScrollBarValueChanged(int)));
-
- treeViewLeft->setModel(_leftModel = new SimpleDirModel);
- _leftModel->setFilter(QDir::Files | QDir::AllDirs);
- _leftModel->setSorting(QDir::Name | QDir::IgnoreCase | QDir::DirsFirst);
- connect(_leftModel, SIGNAL(modelReset()), this, SLOT(leftModelReset()));
- connect(_leftModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
- this, SLOT(leftRowsInserted(const QModelIndex &, int, int)));
- connect(_leftModel, SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
- this, SLOT(leftRowsRemoved(const QModelIndex &, int, int)));
- connect(treeViewLeft->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)),
- this, SLOT(currentLeftRowChanged(const QModelIndex&, const QModelIndex&)));
-
- treeViewRight->setModel(_rightModel = new SimpleDirModel);
- _rightModel->setFilter(QDir::Files | QDir::AllDirs);
- _rightModel->setSorting(QDir::Name | QDir::IgnoreCase | QDir::DirsFirst);
+ lineEditLeftDir->installEventFilter(this);
+ lineEditRightDir->installEventFilter(this);
+ comboBoxLeftExtension->installEventFilter(this);
+ comboBoxRightExtension->installEventFilter(this);
+ treeViewLeft->viewport()->installEventFilter(this);
+ treeViewRight->viewport()->installEventFilter(this);
+ connect(treeViewLeft->verticalScrollBar(), SIGNAL(valueChanged(int)),
+ this, SLOT(leftTreeVerticalScrollBarValueChanged(int)));
+ connect(treeViewRight->verticalScrollBar(), SIGNAL(valueChanged(int)),
+ this, SLOT(rightTreeVerticalScrollBarValueChanged(int)));
+
+ treeViewLeft->setModel(_leftModel = new SimpleDirModel);
+ _leftModel->setFilter(QDir::Files | QDir::AllDirs);
+ _leftModel->setSorting(QDir::Name | QDir::IgnoreCase | QDir::DirsFirst);
+ connect(_leftModel, SIGNAL(modelReset()), this, SLOT(leftModelReset()));
+ connect(_leftModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
+ this, SLOT(leftRowsInserted(const QModelIndex &, int, int)));
+ connect(_leftModel, SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
+ this, SLOT(leftRowsRemoved(const QModelIndex &, int, int)));
+ connect(treeViewLeft->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)),
+ this, SLOT(currentLeftRowChanged(const QModelIndex&, const QModelIndex&)));
+
+ treeViewRight->setModel(_rightModel = new SimpleDirModel);
+ _rightModel->setFilter(QDir::Files | QDir::AllDirs);
+ _rightModel->setSorting(QDir::Name | QDir::IgnoreCase | QDir::DirsFirst);
connect(_rightModel, SIGNAL(modelReset()), this, SLOT(rightModelReset()));
- connect(_rightModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
- this, SLOT(rightRowsInserted(const QModelIndex &, int, int)));
- connect(_rightModel, SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
- this, SLOT(rightRowsRemoved(const QModelIndex &, int, int)));
- connect(treeViewRight->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)),
- this, SLOT(currentRightRowChanged(const QModelIndex&, const QModelIndex&)));
+ connect(_rightModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
+ this, SLOT(rightRowsInserted(const QModelIndex &, int, int)));
+ connect(_rightModel, SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
+ this, SLOT(rightRowsRemoved(const QModelIndex &, int, int)));
+ connect(treeViewRight->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)),
+ this, SLOT(currentRightRowChanged(const QModelIndex&, const QModelIndex&)));
- refreshChainModeButton();
+ refreshChainModeButton();
- comboBoxLeftExtension->lineEdit()->setText("*.avi,*.mkv");
- validateLeftExtension();
+ comboBoxLeftExtension->lineEdit()->setText("*.avi,*.mkv");
+ validateLeftExtension();
- comboBoxRightExtension->lineEdit()->setText("*.srt,*.sub");
- validateRightExtension();
+ comboBoxRightExtension->lineEdit()->setText("*.srt,*.sub");
+ validateRightExtension();
- lineEditLeftDir->setText(QDir::home().absolutePath());
- validateLeftDir();
+ lineEditLeftDir->setText(QDir::home().absolutePath());
+ validateLeftDir();
- widgetTwinning->setTrees(treeViewLeft, treeViewRight);
+ widgetTwinning->setTrees(treeViewLeft, treeViewRight);
}
void FormTwinning::refreshChainModeButton()
{
- if (_chainedDir)
- pushButtonChainMode->setIcon(QIcon(":/images/chained.png"));
- else
- pushButtonChainMode->setIcon(QIcon(":/images/unchained.png"));
+ if (_chainedDir)
+ pushButtonChainMode->setIcon(QIcon(":/images/chained.png"));
+ else
+ pushButtonChainMode->setIcon(QIcon(":/images/unchained.png"));
}
void FormTwinning::on_pushButtonChainMode_clicked()
{
- // Toggle
- _chainedDir = !_chainedDir;
- refreshChainModeButton();
+ // Toggle
+ _chainedDir = !_chainedDir;
+ refreshChainModeButton();
}
void FormTwinning::validateLeftDir(bool subcall)
{
- if (_leftPath == lineEditLeftDir->text())
- return;
+ if (_leftPath == lineEditLeftDir->text())
+ return;
- _leftPath = lineEditLeftDir->text();
- if (_chainedDir && _rightPath != _leftPath)
- {
- lineEditRightDir->setText(_leftPath);
- validateRightDir(true);
- }
+ _leftPath = lineEditLeftDir->text();
+ if (_chainedDir && _rightPath != _leftPath)
+ {
+ lineEditRightDir->setText(_leftPath);
+ validateRightDir(true);
+ }
- treeViewLeft->setRootIndex(_leftModel->index(_leftPath));
- treeViewLeft->resizeColumnToContents(0);
+ treeViewLeft->setRootIndex(_leftModel->index(_leftPath));
+ treeViewLeft->resizeColumnToContents(0);
- if (!subcall)
- redoTwinning();
+ if (!subcall)
+ redoTwinning();
- widgetTwinning->update();
+ widgetTwinning->update();
}
void FormTwinning::validateRightDir(bool subcall)
{
- if (_rightPath == lineEditRightDir->text())
- return;
+ if (_rightPath == lineEditRightDir->text())
+ return;
- _rightPath = lineEditRightDir->text();
- if (_chainedDir && _leftPath != _rightPath)
- {
- lineEditLeftDir->setText(_rightPath);
- validateLeftDir(true);
- }
+ _rightPath = lineEditRightDir->text();
+ if (_chainedDir && _leftPath != _rightPath)
+ {
+ lineEditLeftDir->setText(_rightPath);
+ validateLeftDir(true);
+ }
- treeViewRight->setRootIndex(_rightModel->index(_rightPath));
- treeViewRight->resizeColumnToContents(0);
+ treeViewRight->setRootIndex(_rightModel->index(_rightPath));
+ treeViewRight->resizeColumnToContents(0);
- if (!subcall)
- redoTwinning();
+ if (!subcall)
+ redoTwinning();
- widgetTwinning->update();
+ widgetTwinning->update();
}
void FormTwinning::validateLeftExtension()
{
- QStringList nameFilters = comboBoxLeftExtension->currentText().split(",");
- _leftModel->setNameFilters(nameFilters);
- treeViewLeft->resizeColumnToContents(0);
- widgetTwinning->update();
+ QStringList nameFilters = comboBoxLeftExtension->currentText().split(",");
+ _leftModel->setNameFilters(nameFilters);
+ treeViewLeft->resizeColumnToContents(0);
+ widgetTwinning->update();
}
void FormTwinning::validateRightExtension()
{
- QStringList nameFilters = comboBoxRightExtension->currentText().split(",");
- _rightModel->setNameFilters(nameFilters);
- treeViewRight->resizeColumnToContents(0);
- widgetTwinning->update();
+ QStringList nameFilters = comboBoxRightExtension->currentText().split(",");
+ _rightModel->setNameFilters(nameFilters);
+ treeViewRight->resizeColumnToContents(0);
+ widgetTwinning->update();
}
void FormTwinning::on_toolButtonLeftDir_clicked()
{
- QString dirPath = QFileDialog::getExistingDirectory(this, tr("Choose a directory for left files"),
- _leftPath);
- if (dirPath == "")
- return;
+ QString dirPath = QFileDialog::getExistingDirectory(this, tr("Choose a directory for left files"),
+ _leftPath);
+ if (dirPath == "")
+ return;
- lineEditLeftDir->setText(dirPath);
- validateLeftDir();
+ lineEditLeftDir->setText(dirPath);
+ validateLeftDir();
}
void FormTwinning::on_toolButtonRightDir_clicked()
{
- QString dirPath = QFileDialog::getExistingDirectory(this, tr("Choose a directory for right files"),
- _rightPath);
- if (dirPath == "")
- return;
+ QString dirPath = QFileDialog::getExistingDirectory(this, tr("Choose a directory for right files"),
+ _rightPath);
+ if (dirPath == "")
+ return;
- lineEditRightDir->setText(dirPath);
- validateRightDir();
+ lineEditRightDir->setText(dirPath);
+ validateRightDir();
}
void FormTwinning::on_comboBoxLeftExtension_currentIndexChanged(const QString &text)
{
- validateLeftExtension();
+ validateLeftExtension();
}
void FormTwinning::on_comboBoxRightExtension_currentIndexChanged(const QString &text)
{
- validateRightExtension();
+ validateRightExtension();
}
void FormTwinning::leftTreeVerticalScrollBarValueChanged(int)
{
- widgetTwinning->update();
+ widgetTwinning->update();
}
void FormTwinning::rightTreeVerticalScrollBarValueChanged(int)
{
- widgetTwinning->update();
+ widgetTwinning->update();
}
void FormTwinning::leftModelReset()
{
}
void FormTwinning::leftRowsInserted(const QModelIndex &parent, int start, int end)
{
}
void FormTwinning::leftRowsRemoved(const QModelIndex &parent, int start, int end)
{
}
void FormTwinning::rightModelReset()
{
}
void FormTwinning::rightRowsInserted(const QModelIndex &parent, int start, int end)
{
}
void FormTwinning::rightRowsRemoved(const QModelIndex &parent, int start, int end)
{
}
QFileInfo FormTwinning::leftFileInfo(int row) const
{
- return _leftModel->fileInfo(_leftModel->index(row, 0, treeViewLeft->rootIndex()));
+ return _leftModel->fileInfo(_leftModel->index(row, 0, treeViewLeft->rootIndex()));
}
QFileInfo FormTwinning::rightFileInfo(int row) const
{
- return _rightModel->fileInfo(_rightModel->index(row, 0, treeViewRight->rootIndex()));
+ return _rightModel->fileInfo(_rightModel->index(row, 0, treeViewRight->rootIndex()));
}
bool pairSortLessThan(const QPair<int,int> pair1, const QPair<int,int> pair2)
{
- return pair1.second < pair2.second;
+ return pair1.second < pair2.second;
}
void FormTwinning::redoTwinning()
{
- _twinning.clear();
-
- // Build left atoms
- QMap<int, QStringList> leftAtomsMapping;
- for (int row = 0; row < _leftModel->rowCount(treeViewLeft->rootIndex()); ++row)
- {
- QFileInfo fileInfo = leftFileInfo(row);
- if (fileInfo.isFile())
- leftAtomsMapping.insert(row, atomize(fileInfo.completeBaseName()));
- }
-
- // Association of every right row with an ordered list of pairs representing a left row and a score
- QMap<int, QList<QPair<int, int> > > mapping;
- for (int rightRow = 0; rightRow < _rightModel->rowCount(treeViewRight->rootIndex()); ++rightRow)
- {
- QList<QPair<int, int> > scores;
- QStringList rightAtoms = atomize(rightFileInfo(rightRow).completeBaseName());
-
- for (int leftRow = 0; leftRow < _leftModel->rowCount(treeViewLeft->rootIndex()); ++leftRow)
- scores << QPair<int, int>(leftRow, challenge(leftAtomsMapping[leftRow], rightAtoms));
-
- // Sort it by score
- qSort(scores.begin(), scores.end(), pairSortLessThan);
-
- mapping.insert(rightRow, scores);
- }
-
- for (int rightRow = 0; rightRow < _rightModel->rowCount(treeViewRight->rootIndex()); ++rightRow)
- {
- const QList<QPair<int, int> > &scores = mapping[rightRow];
- for (int i = scores.count() - 1; i >= 0; --i)
- {
- int leftRow = scores[i].first;
- int score = scores[i].second;
- if (isFree(leftRow, score))
- {
- _twinning.insert(leftRow, QList<int>() << rightRow);
-
- // Remove this left row from mapping
- for (int rightRow = 0; rightRow < _rightModel->rowCount(treeViewRight->rootIndex()); ++rightRow)
- {
- QList<QPair<int, int> > &scores = mapping[rightRow];
- for (int i = 0; i < scores.count(); ++i)
- if (scores[i].first == leftRow)
- {
- scores.removeAt(i);
- break;
- }
+ _twinning.clear();
+
+ // Build left atoms
+ QMap<int, QStringList> leftAtomsMapping;
+ for (int row = 0; row < _leftModel->rowCount(treeViewLeft->rootIndex()); ++row)
+ {
+ QFileInfo fileInfo = leftFileInfo(row);
+ if (fileInfo.isFile())
+ leftAtomsMapping.insert(row, atomize(fileInfo.completeBaseName()));
+ }
+
+ // Association of every right row with an ordered list of pairs representing a left row and a score
+ QMap<int, QList<QPair<int, int> > > mapping;
+ for (int rightRow = 0; rightRow < _rightModel->rowCount(treeViewRight->rootIndex()); ++rightRow)
+ {
+ QList<QPair<int, int> > scores;
+ QStringList rightAtoms = atomize(rightFileInfo(rightRow).completeBaseName());
+
+ for (int leftRow = 0; leftRow < _leftModel->rowCount(treeViewLeft->rootIndex()); ++leftRow)
+ scores << QPair<int, int>(leftRow, challenge(leftAtomsMapping[leftRow], rightAtoms));
+
+ // Sort it by score
+ qSort(scores.begin(), scores.end(), pairSortLessThan);
+
+ mapping.insert(rightRow, scores);
+ }
+
+ for (int rightRow = 0; rightRow < _rightModel->rowCount(treeViewRight->rootIndex()); ++rightRow)
+ {
+ const QList<QPair<int, int> > &scores = mapping[rightRow];
+ for (int i = scores.count() - 1; i >= 0; --i)
+ {
+ int leftRow = scores[i].first;
+ int score = scores[i].second;
+ if (isFree(leftRow, score))
+ {
+ _twinning.insert(leftRow, QList<int>() << rightRow);
+
+ // Remove this left row from mapping
+ for (int rightRow = 0; rightRow < _rightModel->rowCount(treeViewRight->rootIndex()); ++rightRow)
+ {
+ QList<QPair<int, int> > &scores = mapping[rightRow];
+ for (int i = 0; i < scores.count(); ++i)
+ if (scores[i].first == leftRow)
+ {
+ scores.removeAt(i);
+ break;
}
+ }
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- widgetTwinning->setTwinning(_twinning);
- }
+ widgetTwinning->setTwinning(_twinning);
+}
bool FormTwinning::isFree(int leftRow, int score) const
{
- return true;
+ return true;
}
void FormTwinning::currentLeftRowChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
- QMap<int, QList<int> >::const_iterator it = _twinning.find(current.row());
- if (it == _twinning.end())
- return;
+ QMap<int, QList<int> >::const_iterator it = _twinning.find(current.row());
+ if (it == _twinning.end())
+ return;
- treeViewRight->selectionModel()->setCurrentIndex(_rightModel->index((*it)[0], 0, treeViewRight->rootIndex()),
- QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
+ treeViewRight->selectionModel()->setCurrentIndex(_rightModel->index((*it)[0], 0, treeViewRight->rootIndex()),
+ QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
void FormTwinning::currentRightRowChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
}
QStringList FormTwinning::atomize(const QString &text) const
{
- QStringList atoms;
+ QStringList atoms;
- QRegExp regExp("[\\da-zA-z]+");
- int count = 0;
- int pos = 0;
- while ((pos = regExp.indexIn(text, pos)) != -1) {
- ++count;
- atoms << text.mid(pos, regExp.matchedLength());
- pos += regExp.matchedLength();
- }
+ QRegExp regExp("[\\da-zA-z]+");
+ int count = 0;
+ int pos = 0;
+ while ((pos = regExp.indexIn(text, pos)) != -1) {
+ ++count;
+ atoms << text.mid(pos, regExp.matchedLength());
+ pos += regExp.matchedLength();
+ }
- return atoms;
+ return atoms;
}
int FormTwinning::challenge(const QStringList &atoms1, const QStringList &atoms2) const
{
- int score = 0;
- QStringList tmpAtoms2 = atoms2;
- QList<QPair<int,int> > remainEpNumbers;
-
- // Simple string correspondances
- foreach (const QString &atom, atoms1)
- {
- int index = tmpAtoms2.indexOf(QRegExp(atom, Qt::CaseInsensitive, QRegExp::FixedString));
- if (index >= 0)
- {
- score++;
- tmpAtoms2.removeAt(index);
- } else
- {
- int season = -1;
- int episode = -1;
- if (isEpisodeNumberString(atom, season, episode))
- remainEpNumbers << QPair<int,int>(season, episode);
- }
- }
-
- foreach (const QString &atom, tmpAtoms2)
- {
- int season = -1;
- int episode = -1;
- if (isEpisodeNumberString(atom, season, episode))
- {
- int index = remainEpNumbers.indexOf(QPair<int,int>(season, episode));
- if (index >= 0)
- {
- score += 10;
- remainEpNumbers.removeAt(index);
- }
- }
- }
-
- return score;
+ int score = 0;
+ QStringList tmpAtoms2 = atoms2;
+ QList<QPair<int,int> > remainEpNumbers;
+
+ // Simple string correspondances
+ foreach (const QString &atom, atoms1)
+ {
+ int index = tmpAtoms2.indexOf(QRegExp(atom, Qt::CaseInsensitive, QRegExp::FixedString));
+ if (index >= 0)
+ {
+ score++;
+ tmpAtoms2.removeAt(index);
+ } else
+ {
+ int season = -1;
+ int episode = -1;
+ if (isEpisodeNumberString(atom, season, episode))
+ remainEpNumbers << QPair<int,int>(season, episode);
+ }
+ }
+
+ foreach (const QString &atom, tmpAtoms2)
+ {
+ int season = -1;
+ int episode = -1;
+ if (isEpisodeNumberString(atom, season, episode))
+ {
+ int index = remainEpNumbers.indexOf(QPair<int,int>(season, episode));
+ if (index >= 0)
+ {
+ score += 10;
+ remainEpNumbers.removeAt(index);
+ }
+ }
+ }
+
+ return score;
}
bool FormTwinning::isEpisodeNumberString(const QString &text, int &season, int &episode) const
{
- QRegExp epNumRegExp1("S(\\d+)E(\\d+)", Qt::CaseInsensitive);
- QRegExp epNumRegExp2("(\\d+)x(\\d+)", Qt::CaseInsensitive);
- QRegExp epNumRegExp3("(\\d)(\\d{2})", Qt::CaseInsensitive);
-
- if (epNumRegExp1.exactMatch(text))
- {
- season = epNumRegExp1.cap(1).toInt();
- episode = epNumRegExp1.cap(2).toInt();
- } else if (epNumRegExp2.exactMatch(text))
- {
- season = epNumRegExp2.cap(1).toInt();
- episode = epNumRegExp2.cap(2).toInt();
- } else if (epNumRegExp3.exactMatch(text))
- {
- season = epNumRegExp3.cap(1).toInt();
- episode = epNumRegExp3.cap(2).toInt();
- } else
- return false;
- return true;
+ QRegExp epNumRegExp1("S(\\d+)E(\\d+)", Qt::CaseInsensitive);
+ QRegExp epNumRegExp2("(\\d+)x(\\d+)", Qt::CaseInsensitive);
+ QRegExp epNumRegExp3("(\\d)(\\d{2})", Qt::CaseInsensitive);
+
+ if (epNumRegExp1.exactMatch(text))
+ {
+ season = epNumRegExp1.cap(1).toInt();
+ episode = epNumRegExp1.cap(2).toInt();
+ } else if (epNumRegExp2.exactMatch(text))
+ {
+ season = epNumRegExp2.cap(1).toInt();
+ episode = epNumRegExp2.cap(2).toInt();
+ } else if (epNumRegExp3.exactMatch(text))
+ {
+ season = epNumRegExp3.cap(1).toInt();
+ episode = epNumRegExp3.cap(2).toInt();
+ } else
+ return false;
+ return true;
}
void FormTwinning::on_pushButtonProcess_clicked()
{
- foreach (int leftRow, _twinning.keys())
- {
- int rightRow = _twinning[leftRow][0];
-
- QFileInfo leftFileInfo = _leftModel->fileInfo(_leftModel->index(leftRow, 0, treeViewLeft->rootIndex()));
- QFileInfo rightFileInfo = _rightModel->fileInfo(_rightModel->index(rightRow, 0, treeViewRight->rootIndex()));
-
- if (leftFileInfo.completeBaseName() != rightFileInfo.completeBaseName())
- {
- QString oldName = rightFileInfo.absoluteFilePath();
- QString newName = QDir(rightFileInfo.absolutePath()).filePath(leftFileInfo.completeBaseName() + '.' +
- rightFileInfo.suffix());
- QFile::rename(oldName, newName);
- }
- }
- _rightModel->refresh();
- redoTwinning();
+ foreach (int leftRow, _twinning.keys())
+ {
+ int rightRow = _twinning[leftRow][0];
+
+ QFileInfo leftFileInfo = _leftModel->fileInfo(_leftModel->index(leftRow, 0, treeViewLeft->rootIndex()));
+ QFileInfo rightFileInfo = _rightModel->fileInfo(_rightModel->index(rightRow, 0, treeViewRight->rootIndex()));
+
+ if (leftFileInfo.completeBaseName() != rightFileInfo.completeBaseName())
+ {
+ QString oldName = rightFileInfo.absoluteFilePath();
+ QString newName = QDir(rightFileInfo.absolutePath()).filePath(leftFileInfo.completeBaseName() + '.' +
+ rightFileInfo.suffix());
+ QFile::rename(oldName, newName);
+ }
+ }
+ _rightModel->refresh();
+ redoTwinning();
}
diff --git a/renamah/form_twinning.h b/renamah/form_twinning.h
index b4abb9a..de0fba9 100644
--- a/renamah/form_twinning.h
+++ b/renamah/form_twinning.h
@@ -1,81 +1,81 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FORM_TWINNING_H
#define FORM_TWINNING_H
#include <QDirModel>
#include <QString>
#include <QRegExp>
#include "simple_dir_model.h"
#include "ui_form_twinning.h"
class FormTwinning : public QWidget, private Ui::FormTwinning
{
- Q_OBJECT
+ Q_OBJECT
public:
- FormTwinning(QWidget *parent = 0);
+ FormTwinning(QWidget *parent = 0);
protected:
- bool eventFilter(QObject *watched, QEvent *event);
+ bool eventFilter(QObject *watched, QEvent *event);
private:
- bool _chainedDir;
- QString _leftPath;
- QString _rightPath;
- SimpleDirModel *_leftModel;
- SimpleDirModel *_rightModel;
- QMap<int, QList<int> > _twinning;
+ bool _chainedDir;
+ QString _leftPath;
+ QString _rightPath;
+ SimpleDirModel *_leftModel;
+ SimpleDirModel *_rightModel;
+ QMap<int, QList<int> > _twinning;
- void init();
- void refreshChainModeButton();
- void validateLeftDir(bool subcall = false);
- void validateRightDir(bool subcall = false);
- void validateLeftExtension();
- void validateRightExtension();
- void redoTwinning();
- QStringList atomize(const QString &text) const;
- int challenge(const QStringList &atoms1, const QStringList &atoms2) const;
- bool isEpisodeNumberString(const QString &text, int &season, int &episode) const;
- QFileInfo leftFileInfo(int row) const;
- QFileInfo rightFileInfo(int row) const;
- bool isFree(int leftRow, int score) const;
+ void init();
+ void refreshChainModeButton();
+ void validateLeftDir(bool subcall = false);
+ void validateRightDir(bool subcall = false);
+ void validateLeftExtension();
+ void validateRightExtension();
+ void redoTwinning();
+ QStringList atomize(const QString &text) const;
+ int challenge(const QStringList &atoms1, const QStringList &atoms2) const;
+ bool isEpisodeNumberString(const QString &text, int &season, int &episode) const;
+ QFileInfo leftFileInfo(int row) const;
+ QFileInfo rightFileInfo(int row) const;
+ bool isFree(int leftRow, int score) const;
private slots:
- void on_pushButtonChainMode_clicked();
- void on_toolButtonLeftDir_clicked();
- void on_toolButtonRightDir_clicked();
- void on_comboBoxLeftExtension_currentIndexChanged(const QString &text);
- void on_comboBoxRightExtension_currentIndexChanged(const QString &text);
- void leftTreeVerticalScrollBarValueChanged(int value);
- void rightTreeVerticalScrollBarValueChanged(int value);
- void leftModelReset();
- void leftRowsInserted(const QModelIndex &parent, int start, int end);
- void leftRowsRemoved(const QModelIndex &parent, int start, int end);
- void rightModelReset();
- void rightRowsInserted(const QModelIndex &parent, int start, int end);
- void rightRowsRemoved(const QModelIndex &parent, int start, int end);
- void currentLeftRowChanged(const QModelIndex ¤t, const QModelIndex &previous);
- void currentRightRowChanged(const QModelIndex ¤t, const QModelIndex &previous);
- void on_pushButtonProcess_clicked();
+ void on_pushButtonChainMode_clicked();
+ void on_toolButtonLeftDir_clicked();
+ void on_toolButtonRightDir_clicked();
+ void on_comboBoxLeftExtension_currentIndexChanged(const QString &text);
+ void on_comboBoxRightExtension_currentIndexChanged(const QString &text);
+ void leftTreeVerticalScrollBarValueChanged(int value);
+ void rightTreeVerticalScrollBarValueChanged(int value);
+ void leftModelReset();
+ void leftRowsInserted(const QModelIndex &parent, int start, int end);
+ void leftRowsRemoved(const QModelIndex &parent, int start, int end);
+ void rightModelReset();
+ void rightRowsInserted(const QModelIndex &parent, int start, int end);
+ void rightRowsRemoved(const QModelIndex &parent, int start, int end);
+ void currentLeftRowChanged(const QModelIndex ¤t, const QModelIndex &previous);
+ void currentRightRowChanged(const QModelIndex ¤t, const QModelIndex &previous);
+ void on_pushButtonProcess_clicked();
};
#endif
diff --git a/renamah/led_widget.cpp b/renamah/led_widget.cpp
index 6286cdc..d1f3dcf 100644
--- a/renamah/led_widget.cpp
+++ b/renamah/led_widget.cpp
@@ -1,28 +1,28 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QPainter>
#include "led_widget.h"
void LedWidget::paintEvent(QPaintEvent *event)
{
- QPainter painter(this);
- QRect r(0, 0, 16, 16);
- painter.drawPixmap(r, QPixmap(":/images/checked.png"));
+ QPainter painter(this);
+ QRect r(0, 0, 16, 16);
+ painter.drawPixmap(r, QPixmap(":/images/checked.png"));
}
diff --git a/renamah/led_widget.h b/renamah/led_widget.h
index eb4c2a0..f65f42d 100644
--- a/renamah/led_widget.h
+++ b/renamah/led_widget.h
@@ -1,35 +1,35 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef LED_WIDGET_H
#define LED_WIDGET_H
#include <QWidget>
class LedWidget : public QWidget
{
- Q_OBJECT
+ Q_OBJECT
public:
- LedWidget(QWidget *parent = 0) : QWidget(parent) {}
+ LedWidget(QWidget *parent = 0) : QWidget(parent) {}
protected:
- void paintEvent(QPaintEvent *event);
+ void paintEvent(QPaintEvent *event);
};
#endif
diff --git a/renamah/main.cpp b/renamah/main.cpp
index 2edddfc..b14ea84 100644
--- a/renamah/main.cpp
+++ b/renamah/main.cpp
@@ -1,35 +1,35 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QApplication>
#include "main_window.h"
int main(int argc, char *argv[])
{
- QApplication app(argc, argv);
+ QApplication app(argc, argv);
- app.setOrganizationName("GuidSofts");
- app.setApplicationName("Renamah");
- app.setApplicationVersion("0.01a");
+ app.setOrganizationName("GuidSofts");
+ app.setApplicationName("Renamah");
+ app.setApplicationVersion("0.01a");
- MainWindow mainWindow;
- mainWindow.show();
+ MainWindow mainWindow;
+ mainWindow.show();
- return app.exec();
+ return app.exec();
}
diff --git a/renamah/main_window.cpp b/renamah/main_window.cpp
index 38b190a..f21cd59 100644
--- a/renamah/main_window.cpp
+++ b/renamah/main_window.cpp
@@ -1,170 +1,170 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QTranslator>
#include <QSettings>
#include <QLibraryInfo>
#include <QFileDialog>
#include <QShortcut>
#include "plugin_manager.h"
#include "filter_model.h"
#include "processor.h"
#include "profile.h"
#include "undo_manager.h"
#include "paths.h"
#include "main_window.h"
MainWindow::MainWindow(QWidget *parent)
: actionGroupLanguages(0),
QMainWindow(parent) {
- setupUi(this);
+ setupUi(this);
- PluginManager::instance().load();
+ PluginManager::instance().load();
- tabWidgetMain->setCurrentWidget(tabSimple);
+ tabWidgetMain->setCurrentWidget(tabSimple);
- connect(&Processor::instance(), SIGNAL(started()), this, SLOT(processorStarted()));
+ connect(&Processor::instance(), SIGNAL(started()), this, SLOT(processorStarted()));
- widgetSimple->initAfterPluginLoaded();
+ widgetSimple->initAfterPluginLoaded();
- actionLanguage->setMenu(&menuLanguages);
+ actionLanguage->setMenu(&menuLanguages);
- QSettings settings;
- QString currentLanguage = settings.value("general/language", "").toString();
- if (currentLanguage != "")
- installLanguage(currentLanguage);
+ QSettings settings;
+ QString currentLanguage = settings.value("general/language", "").toString();
+ if (currentLanguage != "")
+ installLanguage(currentLanguage);
- refreshLanguageActions();
+ refreshLanguageActions();
- connect(&signalMapperLanguages, SIGNAL(mapped(const QString &)),
- this, SLOT(languageRequested(const QString &)));
+ connect(&signalMapperLanguages, SIGNAL(mapped(const QString &)),
+ this, SLOT(languageRequested(const QString &)));
}
void MainWindow::refreshLanguageActions() {
- if (actionGroupLanguages)
- delete actionGroupLanguages;
- actionGroupLanguages = new QActionGroup(this);
- menuLanguages.clear();
-
- QAction *actionToCheck = 0;
- QSettings settings;
- QString currentLanguage = settings.value("general/language", "").toString();
-
- // Get languages list
- foreach (const QFileInfo &fileInfo, QDir(Paths::sharePath()).entryInfoList(QStringList() << "*.qm",
- QDir::Files)) {
- QString baseName = fileInfo.baseName();
- int p = baseName.indexOf("_");
- if (p > 0) {
- QString fileLanguage = baseName.mid(p + 1, baseName.length() - p - 1);
- QLocale locale(fileLanguage);
- QString language = QLocale::languageToString(locale.language());
- QString country = QLocale::countryToString(locale.country());
- QAction *action = menuLanguages.addAction(QString("%1 (%2)").arg(language).arg(country));
- if (fileLanguage == currentLanguage)
- actionToCheck = action;
- signalMapperLanguages.setMapping(action, fileLanguage);
- connect(action, SIGNAL(triggered()), &signalMapperLanguages, SLOT(map()));
- action->setCheckable(true);
- actionGroupLanguages->addAction(action);
- }
- }
-
- if (actionToCheck)
- actionToCheck->setChecked(true);
+ if (actionGroupLanguages)
+ delete actionGroupLanguages;
+ actionGroupLanguages = new QActionGroup(this);
+ menuLanguages.clear();
+
+ QAction *actionToCheck = 0;
+ QSettings settings;
+ QString currentLanguage = settings.value("general/language", "").toString();
+
+ // Get languages list
+ foreach (const QFileInfo &fileInfo, QDir(Paths::sharePath()).entryInfoList(QStringList() << "*.qm",
+ QDir::Files)) {
+ QString baseName = fileInfo.baseName();
+ int p = baseName.indexOf("_");
+ if (p > 0) {
+ QString fileLanguage = baseName.mid(p + 1, baseName.length() - p - 1);
+ QLocale locale(fileLanguage);
+ QString language = QLocale::languageToString(locale.language());
+ QString country = QLocale::countryToString(locale.country());
+ QAction *action = menuLanguages.addAction(QString("%1 (%2)").arg(language).arg(country));
+ if (fileLanguage == currentLanguage)
+ actionToCheck = action;
+ signalMapperLanguages.setMapping(action, fileLanguage);
+ connect(action, SIGNAL(triggered()), &signalMapperLanguages, SLOT(map()));
+ action->setCheckable(true);
+ actionGroupLanguages->addAction(action);
+ }
+ }
+
+ if (actionToCheck)
+ actionToCheck->setChecked(true);
}
void MainWindow::processorStarted() {
- tabWidgetMain->setCurrentWidget(tabLastOperations);
+ tabWidgetMain->setCurrentWidget(tabLastOperations);
}
void MainWindow::languageRequested(const QString &language) {
- installLanguage(language);
+ installLanguage(language);
- QSettings settings;
- settings.setValue("general/language", language);
+ QSettings settings;
+ settings.setValue("general/language", language);
}
void MainWindow::changeEvent(QEvent *event) {
- if (event->type() == QEvent::LanguageChange) {
- retranslateUi(this);
- } else
- QWidget::changeEvent(event);
+ if (event->type() == QEvent::LanguageChange) {
+ retranslateUi(this);
+ } else
+ QWidget::changeEvent(event);
}
void MainWindow::installLanguage(const QString &language) {
- // Remove all existing translators
- foreach (QTranslator *translator, translators)
- qApp->removeTranslator(translator);
- translators.clear();
-
- // Install the Qt translator
- QTranslator *qtTranslator = new QTranslator;
- qtTranslator->load("qt_" + language,
- QLibraryInfo::location(QLibraryInfo::TranslationsPath));
+ // Remove all existing translators
+ foreach (QTranslator *translator, translators)
+ qApp->removeTranslator(translator);
+ translators.clear();
+
+ // Install the Qt translator
+ QTranslator *qtTranslator = new QTranslator;
+ qtTranslator->load("qt_" + language,
+ QLibraryInfo::location(QLibraryInfo::TranslationsPath));
qApp->installTranslator(qtTranslator);
- // Install the main app translator
- QTranslator *translator = new QTranslator;
- translator->load("renamah_" + language,
- Paths::sharePath());
+ // Install the main app translator
+ QTranslator *translator = new QTranslator;
+ translator->load("renamah_" + language,
+ Paths::sharePath());
qApp->installTranslator(translator);
- translators << translator;
-
- // Install all plugins translators
- foreach (const QString &fileName, PluginManager::instance().pluginFileNames()) {
- QString relativeFileName = QFileInfo(fileName).completeBaseName() + "_" + language + ".qm";
- QString qmFileName = QDir(QDir(Paths::sharePath()).filePath("plugins")).filePath(relativeFileName);
-
- QTranslator *translator = new QTranslator;
- translator->load(qmFileName,
- QCoreApplication::applicationDirPath());
- qApp->installTranslator(translator);
- translators << translator;
- }
+ translators << translator;
+
+ // Install all plugins translators
+ foreach (const QString &fileName, PluginManager::instance().pluginFileNames()) {
+ QString relativeFileName = QFileInfo(fileName).completeBaseName() + "_" + language + ".qm";
+ QString qmFileName = QDir(QDir(Paths::sharePath()).filePath("plugins")).filePath(relativeFileName);
+
+ QTranslator *translator = new QTranslator;
+ translator->load(qmFileName,
+ QCoreApplication::applicationDirPath());
+ qApp->installTranslator(translator);
+ translators << translator;
+ }
}
void MainWindow::on_actionLoadProfile_triggered() {
- QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a profile to load"),
- QDir::home().absolutePath());
- if (fileName == "")
- return;
+ QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a profile to load"),
+ QDir::home().absolutePath());
+ if (fileName == "")
+ return;
- if (!Profile::load(fileName))
- return;
+ if (!Profile::load(fileName))
+ return;
- widgetSimple->newProfile();
+ widgetSimple->newProfile();
}
void MainWindow::on_actionSaveProfile_triggered() {
- QString fileName = QFileDialog::getSaveFileName(this, tr("Choose a profile filename to save in"),
- QDir::home().absolutePath());
- if (fileName == "")
- return;
+ QString fileName = QFileDialog::getSaveFileName(this, tr("Choose a profile filename to save in"),
+ QDir::home().absolutePath());
+ if (fileName == "")
+ return;
- Profile::save(fileName);
+ Profile::save(fileName);
}
void MainWindow::on_actionUndo_triggered() {
- UndoManager::instance().undo();
+ UndoManager::instance().undo();
}
void MainWindow::on_actionRedo_triggered() {
- UndoManager::instance().redo();
+ UndoManager::instance().redo();
}
diff --git a/renamah/main_window.h b/renamah/main_window.h
index 0247847..14ce284 100644
--- a/renamah/main_window.h
+++ b/renamah/main_window.h
@@ -1,53 +1,53 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QMenu>
#include <QSignalMapper>
#include <QTranslator>
#include <QActionGroup>
#include "ui_main_window.h"
class MainWindow : public QMainWindow, private Ui::MainWindow
{
- Q_OBJECT
+ Q_OBJECT
public:
- MainWindow(QWidget *parent = 0);
+ MainWindow(QWidget *parent = 0);
protected:
- void changeEvent(QEvent *event);
+ void changeEvent(QEvent *event);
private:
- QMenu menuLanguages;
- QActionGroup *actionGroupLanguages;
- QSignalMapper signalMapperLanguages;
- QList<QTranslator*> translators;
+ QMenu menuLanguages;
+ QActionGroup *actionGroupLanguages;
+ QSignalMapper signalMapperLanguages;
+ QList<QTranslator*> translators;
- void refreshLanguageActions();
+ void refreshLanguageActions();
- void installLanguage(const QString &language);
+ void installLanguage(const QString &language);
private slots:
- void processorStarted();
- void languageRequested(const QString &language);
- void on_actionLoadProfile_triggered();
- void on_actionSaveProfile_triggered();
- void on_actionUndo_triggered();
- void on_actionRedo_triggered();
+ void processorStarted();
+ void languageRequested(const QString &language);
+ void on_actionLoadProfile_triggered();
+ void on_actionSaveProfile_triggered();
+ void on_actionUndo_triggered();
+ void on_actionRedo_triggered();
};
diff --git a/renamah/modifier_delegate.cpp b/renamah/modifier_delegate.cpp
index 72c31f7..5e15ec3 100644
--- a/renamah/modifier_delegate.cpp
+++ b/renamah/modifier_delegate.cpp
@@ -1,77 +1,77 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QPainter>
#include "modifier_model.h"
#include "led_widget.h"
#include "modifier_delegate.h"
ModifierDelegate::ModifierDelegate(QObject *parent)
- : QStyledItemDelegate(parent)
+ : QStyledItemDelegate(parent)
{
}
void ModifierDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
- QStyledItemDelegate::paint(painter, option, index);
+ QStyledItemDelegate::paint(painter, option, index);
- const ModifierModel *model = qobject_cast<const ModifierModel*>(index.model());
- Q_ASSERT_X(model, "ModifierDelegate()", "index.model() is not a ModifierModel!");
- core::Modifier *modifier = model->modifier(index);
- switch (index.column())
+ const ModifierModel *model = qobject_cast<const ModifierModel*>(index.model());
+ Q_ASSERT_X(model, "ModifierDelegate()", "index.model() is not a ModifierModel!");
+ core::Modifier *modifier = model->modifier(index);
+ switch (index.column())
{
- case ModifierModel::colMode:
+ case ModifierModel::colMode:
{
- painter->save();
+ painter->save();
- QRect centerRect = option.rect;
- centerRect.setWidth(qMin(centerRect.width(), 32));
- centerRect.setHeight(qMin(centerRect.height(), 16));
- int dx = 0;
- if (centerRect.width() == 32 && option.rect.width() > 32)
- dx = option.rect.width() / 2 - 16;
- int dy = 0;
- if (centerRect.height() == 32 && option.rect.height() > 32)
- dy = option.rect.height() / 2 - 16;
- centerRect.translate(dx, dy);
- QRect leftRect = centerRect;
- leftRect.setWidth(16);
- QRect rightRect = centerRect;
- rightRect.setWidth(16);
- rightRect.translate(16, 0);
- if (model->modifierState(modifier))
- {
- if (!model->exclusiveModifier() ||
- model->exclusiveModifier() == modifier)
- painter->drawPixmap(leftRect, QPixmap(":/images/filter-on.png"));
- else
- painter->drawPixmap(leftRect, QPixmap(":/images/filter-on-single.png"));
- } else
- painter->drawPixmap(leftRect, QPixmap(":/images/filter-off.png"));
- if (model->exclusiveModifier() == modifier)
- painter->drawPixmap(rightRect, QPixmap(":/images/filter-single-on.png"));
- else
- painter->drawPixmap(rightRect, QPixmap(":/images/filter-single-off.png"));
+ QRect centerRect = option.rect;
+ centerRect.setWidth(qMin(centerRect.width(), 32));
+ centerRect.setHeight(qMin(centerRect.height(), 16));
+ int dx = 0;
+ if (centerRect.width() == 32 && option.rect.width() > 32)
+ dx = option.rect.width() / 2 - 16;
+ int dy = 0;
+ if (centerRect.height() == 32 && option.rect.height() > 32)
+ dy = option.rect.height() / 2 - 16;
+ centerRect.translate(dx, dy);
+ QRect leftRect = centerRect;
+ leftRect.setWidth(16);
+ QRect rightRect = centerRect;
+ rightRect.setWidth(16);
+ rightRect.translate(16, 0);
+ if (model->modifierState(modifier))
+ {
+ if (!model->exclusiveModifier() ||
+ model->exclusiveModifier() == modifier)
+ painter->drawPixmap(leftRect, QPixmap(":/images/filter-on.png"));
+ else
+ painter->drawPixmap(leftRect, QPixmap(":/images/filter-on-single.png"));
+ } else
+ painter->drawPixmap(leftRect, QPixmap(":/images/filter-off.png"));
+ if (model->exclusiveModifier() == modifier)
+ painter->drawPixmap(rightRect, QPixmap(":/images/filter-single-on.png"));
+ else
+ painter->drawPixmap(rightRect, QPixmap(":/images/filter-single-off.png"));
- painter->restore();
- return;
- }
- default:;
+ painter->restore();
+ return;
}
+ default:;
+ }
}
diff --git a/renamah/modifier_delegate.h b/renamah/modifier_delegate.h
index b7526ff..5d853e1 100644
--- a/renamah/modifier_delegate.h
+++ b/renamah/modifier_delegate.h
@@ -1,38 +1,38 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef MODIFIER_DELEGATE_H
#define MODIFIER_DELEGATE_H
#include <QStyledItemDelegate>
#include <QTreeView>
class ModifierDelegate : public QStyledItemDelegate
{
- Q_OBJECT
+ Q_OBJECT
public:
- ModifierDelegate(QObject *parent = 0);
+ ModifierDelegate(QObject *parent = 0);
- void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
+ void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
private:
- QRect getStateRect() const;
+ QRect getStateRect() const;
};
#endif
diff --git a/renamah/modifier_manager.cpp b/renamah/modifier_manager.cpp
index cb43586..af03f91 100644
--- a/renamah/modifier_manager.cpp
+++ b/renamah/modifier_manager.cpp
@@ -1,32 +1,32 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 "modifier_manager.h"
void ModifierManager::addFactory(core::ModifierFactory *factory)
{
- _factories << factory;
+ _factories << factory;
}
core::ModifierFactory *ModifierManager::factoryByName(const QString &name) const
{
- foreach (core::ModifierFactory *factory, _factories)
- if (!factory->info().name().compare(name, Qt::CaseInsensitive))
- return factory;
- return 0;
+ foreach (core::ModifierFactory *factory, _factories)
+ if (!factory->info().name().compare(name, Qt::CaseInsensitive))
+ return factory;
+ return 0;
}
diff --git a/renamah/modifier_manager.h b/renamah/modifier_manager.h
index 8a00bd7..650a1e1 100644
--- a/renamah/modifier_manager.h
+++ b/renamah/modifier_manager.h
@@ -1,40 +1,40 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef MODIFIER_MANAGER_H
#define MODIFIER_MANAGER_H
#include <interfaces/modifier_factory.h>
class ModifierManager
{
public:
- void addFactory(core::ModifierFactory *factory);
+ void addFactory(core::ModifierFactory *factory);
- core::ModifierFactory *factoryByName(const QString &name) const;
+ core::ModifierFactory *factoryByName(const QString &name) const;
- const QList<core::ModifierFactory*> &factories() const { return _factories; }
+ const QList<core::ModifierFactory*> &factories() const { return _factories; }
- /*! Returns the type name of the modifier created by the factory */
- virtual QString modifierTypeName() = 0;
+ /*! Returns the type name of the modifier created by the factory */
+ virtual QString modifierTypeName() = 0;
private:
- QList<core::ModifierFactory*> _factories;
+ QList<core::ModifierFactory*> _factories;
};
#endif
diff --git a/renamah/modifier_model.cpp b/renamah/modifier_model.cpp
index 856fcc3..beeb682 100644
--- a/renamah/modifier_model.cpp
+++ b/renamah/modifier_model.cpp
@@ -1,383 +1,383 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QMimeData>
#include <interfaces/modifier_factory.h>
#include "undo_manager.h"
#include "modifier_model.h"
ModifierModel::ModifierModel(ModifierManager *manager)
- : _manager(manager),
- _exclusiveModifier(0),
- _disableUndo(false)
+ : _manager(manager),
+ _exclusiveModifier(0),
+ _disableUndo(false)
{
}
int ModifierModel::rowCount(const QModelIndex &parent) const
{
- return _modifiers.count();
+ return _modifiers.count();
}
int ModifierModel::columnCount(const QModelIndex &parent) const
{
- return columnNumber;
+ return columnNumber;
}
QVariant ModifierModel::data(const QModelIndex &index, int role) const
{
- if (!index.isValid() || index.row() < 0 || index.row() >= _modifiers.count())
- return QVariant();
-
- const core::Modifier *modifier = _modifiers[index.row()];
- switch (role)
- {
- case Qt::DisplayRole:
- switch (index.column())
- {
- case colIndex: return index.row() + 1;
- case colMode: return "";
- case colCaption: return modifier->factory()->info().caption() + " [" + modifier->resume() + "]";
- default:;
- }
+ if (!index.isValid() || index.row() < 0 || index.row() >= _modifiers.count())
+ return QVariant();
+
+ const core::Modifier *modifier = _modifiers[index.row()];
+ switch (role)
+ {
+ case Qt::DisplayRole:
+ switch (index.column())
+ {
+ case colIndex: return index.row() + 1;
+ case colMode: return "";
+ case colCaption: return modifier->factory()->info().caption() + " [" + modifier->resume() + "]";
+ default:;
+ }
case Qt::ForegroundRole:
- if (_exclusiveModifier && _exclusiveModifier != modifier)
- return Qt::gray;
- break;
+ if (_exclusiveModifier && _exclusiveModifier != modifier)
+ return Qt::gray;
+ break;
default:;
}
- return QVariant();
+ return QVariant();
}
QVariant ModifierModel::headerData(int section, Qt::Orientation orientation, int role) const
{
- switch (role)
- {
- case Qt::DisplayRole:
- switch (section)
- {
- case colIndex: return tr("#");
- case colMode: return tr("Mode");
- case colCaption: return tr("Action");
- default:;
- }
- break;
+ switch (role)
+ {
+ case Qt::DisplayRole:
+ switch (section)
+ {
+ case colIndex: return tr("#");
+ case colMode: return tr("Mode");
+ case colCaption: return tr("Action");
+ default:;
+ }
+ break;
default:;
}
- return QVariant();
+ return QVariant();
}
void ModifierModel::init(core::Modifier *modifier) {
- connect(modifier, SIGNAL(settingsChanging()), this, SLOT(modifierChanging()));
- connect(modifier, SIGNAL(settingsChanged()), this, SLOT(modifierChanged()));
- connect(modifier, SIGNAL(settingsChanged()), this, SIGNAL(modifiersChanged()));
+ connect(modifier, SIGNAL(settingsChanging()), this, SLOT(modifierChanging()));
+ connect(modifier, SIGNAL(settingsChanged()), this, SLOT(modifierChanged()));
+ connect(modifier, SIGNAL(settingsChanged()), this, SIGNAL(modifiersChanged()));
}
void ModifierModel::addModifier(core::Modifier *modifier)
{
- init(modifier);
+ init(modifier);
- beginInsertRows(QModelIndex(), _modifiers.count(), _modifiers.count());
- _modifiers << modifier;
- _modifierStates[modifier] = true;
- endInsertRows();
+ beginInsertRows(QModelIndex(), _modifiers.count(), _modifiers.count());
+ _modifiers << modifier;
+ _modifierStates[modifier] = true;
+ endInsertRows();
- if (!_disableUndo) {
- CreateModifierCommand *command = new CreateModifierCommand(this, _manager, modifier->factory()->info().name());
- UndoManager::instance().push(command);
- command->activate();
- }
+ if (!_disableUndo) {
+ CreateModifierCommand *command = new CreateModifierCommand(this, _manager, modifier->factory()->info().name());
+ UndoManager::instance().push(command);
+ command->activate();
+ }
- emit modifiersChanged();
+ emit modifiersChanged();
}
void ModifierModel::insertModifier(int index, core::Modifier *modifier) {
- init(modifier);
+ init(modifier);
- beginInsertRows(QModelIndex(), index, index);
- _modifiers.insert(index, modifier);
- _modifierStates[modifier] = true;
- endInsertRows();
+ beginInsertRows(QModelIndex(), index, index);
+ _modifiers.insert(index, modifier);
+ _modifierStates[modifier] = true;
+ endInsertRows();
- // TODO : integrate into the undo framework!!!
+ // TODO : integrate into the undo framework!!!
- emit modifiersChanged();
+ emit modifiersChanged();
}
void ModifierModel::removeModifier(const QModelIndex &index)
{
- if (!index.isValid())
- return;
+ if (!index.isValid())
+ return;
- removeRows(index.row(), 1);
+ removeRows(index.row(), 1);
}
bool ModifierModel::modifierState(core::Modifier *modifier) const
{
- if (_modifierStates.find(modifier) == _modifierStates.end())
- return false;
- else
- return _modifierStates[modifier];
+ if (_modifierStates.find(modifier) == _modifierStates.end())
+ return false;
+ else
+ return _modifierStates[modifier];
}
void ModifierModel::setModifierState(core::Modifier *modifier, bool state)
{
- int modifierRow = _modifiers.indexOf(modifier);
- if (modifierRow < 0)
- return;
-
- if (_modifierStates[modifier] != state)
- {
- _modifierStates[modifier] = state;
- emit dataChanged(index(modifierRow, 0), index(modifierRow, columnNumber - 1));
- emit modifiersChanged();
- }
+ int modifierRow = _modifiers.indexOf(modifier);
+ if (modifierRow < 0)
+ return;
+
+ if (_modifierStates[modifier] != state)
+ {
+ _modifierStates[modifier] = state;
+ emit dataChanged(index(modifierRow, 0), index(modifierRow, columnNumber - 1));
+ emit modifiersChanged();
+ }
}
void ModifierModel::toggleModifierState(core::Modifier *modifier)
{
- if (_modifierStates.find(modifier) == _modifierStates.end())
- return;
+ if (_modifierStates.find(modifier) == _modifierStates.end())
+ return;
- setModifierState(modifier, !_modifierStates[modifier]);
+ setModifierState(modifier, !_modifierStates[modifier]);
}
void ModifierModel::setExclusiveModifier(core::Modifier *modifier)
{
- if (_exclusiveModifier == modifier)
- return;
+ if (_exclusiveModifier == modifier)
+ return;
- _exclusiveModifier = modifier;
- if (modifier)
- _modifierStates[modifier] = true;
+ _exclusiveModifier = modifier;
+ if (modifier)
+ _modifierStates[modifier] = true;
- // Refresh all
- emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
- emit modifiersChanged();
+ // Refresh all
+ emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
+ emit modifiersChanged();
}
/*QString ModifierModel::apply(const QString &str) const
{
if (_exclusiveModifier)
return _exclusiveModifier->apply(str);
QString filtered = str;
foreach (core::Filter *filter, _modifiers)
if (_modifierstates[filter])
filtered = filter->apply(filtered);
return filtered;
}*/
core::Modifier *ModifierModel::modifier(const QModelIndex &index) const
{
- if (!index.isValid())
- return 0;
+ if (!index.isValid())
+ return 0;
- return _modifiers[index.row()];
+ return _modifiers[index.row()];
}
Qt::ItemFlags ModifierModel::flags(const QModelIndex &index) const
{
- Qt::ItemFlags flags = QAbstractListModel::flags(index);
+ Qt::ItemFlags flags = QAbstractListModel::flags(index);
- if (index.isValid())
- return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
- else
- return Qt::ItemIsDropEnabled | flags;
+ if (index.isValid())
+ return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
+ else
+ return Qt::ItemIsDropEnabled | flags;
}
void ModifierModel::toggleExclusiveState(core::Modifier *modifier)
{
- if (_exclusiveModifier == modifier)
- _exclusiveModifier = 0;
- else
- _exclusiveModifier = modifier;
+ if (_exclusiveModifier == modifier)
+ _exclusiveModifier = 0;
+ else
+ _exclusiveModifier = modifier;
- if (_exclusiveModifier)
- _modifierStates[_exclusiveModifier] = true;
+ if (_exclusiveModifier)
+ _modifierStates[_exclusiveModifier] = true;
- // Refresh all
- emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
- emit modifiersChanged();
+ // Refresh all
+ emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
+ emit modifiersChanged();
}
Qt::DropActions ModifierModel::supportedDropActions() const {
- return Qt::CopyAction;
+ return Qt::CopyAction;
}
bool ModifierModel::removeRows(int row, int count, const QModelIndex &parent) {
- core::Modifier *modifierToRemove = modifier(index(row, 0));
+ core::Modifier *modifierToRemove = modifier(index(row, 0));
- if (!_disableUndo) {
- RemoveModifierCommand *command = new RemoveModifierCommand(this, _manager, row, modifierToRemove->factory()->info().name(),
- modifierToRemove->serializeProperties());
- UndoManager::instance().push(command);
- command->activate();
- }
+ if (!_disableUndo) {
+ RemoveModifierCommand *command = new RemoveModifierCommand(this, _manager, row, modifierToRemove->factory()->info().name(),
+ modifierToRemove->serializeProperties());
+ UndoManager::instance().push(command);
+ command->activate();
+ }
- beginRemoveRows(QModelIndex(), row, row);
+ beginRemoveRows(QModelIndex(), row, row);
- _modifiers.removeAt(_modifiers.indexOf(modifierToRemove));
- _modifierStates.remove(modifierToRemove);
- if (_exclusiveModifier == modifierToRemove)
- _exclusiveModifier = 0;
- delete modifierToRemove;
+ _modifiers.removeAt(_modifiers.indexOf(modifierToRemove));
+ _modifierStates.remove(modifierToRemove);
+ if (_exclusiveModifier == modifierToRemove)
+ _exclusiveModifier = 0;
+ delete modifierToRemove;
- endRemoveRows();
+ endRemoveRows();
- emit modifiersChanged();
+ emit modifiersChanged();
- return true;
+ return true;
}
#define MIMETYPE QLatin1String("filter-rows")
QStringList ModifierModel::mimeTypes() const
{
- QStringList types;
- types << MIMETYPE;
- return types;
+ QStringList types;
+ types << MIMETYPE;
+ return types;
}
QMimeData *ModifierModel::mimeData(const QModelIndexList &indexes) const
{
- QMimeData *mimeData = new QMimeData;
- QByteArray encodedData;
+ QMimeData *mimeData = new QMimeData;
+ QByteArray encodedData;
- QDataStream stream(&encodedData, QIODevice::WriteOnly);
+ QDataStream stream(&encodedData, QIODevice::WriteOnly);
- foreach (QModelIndex index, indexes) {
- if (index.isValid()) {
- stream << index.row();
- }
- }
+ foreach (QModelIndex index, indexes) {
+ if (index.isValid()) {
+ stream << index.row();
+ }
+ }
- mimeData->setData(MIMETYPE, encodedData);
- return mimeData;
+ mimeData->setData(MIMETYPE, encodedData);
+ return mimeData;
}
bool ModifierModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
- if (action == Qt::IgnoreAction)
- return false;
-
- QByteArray inData = data->data(MIMETYPE);
- QDataStream stream(inData);
- int sourceRow;
- stream >> sourceRow;
-
- int destinationRow = rowCount();
-
- if (row != -1) {
- if (row >= rowCount()) {
- destinationRow = rowCount();
- } else {
- if (sourceRow < row)
- row--;
- destinationRow = row;
- }
- } else if (parent.isValid()) {
- destinationRow = parent.row();
- } else if (!parent.isValid()) {
- destinationRow = rowCount();
- }
-
- moveModifier(sourceRow, destinationRow);
-
- return false;
+ if (action == Qt::IgnoreAction)
+ return false;
+
+ QByteArray inData = data->data(MIMETYPE);
+ QDataStream stream(inData);
+ int sourceRow;
+ stream >> sourceRow;
+
+ int destinationRow = rowCount();
+
+ if (row != -1) {
+ if (row >= rowCount()) {
+ destinationRow = rowCount();
+ } else {
+ if (sourceRow < row)
+ row--;
+ destinationRow = row;
+ }
+ } else if (parent.isValid()) {
+ destinationRow = parent.row();
+ } else if (!parent.isValid()) {
+ destinationRow = rowCount();
+ }
+
+ moveModifier(sourceRow, destinationRow);
+
+ return false;
}
void ModifierModel::clear() {
- _exclusiveModifier = 0;
- qDeleteAll(_modifiers);
- _modifiers.clear();
- _modifierStates.clear();
- reset();
- emit modifiersChanged();
+ _exclusiveModifier = 0;
+ qDeleteAll(_modifiers);
+ _modifiers.clear();
+ _modifierStates.clear();
+ reset();
+ emit modifiersChanged();
}
void ModifierModel::modifierChanged() {
- if (_disableUndo)
- return;
+ if (_disableUndo)
+ return;
- core::Modifier *modifier = static_cast<core::Modifier*>(sender());
+ core::Modifier *modifier = static_cast<core::Modifier*>(sender());
- // Undo managing => compute the diff
- QMap<QString,QPair<QString,QVariant> > newProperties = modifier->serializeProperties();
- QMap<QString,QPair<QString,QVariant> > &oldProperties = _changingModifierOldProperties;
- QMap<QString,QPair<QString,QVariant> > undoProperties, redoProperties;
+ // Undo managing => compute the diff
+ QMap<QString,QPair<QString,QVariant> > newProperties = modifier->serializeProperties();
+ QMap<QString,QPair<QString,QVariant> > &oldProperties = _changingModifierOldProperties;
+ QMap<QString,QPair<QString,QVariant> > undoProperties, redoProperties;
- foreach (const QString &propName, newProperties.keys()) {
- QPair<QString,QVariant> &newPair = newProperties[propName];
- QPair<QString,QVariant> &oldPair = oldProperties[propName];
+ foreach (const QString &propName, newProperties.keys()) {
+ QPair<QString,QVariant> &newPair = newProperties[propName];
+ QPair<QString,QVariant> &oldPair = oldProperties[propName];
- if (newPair != oldPair) {
- undoProperties.insert(propName, oldPair);
- redoProperties.insert(propName, newPair);
- }
- }
+ if (newPair != oldPair) {
+ undoProperties.insert(propName, oldPair);
+ redoProperties.insert(propName, newPair);
+ }
+ }
- ModifyModifierCommand *command = new ModifyModifierCommand(this, _modifiers.indexOf(modifier), undoProperties, redoProperties);
- UndoManager::instance().push(command);
- command->activate();
+ ModifyModifierCommand *command = new ModifyModifierCommand(this, _modifiers.indexOf(modifier), undoProperties, redoProperties);
+ UndoManager::instance().push(command);
+ command->activate();
}
void ModifierModel::modifierChanging() {
- if (_disableUndo)
- return;
+ if (_disableUndo)
+ return;
- core::Modifier *modifier = static_cast<core::Modifier*>(sender());
+ core::Modifier *modifier = static_cast<core::Modifier*>(sender());
- _changingModifierOldProperties = modifier->serializeProperties();
+ _changingModifierOldProperties = modifier->serializeProperties();
}
void ModifierModel::beginUndoAction() {
- _disableUndo = true;
+ _disableUndo = true;
}
void ModifierModel::endUndoAction() {
- _disableUndo = false;
+ _disableUndo = false;
}
void ModifierModel::moveModifier(int sourceRow, int destinationRow) {
- Q_ASSERT_X(sourceRow >= 0 && sourceRow < rowCount(), "ModifierModel::moveModifier()", qPrintable(QString("<sourceRow> is out of bound: %d!").arg(sourceRow)));
+ Q_ASSERT_X(sourceRow >= 0 && sourceRow < rowCount(), "ModifierModel::moveModifier()", qPrintable(QString("<sourceRow> is out of bound: %d!").arg(sourceRow)));
- if (sourceRow == destinationRow) // Save destination => do nothing
- return;
+ if (sourceRow == destinationRow) // Save destination => do nothing
+ return;
- if (destinationRow >= rowCount() - 1 &&
- sourceRow == rowCount() - 1) // Already at the list queue => do nothing
- return;
+ if (destinationRow >= rowCount() - 1 &&
+ sourceRow == rowCount() - 1) // Already at the list queue => do nothing
+ return;
- beginRemoveRows(QModelIndex(), sourceRow, sourceRow);
- core::Modifier *modifier = _modifiers.takeAt(sourceRow);
- endRemoveRows();
- beginInsertRows(QModelIndex(), destinationRow, destinationRow);
- _modifiers.insert(destinationRow, modifier);
- endInsertRows();
+ beginRemoveRows(QModelIndex(), sourceRow, sourceRow);
+ core::Modifier *modifier = _modifiers.takeAt(sourceRow);
+ endRemoveRows();
+ beginInsertRows(QModelIndex(), destinationRow, destinationRow);
+ _modifiers.insert(destinationRow, modifier);
+ endInsertRows();
- emit modifiersChanged();
+ emit modifiersChanged();
- if (!_disableUndo) {
- MoveModifierCommand *command = new MoveModifierCommand(this, sourceRow, destinationRow);
- UndoManager::instance().push(command);
- command->activate();
- }
+ if (!_disableUndo) {
+ MoveModifierCommand *command = new MoveModifierCommand(this, sourceRow, destinationRow);
+ UndoManager::instance().push(command);
+ command->activate();
+ }
}
diff --git a/renamah/modifier_model.h b/renamah/modifier_model.h
index 2cffa58..784124d 100644
--- a/renamah/modifier_model.h
+++ b/renamah/modifier_model.h
@@ -1,115 +1,115 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef MODIFIER_MODEL_H
#define MODIFIER_MODEL_H
#include <QAbstractListModel>
#include <QList>
#include <interfaces/filter.h>
#include "modifier_manager.h"
class ModifierModel : public QAbstractListModel
{
- Q_OBJECT
+ Q_OBJECT
public:
- static const int colIndex = 3;
- static const int colMode = 0;
- static const int colCaption = 1;
- static const int columnNumber = 2;
+ static const int colIndex = 3;
+ static const int colMode = 0;
+ static const int colCaption = 1;
+ static const int columnNumber = 2;
- ModifierModel(ModifierManager *manager);
+ ModifierModel(ModifierManager *manager);
- /** Returns a modifier in function of a model index */
- core::Modifier *modifier(const QModelIndex &index) const;
+ /** Returns a modifier in function of a model index */
+ core::Modifier *modifier(const QModelIndex &index) const;
- /** Add a modifier to the model */
- void addModifier(core::Modifier *modifier);
+ /** Add a modifier to the model */
+ void addModifier(core::Modifier *modifier);
- /** Insert a modifier into the model */
- void insertModifier(int index, core::Modifier *modifier);
+ /** Insert a modifier into the model */
+ void insertModifier(int index, core::Modifier *modifier);
- /*! Remove the modifier at <index> */
- void removeModifier(const QModelIndex &index);
+ /*! Remove the modifier at <index> */
+ void removeModifier(const QModelIndex &index);
- /*! Clear all modifiers */
- virtual void clear();
+ /*! Clear all modifiers */
+ virtual void clear();
- /*! Returns the modifier state */
- bool modifierState(core::Modifier *modifier) const;
+ /*! Returns the modifier state */
+ bool modifierState(core::Modifier *modifier) const;
- /*! Activate or deactivate a modifier */
- void setModifierState(core::Modifier *modifier, bool state);
+ /*! Activate or deactivate a modifier */
+ void setModifierState(core::Modifier *modifier, bool state);
- /*! Toggle the state of the modifier */
- void toggleModifierState(core::Modifier *modifier);
+ /*! Toggle the state of the modifier */
+ void toggleModifierState(core::Modifier *modifier);
- /*! Set a modifier as the uniq modifier, deactivate others */
- void setExclusiveModifier(core::Modifier *modifier);
+ /*! Set a modifier as the uniq modifier, deactivate others */
+ void setExclusiveModifier(core::Modifier *modifier);
- /*! If modifier was not exclusive => set it exclusive */
- void toggleExclusiveState(core::Modifier *modifier);
+ /*! If modifier was not exclusive => set it exclusive */
+ void toggleExclusiveState(core::Modifier *modifier);
- /** Move a modifier from a place to another
+ /** Move a modifier from a place to another
* destination can be >= rowCount(), in this case, the modifier is moved at the list tail
*/
- void moveModifier(int source, int destination);
+ void moveModifier(int source, int destination);
- /*! Returns the exclusive modifier */
- core::Modifier *exclusiveModifier() const { return _exclusiveModifier; }
+ /*! Returns the exclusive modifier */
+ core::Modifier *exclusiveModifier() const { return _exclusiveModifier; }
- void refreshLayout() { emit layoutChanged(); }
+ void refreshLayout() { emit layoutChanged(); }
- void beginUndoAction(); // Must be called just before the undo manager makes an undo or a redo action
- void endUndoAction(); // Must be called just after the undo manager makes an undo or a redo action
+ void beginUndoAction(); // Must be called just before the undo manager makes an undo or a redo action
+ void endUndoAction(); // Must be called just after the undo manager makes an undo or a redo action
- bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
- Qt::DropActions supportedDropActions() const;
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
+ bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ int columnCount(const QModelIndex &parent = QModelIndex()) const;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+ virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
+ Qt::ItemFlags flags(const QModelIndex &index) const;
+ Qt::DropActions supportedDropActions() const;
+ QStringList mimeTypes() const;
+ QMimeData *mimeData(const QModelIndexList &indexes) const;
+ bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
signals:
- void modifiersChanged();
+ void modifiersChanged();
protected:
- ModifierManager *_manager;
- QList<core::Modifier*> _modifiers;
- QMap<core::Modifier*, bool> _modifierStates;
- core::Modifier *_exclusiveModifier;
- QMap<QString,QPair<QString,QVariant> > _changingModifierOldProperties;
+ ModifierManager *_manager;
+ QList<core::Modifier*> _modifiers;
+ QMap<core::Modifier*, bool> _modifierStates;
+ core::Modifier *_exclusiveModifier;
+ QMap<QString,QPair<QString,QVariant> > _changingModifierOldProperties;
private:
- bool _disableUndo;
+ bool _disableUndo;
- void init(core::Modifier *modifier);
+ void init(core::Modifier *modifier);
private slots:
- void modifierChanging();
- void modifierChanged();
+ void modifierChanging();
+ void modifierChanged();
};
#endif
diff --git a/renamah/paths.cpp b/renamah/paths.cpp
index 36268ed..1614ea7 100644
--- a/renamah/paths.cpp
+++ b/renamah/paths.cpp
@@ -1,71 +1,71 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QDir>
#include <QCoreApplication>
#include <QDesktopServices>
#include "global.h"
#include "paths.h"
QString Paths::sharePath()
{
QDir appDir(QCoreApplication::applicationDirPath());
if (Global::devMode()) {
return QDir(appDir.filePath("../share/renamah")).canonicalPath();
- }
+ }
if (Global::localMode())
return appDir.absolutePath();
#if defined(Q_OS_LINUX)
return QDir(appDir.filePath("/usr/share/renamah")).canonicalPath();
#else
return appDir.absolutePath();
#endif
}
QString Paths::libPath()
{
QDir appDir(QCoreApplication::applicationDirPath());
if (Global::devMode()) {
return QDir(appDir.filePath("../lib/renamah")).canonicalPath();
- }
+ }
if (Global::localMode())
return appDir.absolutePath();
#if defined(Q_OS_LINUX)
return QDir(appDir.filePath("/usr/lib/renamah")).canonicalPath();
#else
return appDir.absolutePath();
#endif
}
QString Paths::profilePath()
{
if (Global::devMode() || Global::localMode())
return QDir(QCoreApplication::applicationDirPath()).filePath(qApp->applicationName());
return QDesktopServices::storageLocation(QDesktopServices::DataLocation);
}
diff --git a/renamah/paths.h b/renamah/paths.h
index 69f7fca..495f922 100644
--- a/renamah/paths.h
+++ b/renamah/paths.h
@@ -1,31 +1,31 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef PATHS_H
#define PATHS_H
#include <QString>
namespace Paths
{
QString sharePath();
- QString libPath();
+ QString libPath();
QString profilePath();
};
#endif
diff --git a/renamah/plugin_manager.cpp b/renamah/plugin_manager.cpp
index 98f657f..4ab3d7a 100644
--- a/renamah/plugin_manager.cpp
+++ b/renamah/plugin_manager.cpp
@@ -1,82 +1,82 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QPluginLoader>
#include <QDir>
#include <QCoreApplication>
#include <interfaces/filter.h>
#include <interfaces/filter_factory.h>
#include <interfaces/action_factory.h>
#include "filter_manager.h"
#include "action_manager.h"
#include "paths.h"
#include "plugin_manager.h"
PluginManager *PluginManager::_instance = 0;
PluginManager &PluginManager::instance()
{
- if (!_instance)
- _instance = new PluginManager;
+ if (!_instance)
+ _instance = new PluginManager;
- return *_instance;
+ return *_instance;
}
void PluginManager::load()
{
- // Static plugins
- foreach (QObject *plugin, QPluginLoader::staticInstances())
- dispatchPlugin(plugin);
+ // Static plugins
+ foreach (QObject *plugin, QPluginLoader::staticInstances())
+ dispatchPlugin(plugin);
- // Dynamic plugins
- QDir pluginsDir(QDir(Paths::libPath()).filePath("plugins"));
- foreach (const QString &fileName, pluginsDir.entryList(QDir::Files))
- {
- if (QLibrary::isLibrary(fileName)) {
- QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
- QObject *plugin = loader.instance();
- if (plugin) {
- dispatchPlugin(plugin);
- _pluginFileNames << pluginsDir.absoluteFilePath(fileName);
- }
- else
- qDebug("Error: %s", qPrintable(loader.errorString()));
- }
- }
+ // Dynamic plugins
+ QDir pluginsDir(QDir(Paths::libPath()).filePath("plugins"));
+ foreach (const QString &fileName, pluginsDir.entryList(QDir::Files))
+ {
+ if (QLibrary::isLibrary(fileName)) {
+ QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
+ QObject *plugin = loader.instance();
+ if (plugin) {
+ dispatchPlugin(plugin);
+ _pluginFileNames << pluginsDir.absoluteFilePath(fileName);
+ }
+ else
+ qDebug("Error: %s", qPrintable(loader.errorString()));
+ }
+ }
}
void PluginManager::dispatchPlugin(QObject *plugin)
{
- Q_ASSERT_X(plugin, "PluginManager::dispatchPlugin()", "<plugin> is 0!");
+ Q_ASSERT_X(plugin, "PluginManager::dispatchPlugin()", "<plugin> is 0!");
- core::ModifierFactory *factory = qobject_cast<core::FilterFactory*>(plugin);
- if (factory)
- {
- FilterManager::instance().addFactory(factory);
- return;
- }
+ core::ModifierFactory *factory = qobject_cast<core::FilterFactory*>(plugin);
+ if (factory)
+ {
+ FilterManager::instance().addFactory(factory);
+ return;
+ }
- factory = qobject_cast<core::ActionFactory*>(plugin);
- if (factory)
- {
- ActionManager::instance().addFactory(factory);
- return;
- }
+ factory = qobject_cast<core::ActionFactory*>(plugin);
+ if (factory)
+ {
+ ActionManager::instance().addFactory(factory);
+ return;
+ }
}
diff --git a/renamah/plugin_manager.h b/renamah/plugin_manager.h
index 8632eb2..630afa8 100644
--- a/renamah/plugin_manager.h
+++ b/renamah/plugin_manager.h
@@ -1,42 +1,42 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef PLUGIN_MANAGER_H
#define PLUGIN_MANAGER_H
#include <QObject>
#include <QStringList>
class PluginManager
{
public:
- static PluginManager &instance();
+ static PluginManager &instance();
- void load();
+ void load();
- const QStringList &pluginFileNames() const { return _pluginFileNames; }
+ const QStringList &pluginFileNames() const { return _pluginFileNames; }
private:
- static PluginManager *_instance;
+ static PluginManager *_instance;
- QStringList _pluginFileNames;
+ QStringList _pluginFileNames;
- void dispatchPlugin(QObject *plugin);
+ void dispatchPlugin(QObject *plugin);
};
#endif
diff --git a/renamah/processor.cpp b/renamah/processor.cpp
index 9d9ad16..b23bc51 100644
--- a/renamah/processor.cpp
+++ b/renamah/processor.cpp
@@ -1,151 +1,151 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QFile>
#include <QDir>
#include <QFileInfo>
#include "file_model.h"
#include "filter_model.h"
#include "finalizer_model.h"
#include "processor.h"
Processor *Processor::_instance = 0;
Processor &Processor::instance()
{
- if (!_instance)
- _instance = new Processor;
+ if (!_instance)
+ _instance = new Processor;
- return *_instance;
+ return *_instance;
}
Processor::Processor(QObject *parent)
- : QThread(parent),
- _destinationOperation(Rename)
+ : QThread(parent),
+ _destinationOperation(Rename)
{
}
void Processor::run()
{
- _lastPercent = 0;
- emit percentProgress(_lastPercent);
- typedef QPair<QString,QString> Task;
- int i = 1;
- for (int row = 0; row < FileModel::instance().rowCount(); ++row)
- {
- QString originalFileName = FileModel::instance().originalFileName(FileModel::instance().index(row, 0));
- QString renamedFileName = FileModel::instance().renamedFileName(FileModel::instance().index(row, 0));
-// QString newFileName = FilterModel::instance()->apply(originalFileName);
-
- QFile file(originalFileName);
-
- bool result = false;
- QString destinationFileName = QDir(_destinationDir).filePath(QFileInfo(renamedFileName).fileName());
-
- switch (_destinationOperation)
- {
- case Rename:
- result = file.rename(renamedFileName);
- destinationFileName = renamedFileName;
- break;
- case Copy:
- result = file.copy(destinationFileName);
- break;
- case Move:
- result = file.rename(destinationFileName);
- break;
- case SymLink:
- result = file.link(destinationFileName);
- break;
- default:;
- }
-
- if (result)
- {
- emit taskSuccess(originalFileName, destinationFileName);
-// succeed << QPair<QString,QString>(task.first, task.second);
- }
- else
- {
- emit taskFailure(originalFileName, destinationFileName, file.errorString());
-// failed << QPair<QString,QString>(task.first, task.second);
- }
-
- if (result)
- FinalizerModel::instance().apply(destinationFileName);
-
- int percent = (i * 100) / tasks.count();
- if (percent != _lastPercent)
- {
- _lastPercent = percent;
- emit percentProgress(_lastPercent);
- }
- i++;
- }
+ _lastPercent = 0;
+ emit percentProgress(_lastPercent);
+ typedef QPair<QString,QString> Task;
+ int i = 1;
+ for (int row = 0; row < FileModel::instance().rowCount(); ++row)
+ {
+ QString originalFileName = FileModel::instance().originalFileName(FileModel::instance().index(row, 0));
+ QString renamedFileName = FileModel::instance().renamedFileName(FileModel::instance().index(row, 0));
+ // QString newFileName = FilterModel::instance()->apply(originalFileName);
+
+ QFile file(originalFileName);
+
+ bool result = false;
+ QString destinationFileName = QDir(_destinationDir).filePath(QFileInfo(renamedFileName).fileName());
+
+ switch (_destinationOperation)
+ {
+ case Rename:
+ result = file.rename(renamedFileName);
+ destinationFileName = renamedFileName;
+ break;
+ case Copy:
+ result = file.copy(destinationFileName);
+ break;
+ case Move:
+ result = file.rename(destinationFileName);
+ break;
+ case SymLink:
+ result = file.link(destinationFileName);
+ break;
+ default:;
+ }
+
+ if (result)
+ {
+ emit taskSuccess(originalFileName, destinationFileName);
+ // succeed << QPair<QString,QString>(task.first, task.second);
+ }
+ else
+ {
+ emit taskFailure(originalFileName, destinationFileName, file.errorString());
+ // failed << QPair<QString,QString>(task.first, task.second);
+ }
+
+ if (result)
+ FinalizerModel::instance().apply(destinationFileName);
+
+ int percent = (i * 100) / tasks.count();
+ if (percent != _lastPercent)
+ {
+ _lastPercent = percent;
+ emit percentProgress(_lastPercent);
+ }
+ i++;
+ }
}
void Processor::addTask(const QString &oldFileName, const QString &newFileName)
{
- if (isRunning()) // cannot add tasks while running
- return;
+ if (isRunning()) // cannot add tasks while running
+ return;
- tasks << QPair<QString,QString>(oldFileName, newFileName);
+ tasks << QPair<QString,QString>(oldFileName, newFileName);
}
void Processor::clearTasks()
{
- if (isRunning()) // cannot clear tasks while running
- return;
+ if (isRunning()) // cannot clear tasks while running
+ return;
- tasks.clear();
+ tasks.clear();
}
void Processor::go()
{
- if (!isRunning())
- start();
+ if (!isRunning())
+ start();
}
void Processor::setDestinationOperation(DestinationOperation operation)
{
- if (isRunning() || operation == _destinationOperation)
- return;
+ if (isRunning() || operation == _destinationOperation)
+ return;
- _destinationOperation = operation;
+ _destinationOperation = operation;
}
void Processor::setDestinationDir(const QString &dir)
{
- if (isRunning() || dir == _destinationDir)
- return;
+ if (isRunning() || dir == _destinationDir)
+ return;
- _destinationDir = dir;
+ _destinationDir = dir;
}
QString Processor::destinationOperationName() const
{
- switch (_destinationOperation)
- {
- case Rename: return tr("Rename");
- case Copy: return tr("Copy");
- case Move: return tr("Move");
- case SymLink: return tr("Create link");
- default: return "";
- }
+ switch (_destinationOperation)
+ {
+ case Rename: return tr("Rename");
+ case Copy: return tr("Copy");
+ case Move: return tr("Move");
+ case SymLink: return tr("Create link");
+ default: return "";
+ }
}
diff --git a/renamah/processor.h b/renamah/processor.h
index d92c97a..f925320 100644
--- a/renamah/processor.h
+++ b/renamah/processor.h
@@ -1,71 +1,71 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef PROCESSOR_H
#define PROCESSOR_H
#include <QThread>
#include <QPair>
class Processor : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum DestinationOperation {
- Rename,
- Copy,
- Move,
- SymLink
- };
+ enum DestinationOperation {
+ Rename,
+ Copy,
+ Move,
+ SymLink
+ };
- static Processor &instance();
+ static Processor &instance();
- void clearTasks();
- void addTask(const QString &oldFileName, const QString &newFileName);
- bool hasTasks() const { return tasks.count(); }
+ void clearTasks();
+ void addTask(const QString &oldFileName, const QString &newFileName);
+ bool hasTasks() const { return tasks.count(); }
- DestinationOperation destinationOperation() const { return _destinationOperation; }
- void setDestinationOperation(DestinationOperation operation);
- QString destinationOperationName() const;
- const QString &destinationDir() const { return _destinationDir; }
- void setDestinationDir(const QString &dir);
+ DestinationOperation destinationOperation() const { return _destinationOperation; }
+ void setDestinationOperation(DestinationOperation operation);
+ QString destinationOperationName() const;
+ const QString &destinationDir() const { return _destinationDir; }
+ void setDestinationDir(const QString &dir);
- void go();
+ void go();
signals:
- void taskSuccess(const QString &original, const QString &renamed);
- void taskFailure(const QString &original, const QString &renamed, const QString &errorMsg);
- void percentProgress(int percent);
+ void taskSuccess(const QString &original, const QString &renamed);
+ void taskFailure(const QString &original, const QString &renamed, const QString &errorMsg);
+ void percentProgress(int percent);
protected:
- void run();
+ void run();
private:
- static Processor *_instance;
- QList<QPair<QString,QString> > tasks;
-// QList<QPair<QString,QString> > failed;
-// QList<QPair<QString,QString> > succeed;
- int _lastPercent;
- DestinationOperation _destinationOperation;
- QString _destinationDir;
+ static Processor *_instance;
+ QList<QPair<QString,QString> > tasks;
+ // QList<QPair<QString,QString> > failed;
+ // QList<QPair<QString,QString> > succeed;
+ int _lastPercent;
+ DestinationOperation _destinationOperation;
+ QString _destinationDir;
- Processor(QObject *parent = 0);
+ Processor(QObject *parent = 0);
};
#endif
diff --git a/renamah/profile.cpp b/renamah/profile.cpp
index 594f111..851960d 100644
--- a/renamah/profile.cpp
+++ b/renamah/profile.cpp
@@ -1,197 +1,197 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QDomDocument>
#include <QTextStream>
#include <QMetaProperty>
#include <interfaces/modifier_factory.h>
#include "filter_model.h"
#include "finalizer_model.h"
#include "filter_manager.h"
#include "profile.h"
bool Profile::load(const QString &fileName) {
- QDomDocument doc("renamah_profile");
- QFile file(fileName);
- if (!file.open(QIODevice::ReadOnly)) {
- qCritical("Cannot open the profile file");
- return false;
- }
- if (!doc.setContent(&file)) {
- qCritical("Error in the XML scheme");
- file.close();
- return false;
- }
- file.close();
-
- QDomElement rootElem = doc.firstChildElement("profile");
- if (rootElem.isNull()) {
- qCritical("Error in format of the profile file");
- return false;
- }
-
- FilterModel::instance().clear();
-
- QDomElement extensionPolicyElem = rootElem.firstChildElement("extension_policy");
- if (!extensionPolicyElem.isNull())
- FilterModel::instance().setExtensionPolicy(loadExtensionPolicy(extensionPolicyElem));
-
- // Filters
- QDomElement filtersElem = rootElem.firstChildElement("filters");
- if (!filtersElem.isNull()) {
- QDomElement filterElem = filtersElem.firstChildElement("modifier");
- while (!filterElem.isNull()) {
- QString factoryName = filterElem.attribute("factory");
- core::ModifierFactory *factory = FilterManager::instance().factoryByName(factoryName);
- if (factory) {
- core::Modifier *modifier = factory->makeModifier();
- FilterModel::instance().addModifier(modifier);
- FilterModel::instance().setModifierState(modifier, !filterElem.hasAttribute("state") || filterElem.attribute("state").toInt());
- bool exclusive = filterElem.attribute("exclusive").toInt();
- if (exclusive)
- FilterModel::instance().setExclusiveModifier(modifier);
-
- // Properties
- QDomElement propElem = filterElem.firstChildElement("properties").firstChildElement("property");
- QMap<QString,QPair<QString,QVariant> > properties;
- while (!propElem.isNull()) {
- QString name = propElem.attribute("name");
- QString type = propElem.attribute("type");
- QVariant value(propElem.attribute("value"));
-
- properties.insert(name, QPair<QString,QVariant>(type, value));
-
- // To the next prop
- propElem = propElem.nextSiblingElement("property");
- }
- modifier->deserializeProperties(properties);
-
- // Extension policy
- QDomElement extensionPolicyElem = filterElem.firstChildElement("extension_policy");
- if (!extensionPolicyElem.isNull()) {
- FilterModel::instance().setLocalExtensionPolicyEnabled(static_cast<core::Filter*>(modifier), true);
- FilterModel::instance().setLocalExtensionPolicy(static_cast<core::Filter*>(modifier), loadExtensionPolicy(extensionPolicyElem));
- }
- }
-
- // To the next modifier
- filterElem = filterElem.nextSiblingElement("modifier");
- }
- }
- return true;
+ QDomDocument doc("renamah_profile");
+ QFile file(fileName);
+ if (!file.open(QIODevice::ReadOnly)) {
+ qCritical("Cannot open the profile file");
+ return false;
+ }
+ if (!doc.setContent(&file)) {
+ qCritical("Error in the XML scheme");
+ file.close();
+ return false;
+ }
+ file.close();
+
+ QDomElement rootElem = doc.firstChildElement("profile");
+ if (rootElem.isNull()) {
+ qCritical("Error in format of the profile file");
+ return false;
+ }
+
+ FilterModel::instance().clear();
+
+ QDomElement extensionPolicyElem = rootElem.firstChildElement("extension_policy");
+ if (!extensionPolicyElem.isNull())
+ FilterModel::instance().setExtensionPolicy(loadExtensionPolicy(extensionPolicyElem));
+
+ // Filters
+ QDomElement filtersElem = rootElem.firstChildElement("filters");
+ if (!filtersElem.isNull()) {
+ QDomElement filterElem = filtersElem.firstChildElement("modifier");
+ while (!filterElem.isNull()) {
+ QString factoryName = filterElem.attribute("factory");
+ core::ModifierFactory *factory = FilterManager::instance().factoryByName(factoryName);
+ if (factory) {
+ core::Modifier *modifier = factory->makeModifier();
+ FilterModel::instance().addModifier(modifier);
+ FilterModel::instance().setModifierState(modifier, !filterElem.hasAttribute("state") || filterElem.attribute("state").toInt());
+ bool exclusive = filterElem.attribute("exclusive").toInt();
+ if (exclusive)
+ FilterModel::instance().setExclusiveModifier(modifier);
+
+ // Properties
+ QDomElement propElem = filterElem.firstChildElement("properties").firstChildElement("property");
+ QMap<QString,QPair<QString,QVariant> > properties;
+ while (!propElem.isNull()) {
+ QString name = propElem.attribute("name");
+ QString type = propElem.attribute("type");
+ QVariant value(propElem.attribute("value"));
+
+ properties.insert(name, QPair<QString,QVariant>(type, value));
+
+ // To the next prop
+ propElem = propElem.nextSiblingElement("property");
+ }
+ modifier->deserializeProperties(properties);
+
+ // Extension policy
+ QDomElement extensionPolicyElem = filterElem.firstChildElement("extension_policy");
+ if (!extensionPolicyElem.isNull()) {
+ FilterModel::instance().setLocalExtensionPolicyEnabled(static_cast<core::Filter*>(modifier), true);
+ FilterModel::instance().setLocalExtensionPolicy(static_cast<core::Filter*>(modifier), loadExtensionPolicy(extensionPolicyElem));
+ }
+ }
+
+ // To the next modifier
+ filterElem = filterElem.nextSiblingElement("modifier");
+ }
+ }
+ return true;
}
bool Profile::save(const QString &fileName) {
- QDomDocument doc("renamah_profile");
- QFile file(fileName);
-
- doc.appendChild(doc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"));
-
- QDomElement rootElem = doc.createElement("profile");
- doc.appendChild(rootElem);
-
- // General extension policy
- saveExtensionPolicy(rootElem, FilterModel::instance().extensionPolicy());
-
- // Filters
- QDomElement filtersElem = doc.createElement("filters");
- rootElem.appendChild(filtersElem);
- for (int row = 0; row < FilterModel::instance().rowCount(); ++row) {
- core::Modifier *modifier = FilterModel::instance().modifier(FilterModel::instance().index(row, 0));
-
- QDomElement filterElem = doc.createElement("modifier");
- filtersElem.appendChild(filterElem);
- filterElem.setAttribute("factory", modifier->factory()->info().name());
- filterElem.setAttribute("state", FilterModel::instance().modifierState(modifier) ? "1" : "0");
- if (FilterModel::instance().exclusiveModifier() == modifier)
- filterElem.setAttribute("exclusive", "1");
-
- // Properties
- QDomElement propsElem = doc.createElement("properties");
- filterElem.appendChild(propsElem);
- QMap<QString,QPair<QString,QVariant> > properties = modifier->serializeProperties();
- foreach (const QString &name, properties.keys()) {
- const QPair<QString,QVariant> &pair = properties[name];
- QDomElement propElem = doc.createElement("property");
- propsElem.appendChild(propElem);
- propElem.setAttribute("name", name);
- propElem.setAttribute("type", pair.first);
- propElem.setAttribute("value", pair.second.toString());
- }
-
- // Extension policy
- if (FilterModel::instance().isLocalExtensionPolicyEnabled(static_cast<core::Filter*>(modifier)))
- saveExtensionPolicy(filterElem, FilterModel::instance().localExtensionPolicy(static_cast<core::Filter*>(modifier)));
- }
-
- // Finalizers
- QDomElement finalizersElem = doc.createElement("finalizers");
- rootElem.appendChild(finalizersElem);
- for (int row = 0; row < FinalizerModel::instance().rowCount(); ++row) {
- core::Modifier *modifier = FinalizerModel::instance().modifier(FinalizerModel::instance().index(row, 0));
- QDomElement finalizerElem = doc.createElement("modifier");
- finalizersElem.appendChild(finalizerElem);
- }
-
- if (file.open(QFile::WriteOnly)) {
- QTextStream stream(&file);
- stream << doc.toString(2);
- }
- return true;
+ QDomDocument doc("renamah_profile");
+ QFile file(fileName);
+
+ doc.appendChild(doc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"));
+
+ QDomElement rootElem = doc.createElement("profile");
+ doc.appendChild(rootElem);
+
+ // General extension policy
+ saveExtensionPolicy(rootElem, FilterModel::instance().extensionPolicy());
+
+ // Filters
+ QDomElement filtersElem = doc.createElement("filters");
+ rootElem.appendChild(filtersElem);
+ for (int row = 0; row < FilterModel::instance().rowCount(); ++row) {
+ core::Modifier *modifier = FilterModel::instance().modifier(FilterModel::instance().index(row, 0));
+
+ QDomElement filterElem = doc.createElement("modifier");
+ filtersElem.appendChild(filterElem);
+ filterElem.setAttribute("factory", modifier->factory()->info().name());
+ filterElem.setAttribute("state", FilterModel::instance().modifierState(modifier) ? "1" : "0");
+ if (FilterModel::instance().exclusiveModifier() == modifier)
+ filterElem.setAttribute("exclusive", "1");
+
+ // Properties
+ QDomElement propsElem = doc.createElement("properties");
+ filterElem.appendChild(propsElem);
+ QMap<QString,QPair<QString,QVariant> > properties = modifier->serializeProperties();
+ foreach (const QString &name, properties.keys()) {
+ const QPair<QString,QVariant> &pair = properties[name];
+ QDomElement propElem = doc.createElement("property");
+ propsElem.appendChild(propElem);
+ propElem.setAttribute("name", name);
+ propElem.setAttribute("type", pair.first);
+ propElem.setAttribute("value", pair.second.toString());
+ }
+
+ // Extension policy
+ if (FilterModel::instance().isLocalExtensionPolicyEnabled(static_cast<core::Filter*>(modifier)))
+ saveExtensionPolicy(filterElem, FilterModel::instance().localExtensionPolicy(static_cast<core::Filter*>(modifier)));
+ }
+
+ // Finalizers
+ QDomElement finalizersElem = doc.createElement("finalizers");
+ rootElem.appendChild(finalizersElem);
+ for (int row = 0; row < FinalizerModel::instance().rowCount(); ++row) {
+ core::Modifier *modifier = FinalizerModel::instance().modifier(FinalizerModel::instance().index(row, 0));
+ QDomElement finalizerElem = doc.createElement("modifier");
+ finalizersElem.appendChild(finalizerElem);
+ }
+
+ if (file.open(QFile::WriteOnly)) {
+ QTextStream stream(&file);
+ stream << doc.toString(2);
+ }
+ return true;
}
void Profile::saveExtensionPolicy(QDomElement &root, const ExtensionPolicy &policy) {
- QDomDocument doc = root.ownerDocument();
- QDomElement policyElem = doc.createElement("extension_policy");
- root.appendChild(policyElem);
+ QDomDocument doc = root.ownerDocument();
+ QDomElement policyElem = doc.createElement("extension_policy");
+ root.appendChild(policyElem);
- QDomElement filterPolicyElem = doc.createElement("filter_policy");
- policyElem.appendChild(filterPolicyElem);
+ QDomElement filterPolicyElem = doc.createElement("filter_policy");
+ policyElem.appendChild(filterPolicyElem);
QDomText t = doc.createTextNode(QString::number((int) policy.filterPolicy()));
filterPolicyElem.appendChild(t);
- QDomElement extensionDefinitionElem = doc.createElement("extension_definition");
- policyElem.appendChild(extensionDefinitionElem);
+ QDomElement extensionDefinitionElem = doc.createElement("extension_definition");
+ policyElem.appendChild(extensionDefinitionElem);
t = doc.createTextNode(QString::number((int) policy.extensionDefinition()));
extensionDefinitionElem.appendChild(t);
- QDomElement nthPointFromRightElem = doc.createElement("nth_point_from_right");
- policyElem.appendChild(nthPointFromRightElem);
+ QDomElement nthPointFromRightElem = doc.createElement("nth_point_from_right");
+ policyElem.appendChild(nthPointFromRightElem);
t = doc.createTextNode(QString::number(policy.nthPointFromRight()));
nthPointFromRightElem.appendChild(t);
}
ExtensionPolicy Profile::loadExtensionPolicy(const QDomElement &policyElem) {
- ExtensionPolicy policy;
+ ExtensionPolicy policy;
- QDomElement filterPolicyElem = policyElem.firstChildElement("filter_policy");
- if (!filterPolicyElem.isNull())
- policy.setFilterPolicy((ExtensionPolicy::FilterPolicy) filterPolicyElem.text().toInt());
+ QDomElement filterPolicyElem = policyElem.firstChildElement("filter_policy");
+ if (!filterPolicyElem.isNull())
+ policy.setFilterPolicy((ExtensionPolicy::FilterPolicy) filterPolicyElem.text().toInt());
- QDomElement extensionDefinitionElem = policyElem.firstChildElement("extension_definition");
- if (!extensionDefinitionElem.isNull())
- policy.setExtensionDefinition((ExtensionPolicy::ExtensionDefinition) extensionDefinitionElem.text().toInt());
+ QDomElement extensionDefinitionElem = policyElem.firstChildElement("extension_definition");
+ if (!extensionDefinitionElem.isNull())
+ policy.setExtensionDefinition((ExtensionPolicy::ExtensionDefinition) extensionDefinitionElem.text().toInt());
- QDomElement nthPointFromRightElem = policyElem.firstChildElement("nth_point_from_right");
- if (!nthPointFromRightElem.isNull())
- policy.setNthPointFromRight(nthPointFromRightElem.text().toInt());
+ QDomElement nthPointFromRightElem = policyElem.firstChildElement("nth_point_from_right");
+ if (!nthPointFromRightElem.isNull())
+ policy.setNthPointFromRight(nthPointFromRightElem.text().toInt());
- return policy;
+ return policy;
}
diff --git a/renamah/profile.h b/renamah/profile.h
index 23ca8f0..11305e7 100644
--- a/renamah/profile.h
+++ b/renamah/profile.h
@@ -1,37 +1,37 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef PROFILE_H
#define PROFILE_H
#include <QDomElement>
#include "extension_policy.h"
class Profile
{
public:
- static bool load(const QString &fileName);
- static bool save(const QString &fileName);
+ static bool load(const QString &fileName);
+ static bool save(const QString &fileName);
private:
- static void saveExtensionPolicy(QDomElement &root, const ExtensionPolicy &policy);
- static ExtensionPolicy loadExtensionPolicy(const QDomElement &policyElem);
+ static void saveExtensionPolicy(QDomElement &root, const ExtensionPolicy &policy);
+ static ExtensionPolicy loadExtensionPolicy(const QDomElement &policyElem);
};
#endif
diff --git a/renamah/simple_dir_model.cpp b/renamah/simple_dir_model.cpp
index 76cc57f..dccb49d 100644
--- a/renamah/simple_dir_model.cpp
+++ b/renamah/simple_dir_model.cpp
@@ -1,24 +1,24 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 "simple_dir_model.h"
int SimpleDirModel::columnCount(const QModelIndex & parent) const
{
- return 1;
+ return 1;
}
diff --git a/renamah/simple_dir_model.h b/renamah/simple_dir_model.h
index a308b81..96770e8 100644
--- a/renamah/simple_dir_model.h
+++ b/renamah/simple_dir_model.h
@@ -1,31 +1,31 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef SIMPLE_DIR_MODEL_H
#define SIMPLE_DIR_MODEL_H
#include <QDirModel>
class SimpleDirModel : public QDirModel
{
- Q_OBJECT
+ Q_OBJECT
public:
- int columnCount(const QModelIndex & parent = QModelIndex()) const;
+ int columnCount(const QModelIndex & parent = QModelIndex()) const;
};
#endif
diff --git a/renamah/task_manager.h b/renamah/task_manager.h
index 1f356f8..a4fd190 100644
--- a/renamah/task_manager.h
+++ b/renamah/task_manager.h
@@ -1,32 +1,32 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
- #ifndef TASK_MANAGER_H
- #define TASK_MANAGER_H
+#ifndef TASK_MANAGER_H
+#define TASK_MANAGER_H
class TaskManager
{
public:
static TaskManager &instance();
public:
static TaskManager *_instance;
};
- #endif
+#endif
diff --git a/renamah/twinning_widget.cpp b/renamah/twinning_widget.cpp
index 840f503..989f739 100644
--- a/renamah/twinning_widget.cpp
+++ b/renamah/twinning_widget.cpp
@@ -1,94 +1,94 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QPainter>
#include <QDirModel>
#include "twinning_widget.h"
const int TwinningWidget::_priorityColors[] = {
- Qt::red,
- Qt::blue,
- Qt::green
+ Qt::red,
+ Qt::blue,
+ Qt::green
};
void TwinningWidget::paintEvent(QPaintEvent *event)
{
- QPainter painter(this);
+ QPainter painter(this);
- painter.setRenderHint(QPainter::Antialiasing, true);
+ painter.setRenderHint(QPainter::Antialiasing, true);
- QPen pen(Qt::red);
- pen.setWidth(2);
- painter.setPen(pen);
+ QPen pen(Qt::red);
+ pen.setWidth(2);
+ painter.setPen(pen);
- drawLinks(painter);
+ drawLinks(painter);
-// QWidget::paintEvent(event);
+ // QWidget::paintEvent(event);
}
void TwinningWidget::setTrees(QTreeView *leftTree, QTreeView *rightTree)
{
- _leftTree = leftTree;
- _rightTree = rightTree;
+ _leftTree = leftTree;
+ _rightTree = rightTree;
- update();
+ update();
}
void TwinningWidget::drawLinks(QPainter &painter)
{
- if (!_leftTree || !_rightTree)
- return;
-
- QDirModel *leftModel = qobject_cast<QDirModel*>(_leftTree->model());
- QDirModel *rightModel = qobject_cast<QDirModel*>(_rightTree->model());
-
- foreach (int row, _twinning.keys())
- {
- QModelIndex leftIndex = leftModel->index(row, 0, _leftTree->rootIndex());
- QFileInfo leftFileInfo = leftModel->fileInfo(leftIndex);
- QRect leftVisualRect = _leftTree->visualRect(leftIndex);
- QPoint leftPoint(0, leftVisualRect.y() + leftVisualRect.height() / 2 + _leftTree->viewport()->y());
-
- QPen pen = painter.pen();
- int count = _twinning[row].count();
- int offset = 0;
-
- foreach (int rightRow, _twinning[row])
- {
- QModelIndex rightIndex = rightModel->index(rightRow, 0, _rightTree->rootIndex());
- QFileInfo rightFileInfo = rightModel->fileInfo(rightIndex);
- QRect rightVisualRect = _rightTree->visualRect(rightIndex);
- QPoint rightPoint(width(), rightVisualRect.y() + rightVisualRect.height() / 2 + _rightTree->viewport()->y());
-
- if (leftFileInfo.completeBaseName() == rightFileInfo.completeBaseName())
- pen.setColor(Qt::green);
- else
- pen.setColor(Qt::red);
- painter.setPen(pen);
- painter.drawLine(leftPoint, rightPoint);
- offset++;
- }
- }
+ if (!_leftTree || !_rightTree)
+ return;
+
+ QDirModel *leftModel = qobject_cast<QDirModel*>(_leftTree->model());
+ QDirModel *rightModel = qobject_cast<QDirModel*>(_rightTree->model());
+
+ foreach (int row, _twinning.keys())
+ {
+ QModelIndex leftIndex = leftModel->index(row, 0, _leftTree->rootIndex());
+ QFileInfo leftFileInfo = leftModel->fileInfo(leftIndex);
+ QRect leftVisualRect = _leftTree->visualRect(leftIndex);
+ QPoint leftPoint(0, leftVisualRect.y() + leftVisualRect.height() / 2 + _leftTree->viewport()->y());
+
+ QPen pen = painter.pen();
+ int count = _twinning[row].count();
+ int offset = 0;
+
+ foreach (int rightRow, _twinning[row])
+ {
+ QModelIndex rightIndex = rightModel->index(rightRow, 0, _rightTree->rootIndex());
+ QFileInfo rightFileInfo = rightModel->fileInfo(rightIndex);
+ QRect rightVisualRect = _rightTree->visualRect(rightIndex);
+ QPoint rightPoint(width(), rightVisualRect.y() + rightVisualRect.height() / 2 + _rightTree->viewport()->y());
+
+ if (leftFileInfo.completeBaseName() == rightFileInfo.completeBaseName())
+ pen.setColor(Qt::green);
+ else
+ pen.setColor(Qt::red);
+ painter.setPen(pen);
+ painter.drawLine(leftPoint, rightPoint);
+ offset++;
+ }
+ }
}
void TwinningWidget::setTwinning(const QMap<int, QList<int> > &twinning)
{
- _twinning = twinning;
- update();
+ _twinning = twinning;
+ update();
}
diff --git a/renamah/twinning_widget.h b/renamah/twinning_widget.h
index 6b00ada..0fe77c4 100644
--- a/renamah/twinning_widget.h
+++ b/renamah/twinning_widget.h
@@ -1,52 +1,52 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef TWINNING_WIDGET_H
#define TWINNING_WIDGET_H
#include <QWidget>
#include <QTreeView>
class TwinningWidget : public QWidget
{
- Q_OBJECT
+ Q_OBJECT
public:
- TwinningWidget(QWidget *parent = 0)
- : QWidget(parent),
- _leftTree(0),
- _rightTree(0) {}
+ TwinningWidget(QWidget *parent = 0)
+ : QWidget(parent),
+ _leftTree(0),
+ _rightTree(0) {}
- void setTrees(QTreeView *leftTree, QTreeView *rightTree);
+ void setTrees(QTreeView *leftTree, QTreeView *rightTree);
- void setTwinning(const QMap<int, QList<int> > &twinning);
+ void setTwinning(const QMap<int, QList<int> > &twinning);
protected:
- void paintEvent(QPaintEvent *event);
+ void paintEvent(QPaintEvent *event);
private:
- static const int _priorityColors[];
+ static const int _priorityColors[];
- QTreeView *_leftTree;
- QTreeView *_rightTree;
- QMap<int, QList<int> > _twinning;
+ QTreeView *_leftTree;
+ QTreeView *_rightTree;
+ QMap<int, QList<int> > _twinning;
- void drawLinks(QPainter &painter);
+ void drawLinks(QPainter &painter);
};
#endif
diff --git a/renamah/undo_manager.cpp b/renamah/undo_manager.cpp
index b4ff6f2..91907c4 100644
--- a/renamah/undo_manager.cpp
+++ b/renamah/undo_manager.cpp
@@ -1,153 +1,153 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 "undo_manager.h"
UndoManager *UndoManager::_instance = 0;
UndoManager &UndoManager::instance() {
- if (!_instance)
- _instance = new UndoManager;
+ if (!_instance)
+ _instance = new UndoManager;
- return *_instance;
+ return *_instance;
}
/////////////////////////////////
/// ModifierCommand /////////////
/////////////////////////////////
ModifierCommand::ModifierCommand(ModifierModel *model)
- : _model(model),
- _activated(false) {
+ : _model(model),
+ _activated(false) {
}
void ModifierCommand::undo() {
- if (!_activated)
- return;
+ if (!_activated)
+ return;
- _model->beginUndoAction();
- makeUndo();
- _model->endUndoAction();
+ _model->beginUndoAction();
+ makeUndo();
+ _model->endUndoAction();
}
void ModifierCommand::redo() {
- if (!_activated)
- return;
+ if (!_activated)
+ return;
- _model->beginUndoAction();
- makeRedo();
- _model->endUndoAction();
+ _model->beginUndoAction();
+ makeRedo();
+ _model->endUndoAction();
}
/////////////////////////////////
/// ModifyModifierCommand ///////
/////////////////////////////////
ModifyModifierCommand::ModifyModifierCommand(ModifierModel *model,
- int modifierIndex,
- const QMap<QString,QPair<QString,QVariant> > &undoProperties,
- const QMap<QString,QPair<QString,QVariant> > &redoProperties)
- : ModifierCommand(model),
- _modifierIndex(modifierIndex),
- _undoProperties(undoProperties),
- _redoProperties(redoProperties) {
- setText("Modifier modification");
+ int modifierIndex,
+ const QMap<QString,QPair<QString,QVariant> > &undoProperties,
+ const QMap<QString,QPair<QString,QVariant> > &redoProperties)
+ : ModifierCommand(model),
+ _modifierIndex(modifierIndex),
+ _undoProperties(undoProperties),
+ _redoProperties(redoProperties) {
+ setText("Modifier modification");
}
void ModifyModifierCommand::makeUndo() {
- core::Modifier *modifier = _model->modifier(_model->index(_modifierIndex, 0));
- modifier->deserializeProperties(_undoProperties);
+ core::Modifier *modifier = _model->modifier(_model->index(_modifierIndex, 0));
+ modifier->deserializeProperties(_undoProperties);
}
void ModifyModifierCommand::makeRedo() {
- core::Modifier *modifier = _model->modifier(_model->index(_modifierIndex, 0));
- modifier->deserializeProperties(_redoProperties);
+ core::Modifier *modifier = _model->modifier(_model->index(_modifierIndex, 0));
+ modifier->deserializeProperties(_redoProperties);
}
/////////////////////////////////
/// CreateModifierCommand ///////
/////////////////////////////////
CreateModifierCommand::CreateModifierCommand(ModifierModel *model,
- ModifierManager *manager,
- const QString &factoryName)
- : ModifierCommand(model),
- _manager(manager),
- _factoryName(factoryName) {
- setText("Modifier creation");
+ ModifierManager *manager,
+ const QString &factoryName)
+ : ModifierCommand(model),
+ _manager(manager),
+ _factoryName(factoryName) {
+ setText("Modifier creation");
}
void CreateModifierCommand::makeUndo() {
- _model->removeModifier(_model->index(_model->rowCount() - 1, 0));
+ _model->removeModifier(_model->index(_model->rowCount() - 1, 0));
}
void CreateModifierCommand::makeRedo() {
- core::ModifierFactory *factory = _manager->factoryByName(_factoryName);
- core::Modifier *modifier = factory->makeModifier();
- _model->addModifier(modifier);
+ core::ModifierFactory *factory = _manager->factoryByName(_factoryName);
+ core::Modifier *modifier = factory->makeModifier();
+ _model->addModifier(modifier);
}
/////////////////////////////////
/// RemoveModifierCommand ///////
/////////////////////////////////
RemoveModifierCommand::RemoveModifierCommand(ModifierModel *model,
- ModifierManager *manager,
- int modifierIndex,
- const QString &factoryName,
- const QMap<QString,QPair<QString,QVariant> > &properties)
- : ModifierCommand(model),
- _manager(manager),
- _modifierIndex(modifierIndex),
- _factoryName(factoryName),
- _properties(properties) {
- setText("Modifier removing");
+ ModifierManager *manager,
+ int modifierIndex,
+ const QString &factoryName,
+ const QMap<QString,QPair<QString,QVariant> > &properties)
+ : ModifierCommand(model),
+ _manager(manager),
+ _modifierIndex(modifierIndex),
+ _factoryName(factoryName),
+ _properties(properties) {
+ setText("Modifier removing");
}
void RemoveModifierCommand::makeUndo() {
- core::ModifierFactory *factory = _manager->factoryByName(_factoryName);
- core::Modifier *modifier = factory->makeModifier();
- modifier->deserializeProperties(_properties);
- _model->insertModifier(_modifierIndex, modifier);
+ core::ModifierFactory *factory = _manager->factoryByName(_factoryName);
+ core::Modifier *modifier = factory->makeModifier();
+ modifier->deserializeProperties(_properties);
+ _model->insertModifier(_modifierIndex, modifier);
}
void RemoveModifierCommand::makeRedo() {
- _model->removeModifier(_model->index(_modifierIndex, 0));
+ _model->removeModifier(_model->index(_modifierIndex, 0));
}
/////////////////////////////////
/// MoveModifierCommand /////////
/////////////////////////////////
MoveModifierCommand::MoveModifierCommand(ModifierModel *model, int sourceRow, int destinationRow)
- : ModifierCommand(model),
- _sourceRow(sourceRow),
- _destinationRow(destinationRow) {
- setText("Modifier move");
+ : ModifierCommand(model),
+ _sourceRow(sourceRow),
+ _destinationRow(destinationRow) {
+ setText("Modifier move");
}
void MoveModifierCommand::makeUndo() {
- if (_destinationRow >= _model->rowCount())
- _model->moveModifier(_model->rowCount() - 1, _sourceRow);
- else
- _model->moveModifier(_destinationRow, _sourceRow);
+ if (_destinationRow >= _model->rowCount())
+ _model->moveModifier(_model->rowCount() - 1, _sourceRow);
+ else
+ _model->moveModifier(_destinationRow, _sourceRow);
}
void MoveModifierCommand::makeRedo() {
- _model->moveModifier(_sourceRow, _destinationRow);
+ _model->moveModifier(_sourceRow, _destinationRow);
}
diff --git a/renamah/undo_manager.h b/renamah/undo_manager.h
index 40eab70..f288ef5 100644
--- a/renamah/undo_manager.h
+++ b/renamah/undo_manager.h
@@ -1,129 +1,129 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef UNDO_MANAGER_H
#define UNDO_MANAGER_H
#include <QUndoStack>
#include <QUndoCommand>
#include <QMap>
#include <QPair>
#include <QVariant>
#include "modifier_model.h"
#include "modifier_manager.h"
class ModifierCommand : public QUndoCommand
{
public:
- ModifierCommand(ModifierModel *model);
+ ModifierCommand(ModifierModel *model);
- /// undo/redo won't work until this command is activated
- void activate() { _activated = true; }
+ /// undo/redo won't work until this command is activated
+ void activate() { _activated = true; }
- void undo();
- void redo();
+ void undo();
+ void redo();
protected:
- ModifierModel *_model;
+ ModifierModel *_model;
- virtual void makeUndo() = 0;
- virtual void makeRedo() = 0;
+ virtual void makeUndo() = 0;
+ virtual void makeRedo() = 0;
private:
- bool _activated;
+ bool _activated;
};
class ModifyModifierCommand : public ModifierCommand
{
public:
- ModifyModifierCommand(ModifierModel *model,
- int modifierIndex,
- const QMap<QString,QPair<QString,QVariant> > &undoProperties,
- const QMap<QString,QPair<QString,QVariant> > &redoProperties);
+ ModifyModifierCommand(ModifierModel *model,
+ int modifierIndex,
+ const QMap<QString,QPair<QString,QVariant> > &undoProperties,
+ const QMap<QString,QPair<QString,QVariant> > &redoProperties);
- void makeUndo();
- void makeRedo();
+ void makeUndo();
+ void makeRedo();
private:
- int _modifierIndex;
- QMap<QString,QPair<QString,QVariant> > _undoProperties;
- QMap<QString,QPair<QString,QVariant> > _redoProperties;
+ int _modifierIndex;
+ QMap<QString,QPair<QString,QVariant> > _undoProperties;
+ QMap<QString,QPair<QString,QVariant> > _redoProperties;
};
class CreateModifierCommand : public ModifierCommand
{
public:
- CreateModifierCommand(ModifierModel *model,
- ModifierManager *manager,
- const QString &factoryName);
+ CreateModifierCommand(ModifierModel *model,
+ ModifierManager *manager,
+ const QString &factoryName);
- void makeUndo();
- void makeRedo();
+ void makeUndo();
+ void makeRedo();
private:
- ModifierManager *_manager;
- QString _factoryName;
+ ModifierManager *_manager;
+ QString _factoryName;
};
class RemoveModifierCommand : public ModifierCommand
{
public:
- RemoveModifierCommand(ModifierModel *model,
- ModifierManager *manager,
- int modifierIndex,
- const QString &factoryName,
- const QMap<QString,QPair<QString,QVariant> > &properties);
+ RemoveModifierCommand(ModifierModel *model,
+ ModifierManager *manager,
+ int modifierIndex,
+ const QString &factoryName,
+ const QMap<QString,QPair<QString,QVariant> > &properties);
- void makeUndo();
- void makeRedo();
+ void makeUndo();
+ void makeRedo();
private:
- ModifierManager *_manager;
- int _modifierIndex;
- QString _factoryName;
- QMap<QString,QPair<QString,QVariant> > _properties;
+ ModifierManager *_manager;
+ int _modifierIndex;
+ QString _factoryName;
+ QMap<QString,QPair<QString,QVariant> > _properties;
};
class MoveModifierCommand : public ModifierCommand
{
public:
- MoveModifierCommand(ModifierModel *model, int sourceRow, int destinationRow);
+ MoveModifierCommand(ModifierModel *model, int sourceRow, int destinationRow);
- void makeUndo();
- void makeRedo();
+ void makeUndo();
+ void makeRedo();
private:
- int _sourceRow;
- int _destinationRow;
+ int _sourceRow;
+ int _destinationRow;
};
class UndoManager : public QUndoStack
{
- Q_OBJECT
+ Q_OBJECT
public:
- static UndoManager &instance();
+ static UndoManager &instance();
private:
- UndoManager(QObject *parent = 0) : QUndoStack(parent) {}
+ UndoManager(QObject *parent = 0) : QUndoStack(parent) {}
- static UndoManager *_instance;
+ static UndoManager *_instance;
};
#endif
diff --git a/renamah/widget_actions.cpp b/renamah/widget_actions.cpp
index 936176a..b6f75be 100644
--- a/renamah/widget_actions.cpp
+++ b/renamah/widget_actions.cpp
@@ -1,37 +1,37 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 "widget_actions.h"
WidgetActions::WidgetActions(QWidget *parent)
- : WidgetModifiers(parent)
+ : WidgetModifiers(parent)
{
- QVBoxLayout *mainLayout = new QVBoxLayout(widgetConfig);
- mainLayout->setMargin(0);
+ QVBoxLayout *mainLayout = new QVBoxLayout(widgetConfig);
+ mainLayout->setMargin(0);
- // Constructs actions specific widgets
- scrollAreaGeneral = new QScrollArea;
- scrollAreaGeneral->setFrameShape(QFrame::NoFrame);
- scrollAreaGeneral->setWidgetResizable(true);
- mainLayout->addWidget(scrollAreaGeneral);
+ // Constructs actions specific widgets
+ scrollAreaGeneral = new QScrollArea;
+ scrollAreaGeneral->setFrameShape(QFrame::NoFrame);
+ scrollAreaGeneral->setWidgetResizable(true);
+ mainLayout->addWidget(scrollAreaGeneral);
}
void WidgetActions::setConfigWidget(QWidget *widget)
{
- scrollAreaGeneral->setWidget(widget);
+ scrollAreaGeneral->setWidget(widget);
}
diff --git a/renamah/widget_actions.h b/renamah/widget_actions.h
index 4007555..8235d6f 100644
--- a/renamah/widget_actions.h
+++ b/renamah/widget_actions.h
@@ -1,40 +1,40 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef WIDGET_ACTIONS_H
#define WIDGET_ACTIONS_H
#include <QScrollArea>
#include "widget_modifiers.h"
class WidgetActions : public WidgetModifiers
{
- Q_OBJECT
+ Q_OBJECT
public:
- WidgetActions(QWidget *parent = 0);
+ WidgetActions(QWidget *parent = 0);
protected:
- void setConfigWidget(QWidget *widget);
+ void setConfigWidget(QWidget *widget);
private:
- QScrollArea *scrollAreaGeneral;
+ QScrollArea *scrollAreaGeneral;
};
#endif
diff --git a/renamah/widget_extension_policy.cpp b/renamah/widget_extension_policy.cpp
index 5b3174c..ba6b8ad 100644
--- a/renamah/widget_extension_policy.cpp
+++ b/renamah/widget_extension_policy.cpp
@@ -1,155 +1,155 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QMessageBox>
#include "widget_extension_policy.h"
WidgetExtensionPolicy::WidgetExtensionPolicy(QWidget *parent)
- : QWidget(parent)
+ : QWidget(parent)
{
- setupUi(this);
+ setupUi(this);
- refreshControls();
+ refreshControls();
}
void WidgetExtensionPolicy::setExtensionPolicy(const ExtensionPolicy &policy)
{
- if (policy == _extensionPolicy)
- return;
+ if (policy == _extensionPolicy)
+ return;
- _extensionPolicy = policy;
+ _extensionPolicy = policy;
- refreshControls();
+ refreshControls();
}
void WidgetExtensionPolicy::refreshControls()
{
- switch (_extensionPolicy.filterPolicy())
- {
- case ExtensionPolicy::FilterBaseName:
- radioButtonFilterBasename->setChecked(true);
- break;
- case ExtensionPolicy::FilterExtension:
- radioButtonFilterExtension->setChecked(true);
- break;
- case ExtensionPolicy::FilterAll:
- radioButtonFilterAll->setChecked(true);
- break;
- default:;
- }
-
- switch (_extensionPolicy.extensionDefinition())
- {
- case ExtensionPolicy::FirstPoint:
- radioButtonExtensionDefinitionFirstPoint->setChecked(true);
- break;
- case ExtensionPolicy::LastPoint:
- radioButtonExtensionDefinitionLastPoint->setChecked(true);
- break;
- case ExtensionPolicy::NthPointFromRight:
- radioButtonExtensionDefinitionNthPoint->setChecked(true);
- break;
- default:;
- }
-
- spinBoxExtensionNthPoint->setEnabled(radioButtonExtensionDefinitionNthPoint->isChecked());
- spinBoxExtensionNthPoint->setValue(_extensionPolicy.nthPointFromRight());
- labelExtensionNthPoint->setEnabled(radioButtonExtensionDefinitionNthPoint->isChecked());
+ switch (_extensionPolicy.filterPolicy())
+ {
+ case ExtensionPolicy::FilterBaseName:
+ radioButtonFilterBasename->setChecked(true);
+ break;
+ case ExtensionPolicy::FilterExtension:
+ radioButtonFilterExtension->setChecked(true);
+ break;
+ case ExtensionPolicy::FilterAll:
+ radioButtonFilterAll->setChecked(true);
+ break;
+ default:;
+ }
+
+ switch (_extensionPolicy.extensionDefinition())
+ {
+ case ExtensionPolicy::FirstPoint:
+ radioButtonExtensionDefinitionFirstPoint->setChecked(true);
+ break;
+ case ExtensionPolicy::LastPoint:
+ radioButtonExtensionDefinitionLastPoint->setChecked(true);
+ break;
+ case ExtensionPolicy::NthPointFromRight:
+ radioButtonExtensionDefinitionNthPoint->setChecked(true);
+ break;
+ default:;
+ }
+
+ spinBoxExtensionNthPoint->setEnabled(radioButtonExtensionDefinitionNthPoint->isChecked());
+ spinBoxExtensionNthPoint->setValue(_extensionPolicy.nthPointFromRight());
+ labelExtensionNthPoint->setEnabled(radioButtonExtensionDefinitionNthPoint->isChecked());
}
void WidgetExtensionPolicy::on_radioButtonFilterBasename_toggled(bool checked)
{
- if (checked)
- {
- _extensionPolicy.setFilterPolicy(ExtensionPolicy::FilterBaseName);
- emit extensionPolicyChanged();
- }
+ if (checked)
+ {
+ _extensionPolicy.setFilterPolicy(ExtensionPolicy::FilterBaseName);
+ emit extensionPolicyChanged();
+ }
}
void WidgetExtensionPolicy::on_radioButtonFilterAll_toggled(bool checked)
{
- if (checked)
- {
- _extensionPolicy.setFilterPolicy(ExtensionPolicy::FilterAll);
- emit extensionPolicyChanged();
- }
+ if (checked)
+ {
+ _extensionPolicy.setFilterPolicy(ExtensionPolicy::FilterAll);
+ emit extensionPolicyChanged();
+ }
}
void WidgetExtensionPolicy::on_radioButtonFilterExtension_toggled(bool checked)
{
- if (checked)
- {
- _extensionPolicy.setFilterPolicy(ExtensionPolicy::FilterExtension);
- emit extensionPolicyChanged();
- }
+ if (checked)
+ {
+ _extensionPolicy.setFilterPolicy(ExtensionPolicy::FilterExtension);
+ emit extensionPolicyChanged();
+ }
}
void WidgetExtensionPolicy::on_radioButtonExtensionDefinitionLastPoint_toggled(bool checked)
{
- if (checked)
- {
- _extensionPolicy.setExtensionDefinition(ExtensionPolicy::LastPoint);
- emit extensionPolicyChanged();
- }
+ if (checked)
+ {
+ _extensionPolicy.setExtensionDefinition(ExtensionPolicy::LastPoint);
+ emit extensionPolicyChanged();
+ }
}
void WidgetExtensionPolicy::on_radioButtonExtensionDefinitionFirstPoint_toggled(bool checked)
{
- if (checked)
- {
- _extensionPolicy.setExtensionDefinition(ExtensionPolicy::FirstPoint);
- emit extensionPolicyChanged();
- }
+ if (checked)
+ {
+ _extensionPolicy.setExtensionDefinition(ExtensionPolicy::FirstPoint);
+ emit extensionPolicyChanged();
+ }
}
void WidgetExtensionPolicy::on_radioButtonExtensionDefinitionNthPoint_toggled(bool checked)
{
- spinBoxExtensionNthPoint->setEnabled(checked);
- labelExtensionNthPoint->setEnabled(checked);
-
- if (checked)
- {
- _extensionPolicy.setExtensionDefinition(ExtensionPolicy::NthPointFromRight);
- emit extensionPolicyChanged();
- }
+ spinBoxExtensionNthPoint->setEnabled(checked);
+ labelExtensionNthPoint->setEnabled(checked);
+
+ if (checked)
+ {
+ _extensionPolicy.setExtensionDefinition(ExtensionPolicy::NthPointFromRight);
+ emit extensionPolicyChanged();
+ }
}
void WidgetExtensionPolicy::on_spinBoxExtensionNthPoint_valueChanged(int value)
{
- _extensionPolicy.setNthPointFromRight(value);
- emit extensionPolicyChanged();
+ _extensionPolicy.setNthPointFromRight(value);
+ emit extensionPolicyChanged();
}
void WidgetExtensionPolicy::on_pushButtonReset_clicked()
{
- if (QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to return to default extension policy settings?"),
- QMessageBox::Yes | QMessageBox::Cancel) != QMessageBox::Yes)
- return;
+ if (QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to return to default extension policy settings?"),
+ QMessageBox::Yes | QMessageBox::Cancel) != QMessageBox::Yes)
+ return;
- _extensionPolicy.reset();
- refreshControls();
- emit extensionPolicyChanged();
+ _extensionPolicy.reset();
+ refreshControls();
+ emit extensionPolicyChanged();
}
void WidgetExtensionPolicy::changeEvent(QEvent *event) {
- if (event->type() == QEvent::LanguageChange) {
- retranslateUi(this);
- } else
- QWidget::changeEvent(event);
+ if (event->type() == QEvent::LanguageChange) {
+ retranslateUi(this);
+ } else
+ QWidget::changeEvent(event);
}
diff --git a/renamah/widget_extension_policy.h b/renamah/widget_extension_policy.h
index d4f869e..09fa286 100644
--- a/renamah/widget_extension_policy.h
+++ b/renamah/widget_extension_policy.h
@@ -1,58 +1,58 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef WIDGET_EXTENSION_POLICY_H
#define WIDGET_EXTENSION_POLICY_H
#include "extension_policy.h"
#include "ui_widget_extension_policy.h"
class WidgetExtensionPolicy : public QWidget, private Ui::WidgetExtensionPolicy
{
- Q_OBJECT
+ Q_OBJECT
public:
- WidgetExtensionPolicy(QWidget *parent = 0);
+ WidgetExtensionPolicy(QWidget *parent = 0);
- const ExtensionPolicy &extensionPolicy() const { return _extensionPolicy; }
- void setExtensionPolicy(const ExtensionPolicy &policy);
+ const ExtensionPolicy &extensionPolicy() const { return _extensionPolicy; }
+ void setExtensionPolicy(const ExtensionPolicy &policy);
signals:
- void extensionPolicyChanged();
+ void extensionPolicyChanged();
protected:
- void changeEvent(QEvent *event);
+ void changeEvent(QEvent *event);
private:
- ExtensionPolicy _extensionPolicy;
+ ExtensionPolicy _extensionPolicy;
- void refreshControls();
+ void refreshControls();
private slots:
- void on_radioButtonFilterBasename_toggled(bool checked);
- void on_radioButtonFilterAll_toggled(bool checked);
- void on_radioButtonFilterExtension_toggled(bool checked);
- void on_radioButtonExtensionDefinitionLastPoint_toggled(bool checked);
- void on_radioButtonExtensionDefinitionFirstPoint_toggled(bool checked);
- void on_radioButtonExtensionDefinitionNthPoint_toggled(bool checked);
- void on_spinBoxExtensionNthPoint_valueChanged(int value);
- void on_pushButtonReset_clicked();
+ void on_radioButtonFilterBasename_toggled(bool checked);
+ void on_radioButtonFilterAll_toggled(bool checked);
+ void on_radioButtonFilterExtension_toggled(bool checked);
+ void on_radioButtonExtensionDefinitionLastPoint_toggled(bool checked);
+ void on_radioButtonExtensionDefinitionFirstPoint_toggled(bool checked);
+ void on_radioButtonExtensionDefinitionNthPoint_toggled(bool checked);
+ void on_spinBoxExtensionNthPoint_valueChanged(int value);
+ void on_pushButtonReset_clicked();
};
#endif
diff --git a/renamah/widget_filters.cpp b/renamah/widget_filters.cpp
index 3c40c96..7f703a2 100644
--- a/renamah/widget_filters.cpp
+++ b/renamah/widget_filters.cpp
@@ -1,98 +1,98 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 "filter_model.h"
#include "widget_filters.h"
WidgetFilters::WidgetFilters(QWidget *parent)
- : WidgetModifiers(parent)
+ : WidgetModifiers(parent)
{
- QVBoxLayout *mainLayout = new QVBoxLayout(widgetConfig);
- mainLayout->setMargin(0);
+ QVBoxLayout *mainLayout = new QVBoxLayout(widgetConfig);
+ mainLayout->setMargin(0);
- // Constructs filters specific widgets
- tabWidgetMain = new QTabWidget;
- mainLayout->addWidget(tabWidgetMain);
+ // Constructs filters specific widgets
+ tabWidgetMain = new QTabWidget;
+ mainLayout->addWidget(tabWidgetMain);
- scrollAreaGeneral = new QScrollArea;
- scrollAreaGeneral->setFrameShape(QFrame::NoFrame);
- scrollAreaGeneral->setWidgetResizable(true);
- tabWidgetMain->addTab(scrollAreaGeneral, "");
+ scrollAreaGeneral = new QScrollArea;
+ scrollAreaGeneral->setFrameShape(QFrame::NoFrame);
+ scrollAreaGeneral->setWidgetResizable(true);
+ tabWidgetMain->addTab(scrollAreaGeneral, "");
- scrollAreaExtensionPolicy = new QScrollArea;
- scrollAreaExtensionPolicy->setFrameShape(QFrame::NoFrame);
- scrollAreaExtensionPolicy->setWidgetResizable(true);
- tabWidgetMain->addTab(scrollAreaExtensionPolicy, "");
- QWidget *widget = new QWidget;
- QVBoxLayout *layout = new QVBoxLayout(widget);
- scrollAreaExtensionPolicy->setWidget(widget);
- checkBoxExtensionPolicyState = new QCheckBox;
- connect(checkBoxExtensionPolicyState, SIGNAL(toggled(bool)),
- this, SLOT(extensionPolicyStateToggled(bool)));
- layout->addWidget(checkBoxExtensionPolicyState);
- layout->addWidget(widgetExtensionPolicy = new WidgetExtensionPolicy);
- connect(widgetExtensionPolicy, SIGNAL(extensionPolicyChanged()),
- this, SLOT(extensionPolicyChanged()));
+ scrollAreaExtensionPolicy = new QScrollArea;
+ scrollAreaExtensionPolicy->setFrameShape(QFrame::NoFrame);
+ scrollAreaExtensionPolicy->setWidgetResizable(true);
+ tabWidgetMain->addTab(scrollAreaExtensionPolicy, "");
+ QWidget *widget = new QWidget;
+ QVBoxLayout *layout = new QVBoxLayout(widget);
+ scrollAreaExtensionPolicy->setWidget(widget);
+ checkBoxExtensionPolicyState = new QCheckBox;
+ connect(checkBoxExtensionPolicyState, SIGNAL(toggled(bool)),
+ this, SLOT(extensionPolicyStateToggled(bool)));
+ layout->addWidget(checkBoxExtensionPolicyState);
+ layout->addWidget(widgetExtensionPolicy = new WidgetExtensionPolicy);
+ connect(widgetExtensionPolicy, SIGNAL(extensionPolicyChanged()),
+ this, SLOT(extensionPolicyChanged()));
- retranslate();
+ retranslate();
}
void WidgetFilters::retranslate() {
- checkBoxExtensionPolicyState->setText(tr("Override the global extension policy"));
- tabWidgetMain->setTabText(tabWidgetMain->indexOf(scrollAreaGeneral), tr("General"));
- tabWidgetMain->setTabText(tabWidgetMain->indexOf(scrollAreaExtensionPolicy), tr("Extension policy"));
+ checkBoxExtensionPolicyState->setText(tr("Override the global extension policy"));
+ tabWidgetMain->setTabText(tabWidgetMain->indexOf(scrollAreaGeneral), tr("General"));
+ tabWidgetMain->setTabText(tabWidgetMain->indexOf(scrollAreaExtensionPolicy), tr("Extension policy"));
}
void WidgetFilters::extensionPolicyStateToggled(bool checked)
{
- widgetExtensionPolicy->setEnabled(checked);
- core::Filter *filter = static_cast<core::Filter*>(currentModifier());
- FilterModel::instance().setLocalExtensionPolicyEnabled(filter, checked);
+ widgetExtensionPolicy->setEnabled(checked);
+ core::Filter *filter = static_cast<core::Filter*>(currentModifier());
+ FilterModel::instance().setLocalExtensionPolicyEnabled(filter, checked);
}
void WidgetFilters::setConfigWidget(QWidget *widget)
{
- scrollAreaGeneral->setWidget(widget);
+ scrollAreaGeneral->setWidget(widget);
}
void WidgetFilters::init(ModifierManager *modifierManager, ModifierModel &modifierModel)
{
- WidgetModifiers::init(modifierManager, modifierModel);
+ WidgetModifiers::init(modifierManager, modifierModel);
- tabWidgetMain->setCurrentWidget(scrollAreaGeneral);
- widgetExtensionPolicy->setEnabled(false);
+ tabWidgetMain->setCurrentWidget(scrollAreaGeneral);
+ widgetExtensionPolicy->setEnabled(false);
}
void WidgetFilters::currentModifierChanged(core::Modifier *modifier)
{
- core::Filter *filter = static_cast<core::Filter*>(modifier);
- checkBoxExtensionPolicyState->setChecked(FilterModel::instance().isLocalExtensionPolicyEnabled(filter));
- widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().localExtensionPolicy(filter));
+ core::Filter *filter = static_cast<core::Filter*>(modifier);
+ checkBoxExtensionPolicyState->setChecked(FilterModel::instance().isLocalExtensionPolicyEnabled(filter));
+ widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().localExtensionPolicy(filter));
}
void WidgetFilters::extensionPolicyChanged()
{
- core::Filter *filter = static_cast<core::Filter*>(currentModifier());
- FilterModel::instance().setLocalExtensionPolicy(filter, widgetExtensionPolicy->extensionPolicy());
+ core::Filter *filter = static_cast<core::Filter*>(currentModifier());
+ FilterModel::instance().setLocalExtensionPolicy(filter, widgetExtensionPolicy->extensionPolicy());
}
void WidgetFilters::changeEvent(QEvent *event) {
- if (event->type() == QEvent::LanguageChange)
- retranslate();
- WidgetModifiers::changeEvent(event);
+ if (event->type() == QEvent::LanguageChange)
+ retranslate();
+ WidgetModifiers::changeEvent(event);
}
diff --git a/renamah/widget_filters.h b/renamah/widget_filters.h
index 62e90f9..e156535 100644
--- a/renamah/widget_filters.h
+++ b/renamah/widget_filters.h
@@ -1,58 +1,58 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef WIDGET_FILTERS_H
#define WIDGET_FILTERS_H
#include <QTabWidget>
#include <QScrollArea>
#include <QCheckBox>
#include "widget_modifiers.h"
#include "widget_extension_policy.h"
class WidgetFilters : public WidgetModifiers
{
- Q_OBJECT
+ Q_OBJECT
public:
- WidgetFilters(QWidget *parent = 0);
+ WidgetFilters(QWidget *parent = 0);
- void init(ModifierManager *modifierManager, ModifierModel &modifierModel);
+ void init(ModifierManager *modifierManager, ModifierModel &modifierModel);
protected:
- void setConfigWidget(QWidget *widget);
- void currentModifierChanged(core::Modifier *modifier);
- void changeEvent(QEvent *event);
+ void setConfigWidget(QWidget *widget);
+ void currentModifierChanged(core::Modifier *modifier);
+ void changeEvent(QEvent *event);
private:
- QTabWidget *tabWidgetMain;
- QScrollArea *scrollAreaGeneral;
- QScrollArea *scrollAreaExtensionPolicy;
- QCheckBox *checkBoxExtensionPolicyState;
+ QTabWidget *tabWidgetMain;
+ QScrollArea *scrollAreaGeneral;
+ QScrollArea *scrollAreaExtensionPolicy;
+ QCheckBox *checkBoxExtensionPolicyState;
- WidgetExtensionPolicy *widgetExtensionPolicy;
+ WidgetExtensionPolicy *widgetExtensionPolicy;
- void retranslate();
+ void retranslate();
private slots:
- void extensionPolicyStateToggled(bool checked);
- void extensionPolicyChanged();
+ void extensionPolicyStateToggled(bool checked);
+ void extensionPolicyChanged();
};
#endif
diff --git a/renamah/widget_modifiers.cpp b/renamah/widget_modifiers.cpp
index bbd05db..db2e10c 100644
--- a/renamah/widget_modifiers.cpp
+++ b/renamah/widget_modifiers.cpp
@@ -1,252 +1,252 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QMessageBox>
#include <QMouseEvent>
#include <QHeaderView>
#include <QMetaProperty>
#include "modifier_delegate.h"
#include "widget_modifiers.h"
WidgetModifiers::WidgetModifiers(QWidget *parent)
- : QWidget(parent),
- _modifierManager(0),
- _modifierModel(0) {
- setupUi(this);
+ : QWidget(parent),
+ _modifierManager(0),
+ _modifierModel(0) {
+ setupUi(this);
- connect(&signalMapperAddModifier, SIGNAL(mapped(const QString &)),
- this, SLOT(addModifier(const QString &)));
+ connect(&signalMapperAddModifier, SIGNAL(mapped(const QString &)),
+ this, SLOT(addModifier(const QString &)));
- pushButtonAdd->setMenu(&menuAddModifier);
- connect(&menuAddModifier, SIGNAL(aboutToShow()), this, SLOT(aboutToShowAddModifierMenu()));
+ pushButtonAdd->setMenu(&menuAddModifier);
+ connect(&menuAddModifier, SIGNAL(aboutToShow()), this, SLOT(aboutToShowAddModifierMenu()));
- treeView->setItemDelegate(new ModifierDelegate);
+ treeView->setItemDelegate(new ModifierDelegate);
- labelAddModifier->installEventFilter(this);
- treeView->viewport()->installEventFilter(this);
- treeView->installEventFilter(this);
+ labelAddModifier->installEventFilter(this);
+ treeView->viewport()->installEventFilter(this);
+ treeView->installEventFilter(this);
}
void WidgetModifiers::init(ModifierManager *modifierManager, ModifierModel &modifierModel) {
- _modifierManager = modifierManager;
- _modifierModel = &modifierModel;
+ _modifierManager = modifierManager;
+ _modifierModel = &modifierModel;
- retranslate();
+ retranslate();
- treeView->setModel(_modifierModel);
+ treeView->setModel(_modifierModel);
- connect(_modifierModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
- this, SLOT(modifiersInserted(const QModelIndex &, int, int)));
+ connect(_modifierModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
+ this, SLOT(modifiersInserted(const QModelIndex &, int, int)));
- treeView->header()->setResizeMode(0, QHeaderView::ResizeToContents);
- treeView->header()->setResizeMode(1, QHeaderView::ResizeToContents);
- connect(treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
- this, SLOT(currentModifierChanged(const QModelIndex &, const QModelIndex &)));
+ treeView->header()->setResizeMode(0, QHeaderView::ResizeToContents);
+ treeView->header()->setResizeMode(1, QHeaderView::ResizeToContents);
+ connect(treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
+ this, SLOT(currentModifierChanged(const QModelIndex &, const QModelIndex &)));
- currentModifierChanged(QModelIndex(), QModelIndex());
+ currentModifierChanged(QModelIndex(), QModelIndex());
}
void WidgetModifiers::retranslate() {
- labelAddModifier->setText(tr("Add a new %1").arg(_modifierManager->modifierTypeName()));
+ labelAddModifier->setText(tr("Add a new %1").arg(_modifierManager->modifierTypeName()));
- core::Modifier *modifier = currentModifier();
- if (!modifier)
- return;
+ core::Modifier *modifier = currentModifier();
+ if (!modifier)
+ return;
- core::ModifierFactory *factory = modifier->factory();
+ core::ModifierFactory *factory = modifier->factory();
- labelModifierCaption->setText(factory->info().caption());
- labelModifierDescription->setText(factory->info().description());
+ labelModifierCaption->setText(factory->info().caption());
+ labelModifierDescription->setText(factory->info().description());
}
void WidgetModifiers::on_pushButtonRemove_clicked() {
- QModelIndex index = treeView->currentIndex();
- if (!index.isValid())
- return;
+ QModelIndex index = treeView->currentIndex();
+ if (!index.isValid())
+ return;
- _modifierModel->removeModifier(index);
+ _modifierModel->removeModifier(index);
}
void WidgetModifiers::on_pushButtonUp_clicked() {
- QModelIndex index = treeView->currentIndex();
- if (!index.isValid())
- return;
+ QModelIndex index = treeView->currentIndex();
+ if (!index.isValid())
+ return;
- if (!index.row())
- return;
+ if (!index.row())
+ return;
- _modifierModel->moveModifier(index.row(), index.row() - 1);
+ _modifierModel->moveModifier(index.row(), index.row() - 1);
}
void WidgetModifiers::on_pushButtonDown_clicked() {
- QModelIndex index = treeView->currentIndex();
- if (!index.isValid())
- return;
+ QModelIndex index = treeView->currentIndex();
+ if (!index.isValid())
+ return;
- if (index.row() == _modifierModel->rowCount() - 1)
- return;
+ if (index.row() == _modifierModel->rowCount() - 1)
+ return;
- _modifierModel->moveModifier(index.row(), index.row() + 1);
+ _modifierModel->moveModifier(index.row(), index.row() + 1);
}
void WidgetModifiers::aboutToShowAddModifierMenu() {
- menuAddModifier.clear();
+ menuAddModifier.clear();
- foreach (core::ModifierFactory *factory, _modifierManager->factories())
- {
- QAction *action = menuAddModifier.addAction(factory->info().caption() + " (" + factory->info().description() + ")");
- connect(action, SIGNAL(triggered()), &signalMapperAddModifier, SLOT(map()));
- signalMapperAddModifier.setMapping(action, factory->info().name());
- }
+ foreach (core::ModifierFactory *factory, _modifierManager->factories())
+ {
+ QAction *action = menuAddModifier.addAction(factory->info().caption() + " (" + factory->info().description() + ")");
+ connect(action, SIGNAL(triggered()), &signalMapperAddModifier, SLOT(map()));
+ signalMapperAddModifier.setMapping(action, factory->info().name());
+ }
}
void WidgetModifiers::addModifier(const QString &factoryName) {
- core::ModifierFactory *factory = _modifierManager->factoryByName(factoryName);
- Q_ASSERT_X(factory, "WidgetModifiers::addModifierClicked()", "<factoryName> seems to have no factory correspondant");
+ core::ModifierFactory *factory = _modifierManager->factoryByName(factoryName);
+ Q_ASSERT_X(factory, "WidgetModifiers::addModifierClicked()", "<factoryName> seems to have no factory correspondant");
- _modifierModel->addModifier(factory->makeModifier());
- stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
+ _modifierModel->addModifier(factory->makeModifier());
+ stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
}
void WidgetModifiers::currentModifierChanged(const QModelIndex ¤t, const QModelIndex &previous) {
- if (previous.isValid())
- {
- core::Modifier *previousModifier = _modifierModel->modifier(previous);
- core::ModifierFactory *previousFactory = previousModifier->factory();
- if (_configWidget)
- {
- previousFactory->deleteConfigurationWidget(_configWidget);
- _configWidget = 0;
- }
- }
+ if (previous.isValid())
+ {
+ core::Modifier *previousModifier = _modifierModel->modifier(previous);
+ core::ModifierFactory *previousFactory = previousModifier->factory();
+ if (_configWidget)
+ {
+ previousFactory->deleteConfigurationWidget(_configWidget);
+ _configWidget = 0;
+ }
+ }
- if (!current.isValid())
- {
- stackedWidgetConfiguration->setCurrentWidget(pageNoModifiers);
- currentModifierChanged(0);
- return;
- }
+ if (!current.isValid())
+ {
+ stackedWidgetConfiguration->setCurrentWidget(pageNoModifiers);
+ currentModifierChanged(0);
+ return;
+ }
- stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
+ stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
- core::Modifier *modifier = _modifierModel->modifier(current);
- core::ModifierFactory *factory = modifier->factory();
+ core::Modifier *modifier = _modifierModel->modifier(current);
+ core::ModifierFactory *factory = modifier->factory();
- _configWidget = modifier->factory()->makeConfigurationWidget(modifier);
- if (_configWidget)
- {
- setConfigWidget(_configWidget);
+ _configWidget = modifier->factory()->makeConfigurationWidget(modifier);
+ if (_configWidget)
+ {
+ setConfigWidget(_configWidget);
- frameConfiguration->setVisible(true);
- labelModifierCaption->setText(factory->info().caption());
- labelModifierDescription->setText(factory->info().description());
+ frameConfiguration->setVisible(true);
+ labelModifierCaption->setText(factory->info().caption());
+ labelModifierDescription->setText(factory->info().description());
- connect(modifier, SIGNAL(settingsChanged()), this, SLOT(widgetModifierChanged()));
- }
+ connect(modifier, SIGNAL(settingsChanged()), this, SLOT(widgetModifierChanged()));
+ }
- currentModifierChanged(modifier);
+ currentModifierChanged(modifier);
}
bool WidgetModifiers::eventFilter(QObject *obj, QEvent *ev) {
- if (obj == labelAddModifier && ev->type() == QEvent::MouseButtonPress)
- {
- QMouseEvent *event = static_cast<QMouseEvent*>(ev);
- menuAddModifier.popup(event->globalPos());
- } else if (obj == treeView->viewport() && ev->type() == QEvent::MouseButtonPress)
- {
- QMouseEvent *event = static_cast<QMouseEvent*>(ev);
- QPoint p = event->pos();
- QModelIndex index = treeView->indexAt(p);
- if (index.column() == ModifierModel::colMode)
- {
- if (modifierStateRect(index).contains(p))
- _modifierModel->toggleModifierState(_modifierModel->modifier(index));
- else
- {
- if (modifierOnlyRect(index).contains(p))
- _modifierModel->toggleExclusiveState(_modifierModel->modifier(index));
- }
- }
- } else if (obj == treeView && ev->type() == QEvent::KeyPress)
- {
- QKeyEvent *keyEvent = static_cast<QKeyEvent*>(ev);
- if (keyEvent->key() == Qt::Key_Delete)
- {
- on_pushButtonRemove_clicked();
- }
- }
- return QWidget::eventFilter(obj, ev);
+ if (obj == labelAddModifier && ev->type() == QEvent::MouseButtonPress)
+ {
+ QMouseEvent *event = static_cast<QMouseEvent*>(ev);
+ menuAddModifier.popup(event->globalPos());
+ } else if (obj == treeView->viewport() && ev->type() == QEvent::MouseButtonPress)
+ {
+ QMouseEvent *event = static_cast<QMouseEvent*>(ev);
+ QPoint p = event->pos();
+ QModelIndex index = treeView->indexAt(p);
+ if (index.column() == ModifierModel::colMode)
+ {
+ if (modifierStateRect(index).contains(p))
+ _modifierModel->toggleModifierState(_modifierModel->modifier(index));
+ else
+ {
+ if (modifierOnlyRect(index).contains(p))
+ _modifierModel->toggleExclusiveState(_modifierModel->modifier(index));
+ }
+ }
+ } else if (obj == treeView && ev->type() == QEvent::KeyPress)
+ {
+ QKeyEvent *keyEvent = static_cast<QKeyEvent*>(ev);
+ if (keyEvent->key() == Qt::Key_Delete)
+ {
+ on_pushButtonRemove_clicked();
+ }
+ }
+ return QWidget::eventFilter(obj, ev);
}
QRect WidgetModifiers::modifierStateRect(const QModelIndex &index) const {
- QRect indexRect = treeView->visualRect(index);
+ QRect indexRect = treeView->visualRect(index);
- QRect res(indexRect.left(), indexRect.top(), 16, 16);
+ QRect res(indexRect.left(), indexRect.top(), 16, 16);
- if (indexRect.width() > 32)
- res.translate((indexRect.width() - 32) / 2, 0);
+ if (indexRect.width() > 32)
+ res.translate((indexRect.width() - 32) / 2, 0);
- if (indexRect.height() > 16)
- res.translate(0, (indexRect.height() - 16) / 2);
+ if (indexRect.height() > 16)
+ res.translate(0, (indexRect.height() - 16) / 2);
- return res;
+ return res;
}
QRect WidgetModifiers::modifierOnlyRect(const QModelIndex &index) const {
- QRect indexRect = treeView->visualRect(index);
+ QRect indexRect = treeView->visualRect(index);
- QRect res(indexRect.left() + 16, indexRect.top(), 16, 16);
+ QRect res(indexRect.left() + 16, indexRect.top(), 16, 16);
- if (indexRect.width() > 32)
- res.translate((indexRect.width() - 32) / 2, 0);
+ if (indexRect.width() > 32)
+ res.translate((indexRect.width() - 32) / 2, 0);
- if (indexRect.height() > 16)
- res.translate(0, (indexRect.height() - 16) / 2);
+ if (indexRect.height() > 16)
+ res.translate(0, (indexRect.height() - 16) / 2);
- return res;
+ return res;
}
void WidgetModifiers::widgetModifierChanged() {
- if (treeView->currentIndex().isValid())
- {
- _modifierModel->refreshLayout();
- treeView->update(treeView->currentIndex());
- }
+ if (treeView->currentIndex().isValid())
+ {
+ _modifierModel->refreshLayout();
+ treeView->update(treeView->currentIndex());
+ }
}
core::Modifier *WidgetModifiers::currentModifier() const {
- return _modifierModel->modifier(treeView->currentIndex());
+ return _modifierModel->modifier(treeView->currentIndex());
}
void WidgetModifiers::changeEvent(QEvent *event) {
- if (event->type() == QEvent::LanguageChange) {
- retranslateUi(this);
- retranslate();
- } else
- QWidget::changeEvent(event);
+ if (event->type() == QEvent::LanguageChange) {
+ retranslateUi(this);
+ retranslate();
+ } else
+ QWidget::changeEvent(event);
}
void WidgetModifiers::newProfile() {
- if (_modifierModel->rowCount())
- treeView->setCurrentIndex(_modifierModel->index(0, 0));
+ if (_modifierModel->rowCount())
+ treeView->setCurrentIndex(_modifierModel->index(0, 0));
}
void WidgetModifiers::modifiersInserted(const QModelIndex &parent, int start, int end) {
- treeView->setCurrentIndex(_modifierModel->index(start));
+ treeView->setCurrentIndex(_modifierModel->index(start));
}
diff --git a/renamah/widget_modifiers.h b/renamah/widget_modifiers.h
index 8f42427..d24da87 100644
--- a/renamah/widget_modifiers.h
+++ b/renamah/widget_modifiers.h
@@ -1,74 +1,74 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef WIDGET_MODIFIERS_H
#define WIDGET_MODIFIERS_H
#include <QMenu>
#include <QSignalMapper>
#include "modifier_manager.h"
#include "modifier_model.h"
#include "ui_widget_modifiers.h"
class WidgetModifiers : public QWidget, protected Ui::WidgetModifiers
{
- Q_OBJECT
+ Q_OBJECT
public:
- WidgetModifiers(QWidget *parent = 0);
+ WidgetModifiers(QWidget *parent = 0);
- virtual void init(ModifierManager *modifierManager, ModifierModel &modifierModel);
- /*! Called after each profile loaded */
- virtual void newProfile();
+ virtual void init(ModifierManager *modifierManager, ModifierModel &modifierModel);
+ /*! Called after each profile loaded */
+ virtual void newProfile();
public slots:
- void addModifier(const QString &factoryName);
+ void addModifier(const QString &factoryName);
protected:
- bool eventFilter(QObject *obj, QEvent *ev);
- void changeEvent(QEvent *event);
+ bool eventFilter(QObject *obj, QEvent *ev);
+ void changeEvent(QEvent *event);
- core::Modifier *currentModifier() const;
- virtual void setConfigWidget(QWidget *widget) = 0;
- virtual void currentModifierChanged(core::Modifier *modifier) {};
+ core::Modifier *currentModifier() const;
+ virtual void setConfigWidget(QWidget *widget) = 0;
+ virtual void currentModifierChanged(core::Modifier *modifier) {};
private:
- core::ModifierConfigWidget *_configWidget;
- QMenu menuAddModifier;
- QSignalMapper signalMapperAddModifier;
+ core::ModifierConfigWidget *_configWidget;
+ QMenu menuAddModifier;
+ QSignalMapper signalMapperAddModifier;
- ModifierManager *_modifierManager;
- ModifierModel *_modifierModel;
+ ModifierManager *_modifierManager;
+ ModifierModel *_modifierModel;
- QRect modifierStateRect(const QModelIndex &index) const;
- QRect modifierOnlyRect(const QModelIndex &index) const;
+ QRect modifierStateRect(const QModelIndex &index) const;
+ QRect modifierOnlyRect(const QModelIndex &index) const;
- void retranslate();
+ void retranslate();
private slots:
- void on_pushButtonRemove_clicked();
- void on_pushButtonUp_clicked();
- void on_pushButtonDown_clicked();
- void aboutToShowAddModifierMenu();
- void currentModifierChanged(const QModelIndex ¤t, const QModelIndex &previous);
- void widgetModifierChanged();
- void modifiersInserted(const QModelIndex &parent, int start, int end);
+ void on_pushButtonRemove_clicked();
+ void on_pushButtonUp_clicked();
+ void on_pushButtonDown_clicked();
+ void aboutToShowAddModifierMenu();
+ void currentModifierChanged(const QModelIndex ¤t, const QModelIndex &previous);
+ void widgetModifierChanged();
+ void modifiersInserted(const QModelIndex &parent, int start, int end);
};
#endif
diff --git a/renamah/widget_simple.cpp b/renamah/widget_simple.cpp
index d3839e6..3de77e0 100644
--- a/renamah/widget_simple.cpp
+++ b/renamah/widget_simple.cpp
@@ -1,311 +1,311 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QFileDialog>
#include <QMessageBox>
#include <QHeaderView>
#include <QKeyEvent>
#include <QMouseEvent>
#include <interfaces/filter_factory.h>
#include "file_model.h"
#include "filter_model.h"
#include "filter_manager.h"
#include "processor.h"
#include "finalizer_model.h"
#include "action_manager.h"
#include "dialog_manual_rename.h"
#include "widget_simple.h"
WidgetSimple::WidgetSimple(QWidget *parent)
- : uiRetranslating(false), QWidget(parent) {
- setupUi(this);
-
- menuSort = new QMenu(this);
- pushButtonSort->setMenu(menuSort);
- menuSort->addAction(actionSortByName);
- menuSort->addAction(actionSortByModificationDate);
-
- // Filters
- widgetFilters->init(&FilterManager::instance(), FilterModel::instance());
- connect(&FilterModel::instance(), SIGNAL(modifiersChanged()),
- &FileModel::instance(), SLOT(invalidate()));
- refreshFileCount();
-
- // Finalizers
- widgetFinalizers->init(&ActionManager::instance(), FinalizerModel::instance());
- connect(&FinalizerModel::instance(), SIGNAL(modifiersChanged()),
- &FileModel::instance(), SLOT(invalidate()));
-
- // Files
- treeViewFiles->setModel(&FileModel::instance());
- treeViewFiles->header()->resizeSection(0, width() / 2);
- connect(&FileModel::instance(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
- this, SLOT(filesInserted(const QModelIndex &, int, int)));
- connect(&FileModel::instance(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
- this, SLOT(filesRemoved(const QModelIndex &, int, int)));
- connect(&FileModel::instance(), SIGNAL(modelReset()),
- this, SLOT(filesModelReset()));
- connect(&FileModel::instance(), SIGNAL(dropDone()),
- this, SLOT(filesDropDone()));
- connect(treeViewFiles->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
- this, SLOT(treeViewFilesSelectionChanged(const QItemSelection &, const QItemSelection &)));
-
- treeViewFiles->installEventFilter(this);
- treeViewFiles->viewport()->installEventFilter(this);
-
- labelAddFiles->installEventFilter(this);
-
- on_comboBoxOperation_currentIndexChanged(0);
-
- tabWidgetOperations->setCurrentWidget(tabFilters);
-
- widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
- connect(widgetExtensionPolicy, SIGNAL(extensionPolicyChanged()),
- this, SLOT(generalExtensionPolicyChanged()));
-
- QList<int> sizes;
- sizes << 0 << 260;
- splitter->setSizes(sizes);
+ : uiRetranslating(false), QWidget(parent) {
+ setupUi(this);
+
+ menuSort = new QMenu(this);
+ pushButtonSort->setMenu(menuSort);
+ menuSort->addAction(actionSortByName);
+ menuSort->addAction(actionSortByModificationDate);
+
+ // Filters
+ widgetFilters->init(&FilterManager::instance(), FilterModel::instance());
+ connect(&FilterModel::instance(), SIGNAL(modifiersChanged()),
+ &FileModel::instance(), SLOT(invalidate()));
+ refreshFileCount();
+
+ // Finalizers
+ widgetFinalizers->init(&ActionManager::instance(), FinalizerModel::instance());
+ connect(&FinalizerModel::instance(), SIGNAL(modifiersChanged()),
+ &FileModel::instance(), SLOT(invalidate()));
+
+ // Files
+ treeViewFiles->setModel(&FileModel::instance());
+ treeViewFiles->header()->resizeSection(0, width() / 2);
+ connect(&FileModel::instance(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
+ this, SLOT(filesInserted(const QModelIndex &, int, int)));
+ connect(&FileModel::instance(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
+ this, SLOT(filesRemoved(const QModelIndex &, int, int)));
+ connect(&FileModel::instance(), SIGNAL(modelReset()),
+ this, SLOT(filesModelReset()));
+ connect(&FileModel::instance(), SIGNAL(dropDone()),
+ this, SLOT(filesDropDone()));
+ connect(treeViewFiles->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
+ this, SLOT(treeViewFilesSelectionChanged(const QItemSelection &, const QItemSelection &)));
+
+ treeViewFiles->installEventFilter(this);
+ treeViewFiles->viewport()->installEventFilter(this);
+
+ labelAddFiles->installEventFilter(this);
+
+ on_comboBoxOperation_currentIndexChanged(0);
+
+ tabWidgetOperations->setCurrentWidget(tabFilters);
+
+ widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
+ connect(widgetExtensionPolicy, SIGNAL(extensionPolicyChanged()),
+ this, SLOT(generalExtensionPolicyChanged()));
+
+ QList<int> sizes;
+ sizes << 0 << 260;
+ splitter->setSizes(sizes);
}
void WidgetSimple::initAfterPluginLoaded() {
widgetFilters->addModifier("date");
widgetFilters->addModifier("cutter");
widgetFilters->addModifier("numbering");
-// widgetFinalizers->addModifier("command");
+ // widgetFinalizers->addModifier("command");
// TEMP : Fill with some files
foreach (const QFileInfo &fileInfo, QDir::home().entryInfoList(QDir::Files))
FileModel::instance().addFile(fileInfo.absoluteFilePath());
if (FileModel::instance().rowCount())
stackedWidgetFiles->setCurrentWidget(pageFiles);
}
void WidgetSimple::on_pushButtonProcess_clicked() {
- // Fill processor with tasks
- Processor::instance().clearTasks();
- for (int row = 0; row < FileModel::instance().rowCount(); ++row)
- {
- QString original = FileModel::instance().originalFileName(FileModel::instance().index(row, 0));
- QString renamed = FilterModel::instance().apply(original, row);
- if (renamed != original)
- Processor::instance().addTask(original, FilterModel::instance().apply(original, row));
- }
-
- if (!Processor::instance().hasTasks() ||
- QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to start the rename process?"),
- QMessageBox::Yes | QMessageBox::Cancel) != QMessageBox::Yes)
- return;
-
- Processor::instance().go();
+ // Fill processor with tasks
+ Processor::instance().clearTasks();
+ for (int row = 0; row < FileModel::instance().rowCount(); ++row)
+ {
+ QString original = FileModel::instance().originalFileName(FileModel::instance().index(row, 0));
+ QString renamed = FilterModel::instance().apply(original, row);
+ if (renamed != original)
+ Processor::instance().addTask(original, FilterModel::instance().apply(original, row));
+ }
+
+ if (!Processor::instance().hasTasks() ||
+ QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to start the rename process?"),
+ QMessageBox::Yes | QMessageBox::Cancel) != QMessageBox::Yes)
+ return;
+
+ Processor::instance().go();
}
void WidgetSimple::on_comboBoxOperation_currentIndexChanged(int index) {
- if (uiRetranslating)
- return;
-
- switch (index)
- {
- case 0:
- lineEditDestination->setEnabled(false);
- toolButtonDestination->setEnabled(false);
- Processor::instance().setDestinationOperation(Processor::Rename);
- break;
- default:
- lineEditDestination->setEnabled(true);
- toolButtonDestination->setEnabled(true);
- switch (index)
- {
- case 1:
- Processor::instance().setDestinationOperation(Processor::Copy);
- break;
- case 2:
- Processor::instance().setDestinationOperation(Processor::Move);
- break;
- case 3:
- Processor::instance().setDestinationOperation(Processor::SymLink);
- break;
- default:;
- }
- if (lineEditDestination->text() == "")
- on_toolButtonDestination_clicked();
- }
+ if (uiRetranslating)
+ return;
+
+ switch (index)
+ {
+ case 0:
+ lineEditDestination->setEnabled(false);
+ toolButtonDestination->setEnabled(false);
+ Processor::instance().setDestinationOperation(Processor::Rename);
+ break;
+ default:
+ lineEditDestination->setEnabled(true);
+ toolButtonDestination->setEnabled(true);
+ switch (index)
+ {
+ case 1:
+ Processor::instance().setDestinationOperation(Processor::Copy);
+ break;
+ case 2:
+ Processor::instance().setDestinationOperation(Processor::Move);
+ break;
+ case 3:
+ Processor::instance().setDestinationOperation(Processor::SymLink);
+ break;
+ default:;
+ }
+ if (lineEditDestination->text() == "")
+ on_toolButtonDestination_clicked();
+ }
}
void WidgetSimple::on_toolButtonDestination_clicked() {
- QString dirName = "";
- if (QDir(lineEditDestination->text()).exists())
- dirName = lineEditDestination->text();
+ QString dirName = "";
+ if (QDir(lineEditDestination->text()).exists())
+ dirName = lineEditDestination->text();
- dirName = QFileDialog::getExistingDirectory(this, tr("Choose a destination directory"), dirName);
- if (dirName == "")
- return;
+ dirName = QFileDialog::getExistingDirectory(this, tr("Choose a destination directory"), dirName);
+ if (dirName == "")
+ return;
- lineEditDestination->setText(dirName);
+ lineEditDestination->setText(dirName);
- Processor::instance().setDestinationDir(dirName);
+ Processor::instance().setDestinationDir(dirName);
}
void WidgetSimple::refreshFileCount() {
- labelFileCount->setText(tr("%n files", "", FileModel::instance().rowCount()));
+ labelFileCount->setText(tr("%n files", "", FileModel::instance().rowCount()));
}
void WidgetSimple::generalExtensionPolicyChanged() {
- FilterModel::instance().setExtensionPolicy(widgetExtensionPolicy->extensionPolicy());
+ FilterModel::instance().setExtensionPolicy(widgetExtensionPolicy->extensionPolicy());
}
bool WidgetSimple::eventFilter(QObject *watched, QEvent *event) {
- if (watched == treeViewFiles && event->type() == QEvent::KeyPress) {
- QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
- if (keyEvent->key() == Qt::Key_Delete)
- on_pushButtonRemoveFiles_clicked();
- } else if (watched == treeViewFiles->viewport() && event->type() == QEvent::MouseButtonDblClick) {
- QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
- if (mouseEvent->button() == Qt::LeftButton)
- modifyCurrentFileName();
- } else if (watched == labelAddFiles && event->type() == QEvent::MouseButtonPress) {
- actionAddFiles->trigger();
- }
- return QWidget::eventFilter(watched, event);
+ if (watched == treeViewFiles && event->type() == QEvent::KeyPress) {
+ QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
+ if (keyEvent->key() == Qt::Key_Delete)
+ on_pushButtonRemoveFiles_clicked();
+ } else if (watched == treeViewFiles->viewport() && event->type() == QEvent::MouseButtonDblClick) {
+ QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
+ if (mouseEvent->button() == Qt::LeftButton)
+ modifyCurrentFileName();
+ } else if (watched == labelAddFiles && event->type() == QEvent::MouseButtonPress) {
+ actionAddFiles->trigger();
+ }
+ return QWidget::eventFilter(watched, event);
}
void WidgetSimple::modifyCurrentFileName() {
- QModelIndex index = treeViewFiles->currentIndex();
- if (!index.isValid())
- return;
-
- QDir dir = QFileInfo(FileModel::instance().originalFileName(index)).absoluteDir();
-
- DialogManualRename dialog(this);
- dialog.init(QFileInfo(FileModel::instance().originalFileName(index)).fileName(),
- QFileInfo(FileModel::instance().renamedFileName(index)).fileName());
- if (dialog.exec() != QDialog::Accepted)
- return;
-
- if (dialog.automaticRename())
- FileModel::instance().removeManualRenaming(index);
- else
- FileModel::instance().setManualRenaming(index, dir.absoluteFilePath(dialog.fileName()));
+ QModelIndex index = treeViewFiles->currentIndex();
+ if (!index.isValid())
+ return;
+
+ QDir dir = QFileInfo(FileModel::instance().originalFileName(index)).absoluteDir();
+
+ DialogManualRename dialog(this);
+ dialog.init(QFileInfo(FileModel::instance().originalFileName(index)).fileName(),
+ QFileInfo(FileModel::instance().renamedFileName(index)).fileName());
+ if (dialog.exec() != QDialog::Accepted)
+ return;
+
+ if (dialog.automaticRename())
+ FileModel::instance().removeManualRenaming(index);
+ else
+ FileModel::instance().setManualRenaming(index, dir.absoluteFilePath(dialog.fileName()));
}
void WidgetSimple::changeEvent(QEvent *event) {
- if (event->type() == QEvent::LanguageChange) {
- // Operation combobox
- uiRetranslating = true;
- int oldOperationCurrentIndex = comboBoxOperation->currentIndex();
- retranslateUi(this);
- comboBoxOperation->setCurrentIndex(oldOperationCurrentIndex);
- uiRetranslating = false;
-
- refreshFileCount();
- } else
- QWidget::changeEvent(event);
+ if (event->type() == QEvent::LanguageChange) {
+ // Operation combobox
+ uiRetranslating = true;
+ int oldOperationCurrentIndex = comboBoxOperation->currentIndex();
+ retranslateUi(this);
+ comboBoxOperation->setCurrentIndex(oldOperationCurrentIndex);
+ uiRetranslating = false;
+
+ refreshFileCount();
+ } else
+ QWidget::changeEvent(event);
}
void WidgetSimple::newProfile() {
- widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
- widgetFilters->newProfile();
- widgetFinalizers->newProfile();
+ widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
+ widgetFilters->newProfile();
+ widgetFinalizers->newProfile();
}
void WidgetSimple::filesDropDone() {
- int i = 0;
- foreach (int row, FileModel::instance().dropRows()) {
- QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select | QItemSelectionModel::Rows;
- treeViewFiles->selectionModel()->select(FileModel::instance().index(row, 0), i ? flags : QItemSelectionModel::Clear | flags);
- i++;
- }
+ int i = 0;
+ foreach (int row, FileModel::instance().dropRows()) {
+ QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select | QItemSelectionModel::Rows;
+ treeViewFiles->selectionModel()->select(FileModel::instance().index(row, 0), i ? flags : QItemSelectionModel::Clear | flags);
+ i++;
+ }
}
void WidgetSimple::on_actionSortByName_triggered() {
- FileModel::instance().sort(FileModel::SortByName);
+ FileModel::instance().sort(FileModel::SortByName);
}
void WidgetSimple::on_actionSortByModificationDate_triggered() {
- FileModel::instance().sort(FileModel::SortByModificationDate);
+ FileModel::instance().sort(FileModel::SortByModificationDate);
}
void WidgetSimple::on_actionRemoveSelectedFiles_triggered() {
- QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
- if (!list.count())
- return;
+ QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
+ if (!list.count())
+ return;
- if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this files?"),
- QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
- return;
+ if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this files?"),
+ QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
+ return;
- QMap<int, int> rowsAndHeights;
+ QMap<int, int> rowsAndHeights;
- foreach (const QItemSelectionRange &range, treeViewFiles->selectionModel()->selection())
- rowsAndHeights.insert(range.top(), range.height());
+ foreach (const QItemSelectionRange &range, treeViewFiles->selectionModel()->selection())
+ rowsAndHeights.insert(range.top(), range.height());
- QList<int> rows = rowsAndHeights.keys();
- for (int i = rows.count() - 1; i >= 0; --i)
- FileModel::instance().removeRows(rows[i], rowsAndHeights[rows[i]], QModelIndex());
+ QList<int> rows = rowsAndHeights.keys();
+ for (int i = rows.count() - 1; i >= 0; --i)
+ FileModel::instance().removeRows(rows[i], rowsAndHeights[rows[i]], QModelIndex());
- if (!FileModel::instance().rowCount())
- stackedWidgetFiles->setCurrentWidget(pageNoFiles);
+ if (!FileModel::instance().rowCount())
+ stackedWidgetFiles->setCurrentWidget(pageNoFiles);
}
void WidgetSimple::on_actionAddFiles_triggered() {
QStringList files = QFileDialog::getOpenFileNames(this, tr("Pick some files"),
- QDir::home().absolutePath());
+ QDir::home().absolutePath());
foreach (const QString &file, files)
- FileModel::instance().addFile(file);
+ FileModel::instance().addFile(file);
- if (FileModel::instance().rowCount())
- stackedWidgetFiles->setCurrentWidget(pageFiles);
+ if (FileModel::instance().rowCount())
+ stackedWidgetFiles->setCurrentWidget(pageFiles);
}
void WidgetSimple::contextMenuEvent(QContextMenuEvent *event) {
- QMenu popupMenu;
- popupMenu.addAction(actionAddFiles);
- if (treeViewFiles->selectionModel()->selectedRows().count()) {
- popupMenu.addAction(actionRemoveSelectedFiles);
- popupMenu.addSeparator();
- popupMenu.addAction(actionUpSelectedFiles);
- popupMenu.addAction(actionDownSelectedFiles);
- }
-
- popupMenu.exec(event->globalPos());
+ QMenu popupMenu;
+ popupMenu.addAction(actionAddFiles);
+ if (treeViewFiles->selectionModel()->selectedRows().count()) {
+ popupMenu.addAction(actionRemoveSelectedFiles);
+ popupMenu.addSeparator();
+ popupMenu.addAction(actionUpSelectedFiles);
+ popupMenu.addAction(actionDownSelectedFiles);
+ }
+
+ popupMenu.exec(event->globalPos());
}
void WidgetSimple::treeViewFilesSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) {
- pushButtonRemoveFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
- pushButtonUpFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
- pushButtonDownFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
+ pushButtonRemoveFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
+ pushButtonUpFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
+ pushButtonDownFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
}
void WidgetSimple::on_actionUpSelectedFiles_triggered() {
- QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
- if (list.count()) {
- FileModel::instance().upRows(list);
- filesDropDone();
- }
+ QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
+ if (list.count()) {
+ FileModel::instance().upRows(list);
+ filesDropDone();
+ }
}
void WidgetSimple::on_actionDownSelectedFiles_triggered() {
- QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
- if (list.count()) {
- FileModel::instance().downRows(list);
- filesDropDone();
- }
+ QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
+ if (list.count()) {
+ FileModel::instance().downRows(list);
+ filesDropDone();
+ }
}
diff --git a/renamah/widget_simple.h b/renamah/widget_simple.h
index dff7494..ebed657 100644
--- a/renamah/widget_simple.h
+++ b/renamah/widget_simple.h
@@ -1,75 +1,75 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef WIDGET_SIMPLE_H
#define WIDGET_SIMPLE_H
#include <QMenu>
#include <interfaces/filter.h>
#include <interfaces/action.h>
#include <interfaces/modifier_config_widget.h>
#include "ui_widget_simple.h"
class WidgetSimple : public QWidget, private Ui::WidgetSimple
{
- Q_OBJECT
+ Q_OBJECT
public:
- WidgetSimple(QWidget *parent = 0);
+ WidgetSimple(QWidget *parent = 0);
- void initAfterPluginLoaded();
- /*! Called after each profile loaded */
- void newProfile();
+ void initAfterPluginLoaded();
+ /*! Called after each profile loaded */
+ void newProfile();
protected:
- bool eventFilter(QObject *watched, QEvent *event);
- void changeEvent(QEvent *event);
- void contextMenuEvent(QContextMenuEvent *event);
+ bool eventFilter(QObject *watched, QEvent *event);
+ void changeEvent(QEvent *event);
+ void contextMenuEvent(QContextMenuEvent *event);
private:
- int uiRetranslating;
- QMenu *menuSort;
+ int uiRetranslating;
+ QMenu *menuSort;
- void refreshFileCount();
- void modifyCurrentFileName();
+ void refreshFileCount();
+ void modifyCurrentFileName();
private slots:
- void on_pushButtonAddFiles_clicked() { actionAddFiles->trigger(); }
- void on_pushButtonRemoveFiles_clicked() { actionRemoveSelectedFiles->trigger(); }
- void on_pushButtonUpFiles_clicked() { actionUpSelectedFiles->trigger(); }
- void on_pushButtonDownFiles_clicked() { actionDownSelectedFiles->trigger(); }
- void on_pushButtonProcess_clicked();
- void on_comboBoxOperation_currentIndexChanged(int index);
- void on_toolButtonDestination_clicked();
- void filesInserted(const QModelIndex &, int, int) { refreshFileCount(); }
- void filesRemoved(const QModelIndex &, int, int) { refreshFileCount(); }
- void filesModelReset() { refreshFileCount(); }
- void filesDropDone();
- void generalExtensionPolicyChanged();
- void on_actionSortByName_triggered();
- void on_actionSortByModificationDate_triggered();
- void on_actionRemoveSelectedFiles_triggered();
- void on_actionAddFiles_triggered();
- void on_actionUpSelectedFiles_triggered();
- void on_actionDownSelectedFiles_triggered();
- void treeViewFilesSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
+ void on_pushButtonAddFiles_clicked() { actionAddFiles->trigger(); }
+ void on_pushButtonRemoveFiles_clicked() { actionRemoveSelectedFiles->trigger(); }
+ void on_pushButtonUpFiles_clicked() { actionUpSelectedFiles->trigger(); }
+ void on_pushButtonDownFiles_clicked() { actionDownSelectedFiles->trigger(); }
+ void on_pushButtonProcess_clicked();
+ void on_comboBoxOperation_currentIndexChanged(int index);
+ void on_toolButtonDestination_clicked();
+ void filesInserted(const QModelIndex &, int, int) { refreshFileCount(); }
+ void filesRemoved(const QModelIndex &, int, int) { refreshFileCount(); }
+ void filesModelReset() { refreshFileCount(); }
+ void filesDropDone();
+ void generalExtensionPolicyChanged();
+ void on_actionSortByName_triggered();
+ void on_actionSortByModificationDate_triggered();
+ void on_actionRemoveSelectedFiles_triggered();
+ void on_actionAddFiles_triggered();
+ void on_actionUpSelectedFiles_triggered();
+ void on_actionDownSelectedFiles_triggered();
+ void treeViewFilesSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
};
#endif
|
Guid75/renamah
|
1f6341822e38d7678cb63dc55074bf2d293d3187
|
QT_NO_DEBUG is removed from definitions because it becomes useless with CMAKE_BUILD_TYPE
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 41d21f1..ca5a253 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,37 +1,43 @@
PROJECT(RENAMAH)
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)
FIND_PACKAGE(Qt4 REQUIRED)
INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/libcore)
option (UPDATE_TRANSLATIONS "Update source translation translations/*.ts files (WARNING: make clean will delete the source .ts files! Danger!)"
"off")
option (NO_OBSOLETE_TRANSLATIONS "Remove all obsolete translations in *.ts files. This options will work only when UPDATE_TRANSLATIONS is on"
"off")
# Use: COMPUTE_QT_FILES(QM_FILES ${SOURCE_FILES} ${TRANSLATIONS_FILES})
MACRO(COMPUTE_QM_FILES QM_FILES)
FILE (GLOB TRANSLATION_FILES translations/*.ts)
if (UPDATE_TRANSLATIONS)
if (NO_OBSOLETE_TRANSLATIONS)
QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES} OPTIONS -noobsolete)
else (NO_OBSOLETE_TRANSLATIONS)
QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES})
endif (NO_OBSOLETE_TRANSLATIONS)
else (UPDATE_TRANSLATIONS)
QT4_ADD_TRANSLATION(${QM_FILES} ${TRANSLATION_FILES})
endif (UPDATE_TRANSLATIONS)
ENDMACRO(COMPUTE_QM_FILES)
+ADD_CUSTOM_COMMAND(
+ PRE_BUILD
+ TARGET dev
+ COMMAND touch ARGS ${PROJECT_BINARY_DIR}/dev
+)
+
ADD_SUBDIRECTORY(libcore)
ADD_SUBDIRECTORY(plugins)
ADD_SUBDIRECTORY(renamah)
#INSTALL(DIRECTORY share/renamah
# DESTINATION share)
INSTALL(DIRECTORY lib/renamah
DESTINATION lib)
diff --git a/README b/README
index f3c0078..4f17d93 100644
--- a/README
+++ b/README
@@ -1,48 +1,50 @@
--------
WELCOME!
--------
Renamah is a(nother) batch renamer written in C++.
The effort is oriented toward:
* ergonomy
* the crossplatform aspect (Qt4)
* modularity (plugin system for filters)
Featuring:
* cascading filters: replace, numbering, cutter, case manipulations, etc
* cascading finalizers: launching of a system command for each files, etc
* undo system
* internationalization (French and English for now)
--------------------
INSTALL INSTRUCTIONS
--------------------
In the renamah root directory, type:
cmake .
make
sudo make install
+If you just want to execute renamah from the generated build dir in the source directory, just create an empty file named "dev" beside the binary.
+
------------
DEPENDENCIES
------------
To be successfully compiled, Renamah depends on some libraries:
- libqt4-core
- libqt4-gui
- libqt4-xml
------------
THE END WORD
------------
You can find Renamah homepage at: http://github.com/Guid75/renamah
Thank you for using it!
Guillaume Denry <guillaume.denry@gmail.com>
diff --git a/libcore/CMakeLists.txt b/libcore/CMakeLists.txt
index 84ee1ab..e312852 100644
--- a/libcore/CMakeLists.txt
+++ b/libcore/CMakeLists.txt
@@ -1,42 +1,40 @@
INCLUDE(${QT_USE_FILE})
SET(LIBCORE_SOURCES
interfaces/modifier_config_widget.cpp
interfaces/modifier.cpp
)
-SET(LIBCORE_FORMS
-)
+SET(LIBCORE_FORMS)
QT4_WRAP_UI(LIBCORE_FORMS_H ${LIBCORE_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(LIBCORE_MOCH
interfaces/modifier_config_widget.h
interfaces/modifier.h
interfaces/filter.h
interfaces/action.h
)
-ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
ADD_DEFINITIONS(-DRENAMAH_LIBCORE_LIBRARY)
QT4_WRAP_CPP(LIBCORE_MOC ${LIBCORE_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
ADD_LIBRARY(renamahcore SHARED ${LIBCORE_SOURCES} ${LIBCORE_FORMS_H} ${LIBCORE_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(renamahcore ${QT_LIBRARIES})
ENDIF(MSVC)
INSTALL(TARGETS renamahcore
LIBRARY DESTINATION lib)
diff --git a/libcore/interfaces/modifier_factory.h b/libcore/interfaces/modifier_factory.h
index 92a7df1..323e999 100644
--- a/libcore/interfaces/modifier_factory.h
+++ b/libcore/interfaces/modifier_factory.h
@@ -1,51 +1,51 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef MODIFIER_FACTORY_H
#define MODIFIER_FACTORY_H
#include "global.h"
#include "plugin.h"
#include "modifier.h"
#include "modifier_config_widget.h"
namespace core
{
class ModifierFactory : public Plugin
{
public:
- /*! Make a new modifier. Just a call to createModifier() and some parentality done */
+ /*! Make a new modifier. Just a call to createModifier() and some parentality don */
Modifier *makeModifier() const {
Modifier *modifier = createModifier();
modifier->_factory = const_cast<ModifierFactory*>(this);
return modifier;
}
/*! Returns a configuration QWidget */
virtual ModifierConfigWidget *makeConfigurationWidget(Modifier *modifier) const { return 0; }
/*! Deletes the configuration widget in argument (mandatory for shared lib) */
virtual void deleteConfigurationWidget(QWidget *widget) const { delete widget; }
protected:
/*! True method to create a new modifier */
virtual Modifier *createModifier() const = 0;
};
};
#endif
diff --git a/plugins/casefilter/CMakeLists.txt b/plugins/casefilter/CMakeLists.txt
index bbc17e9..b485ed4 100644
--- a/plugins/casefilter/CMakeLists.txt
+++ b/plugins/casefilter/CMakeLists.txt
@@ -1,46 +1,44 @@
INCLUDE(${QT_USE_FILE})
SET(CASEFILTER_SOURCES
case_filter_factory.cpp
case_filter.cpp
config_widget.cpp
)
SET(CASEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CASEFILTER_FORMS_H ${CASEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CASEFILTER_MOCH
case_filter.h
case_filter_factory.h
config_widget.h
)
-ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
-
QT4_WRAP_CPP(CASEFILTER_MOC ${CASEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS} ${CASEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_casefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(casefilter SHARED ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS_H} ${CASEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(casefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(casefilter translations_casefilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/commandaction/CMakeLists.txt b/plugins/commandaction/CMakeLists.txt
index 32ebd8d..8c8f5fc 100644
--- a/plugins/commandaction/CMakeLists.txt
+++ b/plugins/commandaction/CMakeLists.txt
@@ -1,50 +1,48 @@
INCLUDE(${QT_USE_FILE})
SET(COMMANDACTION_SOURCES
command_action_factory.cpp
command_action.cpp
config_widget.cpp
process_handler.cpp
)
SET(COMMANDACTION_FORMS
config_widget.ui
)
QT4_WRAP_UI(COMMANDACTION_FORMS_H ${COMMANDACTION_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(COMMANDACTION_MOCH
command_action.h
command_action_factory.h
config_widget.h
process_handler.h
)
-ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
-
QT4_WRAP_CPP(COMMANDACTION_MOC ${COMMANDACTION_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS} ${COMMANDACTION_MOCH})
ADD_CUSTOM_TARGET(translations_commandaction DEPENDS ${QM_FILES})
ADD_LIBRARY(commandaction SHARED ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(commandaction core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(commandaction translations_commandaction)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/cutterfilter/CMakeLists.txt b/plugins/cutterfilter/CMakeLists.txt
index add5327..3b9cda5 100644
--- a/plugins/cutterfilter/CMakeLists.txt
+++ b/plugins/cutterfilter/CMakeLists.txt
@@ -1,45 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(CUTTERFILTER_SOURCES
cutter_filter_factory.cpp
cutter_filter.cpp
config_widget.cpp
)
SET(CUTTERFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CUTTERFILTER_FORMS_H ${CUTTERFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CUTTERFILTER_MOCH
cutter_filter.h
cutter_filter_factory.h
config_widget.h
)
-ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
-
QT4_WRAP_CPP(CUTTERFILTER_MOC ${CUTTERFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS} ${CUTTERFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_cutterfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(cutterfilter SHARED ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS_H} ${CUTTERFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(cutterfilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(cutterfilter translations_cutterfilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/datefilter/CMakeLists.txt b/plugins/datefilter/CMakeLists.txt
index 6711838..8721b98 100644
--- a/plugins/datefilter/CMakeLists.txt
+++ b/plugins/datefilter/CMakeLists.txt
@@ -1,47 +1,45 @@
INCLUDE(${QT_USE_FILE})
SET(DATEFILTER_SOURCES
date_filter_factory.cpp
date_filter.cpp
config_widget.cpp
)
SET(DATEFILTER_FORMS
config_widget.ui
help_widget.ui
)
QT4_WRAP_UI(DATEFILTER_FORMS_H ${DATEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(DATEFILTER_MOCH
date_filter.h
date_filter_factory.h
config_widget.h
)
-ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
-
QT4_WRAP_CPP(DATEFILTER_MOC ${DATEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS} ${DATEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_datefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(datefilter SHARED ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS_H} ${DATEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(datefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(datefilter translations_datefilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/numberingfilter/CMakeLists.txt b/plugins/numberingfilter/CMakeLists.txt
index 353c05a..20a905d 100644
--- a/plugins/numberingfilter/CMakeLists.txt
+++ b/plugins/numberingfilter/CMakeLists.txt
@@ -1,45 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(NUMBERINGFILTER_SOURCES
numbering_filter_factory.cpp
numbering_filter.cpp
config_widget.cpp
)
SET(NUMBERINGFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(NUMBERINGFILTER_FORMS_H ${NUMBERINGFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(NUMBERINGFILTER_MOCH
numbering_filter.h
numbering_filter_factory.h
config_widget.h
)
-ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
-
QT4_WRAP_CPP(NUMBERINGFILTER_MOC ${NUMBERINGFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS} ${NUMBERINGFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_numberingfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(numberingfilter SHARED ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS_H} ${NUMBERINGFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(numberingfilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(numberingfilter translations_numberingfilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/plugins/replacefilter/CMakeLists.txt b/plugins/replacefilter/CMakeLists.txt
index f41e5cf..07c3953 100644
--- a/plugins/replacefilter/CMakeLists.txt
+++ b/plugins/replacefilter/CMakeLists.txt
@@ -1,45 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(REPLACEFILTER_SOURCES
replace_filter_factory.cpp
replace_filter.cpp
config_widget.cpp
)
SET(REPLACEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(REPLACEFILTER_FORMS_H ${REPLACEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(REPLACEFILTER_MOCH
replace_filter.h
replace_filter_factory.h
config_widget.h
)
-ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
-
QT4_WRAP_CPP(REPLACEFILTER_MOC ${REPLACEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS} ${REPLACEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_replacefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(replacefilter SHARED ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS_H} ${REPLACEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(replacefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(replacefilter translations_replacefilter)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/plugins)
diff --git a/renamah/CMakeLists.txt b/renamah/CMakeLists.txt
index e53c579..add9b19 100644
--- a/renamah/CMakeLists.txt
+++ b/renamah/CMakeLists.txt
@@ -1,112 +1,112 @@
SET(QT_USE_QTXML TRUE)
# SET(QT_USE_QTNETWORK TRUE)
INCLUDE(${QT_USE_FILE})
+INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
+
SET(RENAMAH_SOURCES
main.cpp
main_window.cpp
form_twinning.cpp
simple_dir_model.cpp
twinning_widget.cpp
widget_simple.cpp
file_model.cpp
filter_model.cpp
filter_manager.cpp
plugin_manager.cpp
form_last_operations.cpp
task_manager.cpp
modifier_delegate.cpp
led_widget.cpp
processor.cpp
widget_modifiers.cpp
modifier_manager.cpp
modifier_model.cpp
finalizer_model.cpp
action_manager.cpp
widget_extension_policy.cpp
extension_policy.cpp
widget_filters.cpp
widget_actions.cpp
dialog_manual_rename.cpp
profile.cpp
undo_manager.cpp
global.cpp
paths.cpp
)
SET(RENAMAH_FORMS
main_window.ui
form_twinning.ui
widget_simple.ui
form_last_operations.ui
widget_modifiers.ui
widget_extension_policy.ui
dialog_manual_rename.ui
)
QT4_WRAP_UI(RENAMAH_FORMS_H ${RENAMAH_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/staticlibs)
SET(RENAMAH_MOCH
main_window.h
form_twinning.h
simple_dir_model.h
twinning_widget.h
widget_simple.h
file_model.h
filter_model.h
form_last_operations.h
modifier_delegate.h
led_widget.h
processor.h
widget_modifiers.h
modifier_model.h
finalizer_model.h
widget_extension_policy.h
widget_filters.h
widget_actions.h
dialog_manual_rename.h
undo_manager.h
)
# Translations stuff
COMPUTE_QM_FILES(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH})
ADD_CUSTOM_TARGET(translations_renamah DEPENDS ${QM_FILES})
-ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
-
QT4_WRAP_CPP(RENAMAH_MOC ${RENAMAH_MOCH})
QT4_ADD_RESOURCES(RENAMAH_RES renamah.qrc)
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
ADD_EXECUTABLE(renamah ${RENAMAH_SOURCES} ${RENAMAH_FORMS_H} ${RENAMAH_MOC} ${RENAMAH_RES})
ADD_DEPENDENCIES(renamah translations_renamah)
TARGET_LINK_LIBRARIES(
renamah renamahcore ${QT_LIBRARIES}
)
INSTALL(TARGETS renamah
RUNTIME DESTINATION bin)
INSTALL(FILES ${QM_FILES}
DESTINATION share/renamah/)
#INSTALL(DIRECTORY share/applications
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
#INSTALL(DIRECTORY share/pixmaps
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
|
Guid75/renamah
|
457056440d7c589ab1fa58a45b8226c916cb3043
|
fix for new buid directory (QtCreator adaptation)
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 95996dd..41d21f1 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,39 +1,37 @@
PROJECT(RENAMAH)
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)
FIND_PACKAGE(Qt4 REQUIRED)
-include_directories(
- ${RENAMAH_BINARY_DIR}/libcore
- )
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/libcore)
option (UPDATE_TRANSLATIONS "Update source translation translations/*.ts files (WARNING: make clean will delete the source .ts files! Danger!)"
"off")
option (NO_OBSOLETE_TRANSLATIONS "Remove all obsolete translations in *.ts files. This options will work only when UPDATE_TRANSLATIONS is on"
"off")
# Use: COMPUTE_QT_FILES(QM_FILES ${SOURCE_FILES} ${TRANSLATIONS_FILES})
MACRO(COMPUTE_QM_FILES QM_FILES)
FILE (GLOB TRANSLATION_FILES translations/*.ts)
if (UPDATE_TRANSLATIONS)
if (NO_OBSOLETE_TRANSLATIONS)
QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES} OPTIONS -noobsolete)
else (NO_OBSOLETE_TRANSLATIONS)
QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES})
endif (NO_OBSOLETE_TRANSLATIONS)
else (UPDATE_TRANSLATIONS)
QT4_ADD_TRANSLATION(${QM_FILES} ${TRANSLATION_FILES})
endif (UPDATE_TRANSLATIONS)
ENDMACRO(COMPUTE_QM_FILES)
ADD_SUBDIRECTORY(libcore)
ADD_SUBDIRECTORY(plugins)
ADD_SUBDIRECTORY(renamah)
#INSTALL(DIRECTORY share/renamah
# DESTINATION share)
INSTALL(DIRECTORY lib/renamah
DESTINATION lib)
diff --git a/renamah/widget_simple.cpp b/renamah/widget_simple.cpp
index 86256a5..d3839e6 100644
--- a/renamah/widget_simple.cpp
+++ b/renamah/widget_simple.cpp
@@ -1,311 +1,311 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QFileDialog>
#include <QMessageBox>
#include <QHeaderView>
#include <QKeyEvent>
#include <QMouseEvent>
#include <interfaces/filter_factory.h>
#include "file_model.h"
#include "filter_model.h"
#include "filter_manager.h"
#include "processor.h"
#include "finalizer_model.h"
#include "action_manager.h"
#include "dialog_manual_rename.h"
#include "widget_simple.h"
WidgetSimple::WidgetSimple(QWidget *parent)
: uiRetranslating(false), QWidget(parent) {
setupUi(this);
menuSort = new QMenu(this);
pushButtonSort->setMenu(menuSort);
menuSort->addAction(actionSortByName);
menuSort->addAction(actionSortByModificationDate);
// Filters
widgetFilters->init(&FilterManager::instance(), FilterModel::instance());
connect(&FilterModel::instance(), SIGNAL(modifiersChanged()),
&FileModel::instance(), SLOT(invalidate()));
refreshFileCount();
// Finalizers
widgetFinalizers->init(&ActionManager::instance(), FinalizerModel::instance());
connect(&FinalizerModel::instance(), SIGNAL(modifiersChanged()),
&FileModel::instance(), SLOT(invalidate()));
// Files
treeViewFiles->setModel(&FileModel::instance());
treeViewFiles->header()->resizeSection(0, width() / 2);
connect(&FileModel::instance(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
this, SLOT(filesInserted(const QModelIndex &, int, int)));
connect(&FileModel::instance(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
this, SLOT(filesRemoved(const QModelIndex &, int, int)));
connect(&FileModel::instance(), SIGNAL(modelReset()),
this, SLOT(filesModelReset()));
connect(&FileModel::instance(), SIGNAL(dropDone()),
this, SLOT(filesDropDone()));
connect(treeViewFiles->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(treeViewFilesSelectionChanged(const QItemSelection &, const QItemSelection &)));
treeViewFiles->installEventFilter(this);
treeViewFiles->viewport()->installEventFilter(this);
labelAddFiles->installEventFilter(this);
on_comboBoxOperation_currentIndexChanged(0);
tabWidgetOperations->setCurrentWidget(tabFilters);
widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
connect(widgetExtensionPolicy, SIGNAL(extensionPolicyChanged()),
this, SLOT(generalExtensionPolicyChanged()));
QList<int> sizes;
sizes << 0 << 260;
splitter->setSizes(sizes);
}
void WidgetSimple::initAfterPluginLoaded() {
widgetFilters->addModifier("date");
widgetFilters->addModifier("cutter");
widgetFilters->addModifier("numbering");
// widgetFinalizers->addModifier("command");
- // TEMP : Fill with some files
- foreach (const QFileInfo &fileInfo, QDir::home().entryInfoList(QDir::Files))
- FileModel::instance().addFile(fileInfo.absoluteFilePath());
+ // TEMP : Fill with some files
+ foreach (const QFileInfo &fileInfo, QDir::home().entryInfoList(QDir::Files))
+ FileModel::instance().addFile(fileInfo.absoluteFilePath());
- if (FileModel::instance().rowCount())
- stackedWidgetFiles->setCurrentWidget(pageFiles);
+ if (FileModel::instance().rowCount())
+ stackedWidgetFiles->setCurrentWidget(pageFiles);
}
void WidgetSimple::on_pushButtonProcess_clicked() {
// Fill processor with tasks
Processor::instance().clearTasks();
for (int row = 0; row < FileModel::instance().rowCount(); ++row)
{
QString original = FileModel::instance().originalFileName(FileModel::instance().index(row, 0));
QString renamed = FilterModel::instance().apply(original, row);
if (renamed != original)
Processor::instance().addTask(original, FilterModel::instance().apply(original, row));
}
if (!Processor::instance().hasTasks() ||
QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to start the rename process?"),
QMessageBox::Yes | QMessageBox::Cancel) != QMessageBox::Yes)
return;
Processor::instance().go();
}
void WidgetSimple::on_comboBoxOperation_currentIndexChanged(int index) {
if (uiRetranslating)
return;
switch (index)
{
case 0:
lineEditDestination->setEnabled(false);
toolButtonDestination->setEnabled(false);
Processor::instance().setDestinationOperation(Processor::Rename);
break;
default:
lineEditDestination->setEnabled(true);
toolButtonDestination->setEnabled(true);
switch (index)
{
case 1:
Processor::instance().setDestinationOperation(Processor::Copy);
break;
case 2:
Processor::instance().setDestinationOperation(Processor::Move);
break;
case 3:
Processor::instance().setDestinationOperation(Processor::SymLink);
break;
default:;
}
if (lineEditDestination->text() == "")
on_toolButtonDestination_clicked();
}
}
void WidgetSimple::on_toolButtonDestination_clicked() {
QString dirName = "";
if (QDir(lineEditDestination->text()).exists())
dirName = lineEditDestination->text();
dirName = QFileDialog::getExistingDirectory(this, tr("Choose a destination directory"), dirName);
if (dirName == "")
return;
lineEditDestination->setText(dirName);
Processor::instance().setDestinationDir(dirName);
}
void WidgetSimple::refreshFileCount() {
labelFileCount->setText(tr("%n files", "", FileModel::instance().rowCount()));
}
void WidgetSimple::generalExtensionPolicyChanged() {
FilterModel::instance().setExtensionPolicy(widgetExtensionPolicy->extensionPolicy());
}
bool WidgetSimple::eventFilter(QObject *watched, QEvent *event) {
if (watched == treeViewFiles && event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Delete)
on_pushButtonRemoveFiles_clicked();
} else if (watched == treeViewFiles->viewport() && event->type() == QEvent::MouseButtonDblClick) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton)
modifyCurrentFileName();
} else if (watched == labelAddFiles && event->type() == QEvent::MouseButtonPress) {
actionAddFiles->trigger();
}
return QWidget::eventFilter(watched, event);
}
void WidgetSimple::modifyCurrentFileName() {
QModelIndex index = treeViewFiles->currentIndex();
if (!index.isValid())
return;
QDir dir = QFileInfo(FileModel::instance().originalFileName(index)).absoluteDir();
DialogManualRename dialog(this);
dialog.init(QFileInfo(FileModel::instance().originalFileName(index)).fileName(),
QFileInfo(FileModel::instance().renamedFileName(index)).fileName());
if (dialog.exec() != QDialog::Accepted)
return;
if (dialog.automaticRename())
FileModel::instance().removeManualRenaming(index);
else
FileModel::instance().setManualRenaming(index, dir.absoluteFilePath(dialog.fileName()));
}
void WidgetSimple::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
// Operation combobox
uiRetranslating = true;
int oldOperationCurrentIndex = comboBoxOperation->currentIndex();
retranslateUi(this);
comboBoxOperation->setCurrentIndex(oldOperationCurrentIndex);
uiRetranslating = false;
refreshFileCount();
} else
QWidget::changeEvent(event);
}
void WidgetSimple::newProfile() {
widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
widgetFilters->newProfile();
widgetFinalizers->newProfile();
}
void WidgetSimple::filesDropDone() {
int i = 0;
foreach (int row, FileModel::instance().dropRows()) {
QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select | QItemSelectionModel::Rows;
treeViewFiles->selectionModel()->select(FileModel::instance().index(row, 0), i ? flags : QItemSelectionModel::Clear | flags);
i++;
}
}
void WidgetSimple::on_actionSortByName_triggered() {
FileModel::instance().sort(FileModel::SortByName);
}
void WidgetSimple::on_actionSortByModificationDate_triggered() {
FileModel::instance().sort(FileModel::SortByModificationDate);
}
void WidgetSimple::on_actionRemoveSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (!list.count())
return;
if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this files?"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
QMap<int, int> rowsAndHeights;
foreach (const QItemSelectionRange &range, treeViewFiles->selectionModel()->selection())
rowsAndHeights.insert(range.top(), range.height());
QList<int> rows = rowsAndHeights.keys();
for (int i = rows.count() - 1; i >= 0; --i)
FileModel::instance().removeRows(rows[i], rowsAndHeights[rows[i]], QModelIndex());
if (!FileModel::instance().rowCount())
stackedWidgetFiles->setCurrentWidget(pageNoFiles);
}
void WidgetSimple::on_actionAddFiles_triggered() {
QStringList files = QFileDialog::getOpenFileNames(this, tr("Pick some files"),
QDir::home().absolutePath());
foreach (const QString &file, files)
FileModel::instance().addFile(file);
if (FileModel::instance().rowCount())
stackedWidgetFiles->setCurrentWidget(pageFiles);
}
void WidgetSimple::contextMenuEvent(QContextMenuEvent *event) {
QMenu popupMenu;
popupMenu.addAction(actionAddFiles);
if (treeViewFiles->selectionModel()->selectedRows().count()) {
popupMenu.addAction(actionRemoveSelectedFiles);
popupMenu.addSeparator();
popupMenu.addAction(actionUpSelectedFiles);
popupMenu.addAction(actionDownSelectedFiles);
}
popupMenu.exec(event->globalPos());
}
void WidgetSimple::treeViewFilesSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) {
pushButtonRemoveFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
pushButtonUpFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
pushButtonDownFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
}
void WidgetSimple::on_actionUpSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (list.count()) {
FileModel::instance().upRows(list);
filesDropDone();
}
}
void WidgetSimple::on_actionDownSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (list.count()) {
FileModel::instance().downRows(list);
filesDropDone();
}
}
|
Guid75/renamah
|
26d5666437e9570738a9105d232536e5b6935f84
|
New translation
|
diff --git a/renamah/translations/renamah_fr.ts b/renamah/translations/renamah_fr.ts
index a96e6a7..1b30304 100644
--- a/renamah/translations/renamah_fr.ts
+++ b/renamah/translations/renamah_fr.ts
@@ -1,471 +1,471 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>DialogManualRename</name>
<message>
<location filename="../dialog_manual_rename.cpp" line="45"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.cpp" line="45"/>
<source>Do you really want to set the original filename?</source>
<translatorcomment>bof</translatorcomment>
<translation>Ãtes-vous sûr de vouloir affecter le nom de fichier original ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation>Renommage manuel</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation>Retour au renommage automatique</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation>Valeur originale</translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
<location filename="../file_model.cpp" line="110"/>
<source>Original</source>
<translation>Original</translation>
</message>
<message>
<location filename="../file_model.cpp" line="111"/>
<source>Renamed</source>
<translation>Renommé</translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
<location filename="../form_twinning.cpp" line="208"/>
<source>Choose a directory for left files</source>
<translation>Choisissez un répertoire pour les fichiers de gauche</translation>
</message>
<message>
<location filename="../form_twinning.cpp" line="219"/>
<source>Choose a directory for right files</source>
<translation>Choisissez un répertoire pour les fichiers de droite</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
<translation>Extension :</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
<translation>*avi,*.mkv</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
<translation>Statut</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
<translation>lancer</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation></translation>
</message>
<message>
<location filename="../main_window.ui" line="28"/>
<source>Simple</source>
<translation>Simple</translation>
</message>
<message>
<location filename="../main_window.ui" line="41"/>
<source>Last operations</source>
<translation>Dernières opérations</translation>
</message>
<message>
<location filename="../main_window.ui" line="67"/>
<source>&File</source>
<translation>&Fichier</translation>
</message>
<message>
<location filename="../main_window.ui" line="76"/>
<source>&Settings</source>
- <translation></translation>
+ <translation>&Paramètres</translation>
</message>
<message>
<location filename="../main_window.ui" line="82"/>
<source>&Edit</source>
<translation>&Ãditer</translation>
</message>
<message>
<location filename="../main_window.ui" line="114"/>
<source>&Undo</source>
<translation>&Défaire</translation>
</message>
<message>
<location filename="../main_window.ui" line="117"/>
<source>Ctrl+Z</source>
<translation></translation>
</message>
<message>
<location filename="../main_window.ui" line="122"/>
<source>&Redo</source>
<translation>&Refaire</translation>
</message>
<message>
<source>Settings</source>
<translation type="obsolete">Paramètres</translation>
</message>
<message>
<location filename="../main_window.ui" line="94"/>
<source>&Quit</source>
<translation>&Quitter</translation>
</message>
<message>
<location filename="../main_window.ui" line="99"/>
<source>Language</source>
<translation>Langage</translation>
</message>
<message>
<location filename="../main_window.ui" line="104"/>
<source>&Load profile...</source>
<translation>&Charge un profile...</translation>
</message>
<message>
<location filename="../main_window.ui" line="109"/>
<source>&Save profile...</source>
<translation>&Sauver le profile...</translation>
</message>
<message>
<location filename="../main_window.cpp" line="145"/>
<source>Choose a profile to load</source>
<translation>Choisissez un profile à charger</translation>
</message>
<message>
<location filename="../main_window.cpp" line="157"/>
<source>Choose a profile filename to save in</source>
<translation>Choisissez un nom de profile à sauver</translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
<location filename="../modifier_model.cpp" line="75"/>
<source>#</source>
<translation></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="76"/>
<source>Mode</source>
<translation>Mode</translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="77"/>
<source>Action</source>
<translation>Action</translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
<location filename="../processor.cpp" line="145"/>
<source>Rename</source>
<translation>Renommer</translation>
</message>
<message>
<location filename="../processor.cpp" line="146"/>
<source>Copy</source>
<translation>Copier</translation>
</message>
<message>
<location filename="../processor.cpp" line="147"/>
<source>Move</source>
<translation>Déplacer</translation>
</message>
<message>
<location filename="../processor.cpp" line="148"/>
<source>Create link</source>
<translation>Créer un lien</translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
<location filename="../widget_extension_policy.cpp" line="141"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../widget_extension_policy.cpp" line="141"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation>Souhaitez-vous vraiment revenir à la politique d'extension par défaut ?</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation>Choisissez quelle partie des fichiers vous voulez renommer :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation>Le nom de base (sans l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation>Le nom de fichier en entier (avec l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation>Seulement l'extension</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation>Paramètres par défaut</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation>L'extension du fichier commence juste après le :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation>Premier point en partant de la droite</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation>Premier point en partant de la gauche</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation>ième point en partant de la droite</translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
<location filename="../widget_filters.cpp" line="57"/>
<source>General</source>
<translation>Général</translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="58"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="56"/>
<source>Override the global extension policy</source>
<translation>Supplanter la politique d'extension globale</translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
<location filename="../widget_modifiers.cpp" line="66"/>
<source>Add a new %1</source>
<translation>Ajouter un nouveau %1</translation>
</message>
<message>
<source>Confirmation</source>
<translation type="obsolete">Confirmation</translation>
</message>
<message>
<source>Do you really want to remove this filter?</source>
<translation type="obsolete">Voulez-vous réellement supprimer ce filtre ?</translation>
</message>
<message>
<location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation>Cliquez pour ajouter</translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
<location filename="../widget_simple.cpp" line="251"/>
<source>Confirmation</source>
<translation>Confirmation</translation>
</message>
<message>
<location filename="../widget_simple.cpp" line="251"/>
<source>Do you really want to remove this files?</source>
<translation>Ãtes-vous certain de vouloir supprimer ces fichiers ?</translation>
</message>
<message>
<location filename="../widget_simple.cpp" line="114"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../widget_simple.cpp" line="114"/>
<source>Do you really want to start the rename process?</source>
<translation>Voulez-vous vraiment démarrer le processus de renommage ?</translation>
</message>
<message>
<location filename="../widget_simple.cpp" line="158"/>
<source>Choose a destination directory</source>
<translation>Choisissez un répertoire de destination</translation>
</message>
<message numerus="yes">
<location filename="../widget_simple.cpp" line="168"/>
<source>%n files</source>
<translation>
<numerusform>%n fichier</numerusform>
<numerusform>%n fichiers</numerusform>
</translation>
</message>
<message>
<location filename="../widget_simple.cpp" line="269"/>
<source>Pick some files</source>
<translation>Choisissez des fichiers</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation>Lancer</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation>Renommage de fichier</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation>Copie renommée dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation>Déplacement renommé dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation>Création des liens dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="107"/>
<source>Add some files...</source>
<translation>Ajouter des fichiers...</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="330"/>
<source>Click to add some files</source>
<translation>Cliquer pour ajouter des fichiers</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="459"/>
<source>&Remove</source>
<translation>&Supprimer</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="471"/>
<source>&Add</source>
<translation>&Ajouter</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="474"/>
<source>Add files</source>
<translation>Ajouter des fichiers</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="483"/>
<source>&Up</source>
<translation>&Monter</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="495"/>
<source>&Down</source>
<translation>&Descendre</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="124"/>
<location filename="../widget_simple.ui" line="462"/>
<source>Remove selected files</source>
<translation>Supprimer les fichiers sélectionnés</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="442"/>
<source>by name</source>
<translation>par nom</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="445"/>
<source>Sort files by name</source>
<translation>Trier les fichier par nom</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="450"/>
<source>by modification date</source>
<translation>par date de modification</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="167"/>
<source>Sort by</source>
<translation>Trier par</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="177"/>
<location filename="../widget_simple.ui" line="486"/>
<source>Up selected files</source>
<translation>Monter les fichiers sélectionnés</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="194"/>
<location filename="../widget_simple.ui" line="498"/>
<source>Down selected files</source>
<translation>Descendre les fichiers sélectionnés</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="377"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="412"/>
<source>Filters</source>
<translation>Filtres</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="425"/>
<source>Finalizers</source>
<translation>Finaliseurs</translation>
</message>
</context>
</TS>
|
Guid75/renamah
|
a1d1959dcaa9282045fe3d089c0ff3af4d766ba9
|
Plugins translation files are read from the share path
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9f8c2d2..95996dd 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,39 +1,39 @@
PROJECT(RENAMAH)
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)
FIND_PACKAGE(Qt4 REQUIRED)
include_directories(
${RENAMAH_BINARY_DIR}/libcore
)
option (UPDATE_TRANSLATIONS "Update source translation translations/*.ts files (WARNING: make clean will delete the source .ts files! Danger!)"
"off")
-option (NO_OBSOLETE_TRANSLATIONS "Remove all obsolete translations in *.ts files. This options will work only when UPDATE_TRANSLATIONS i on"
+option (NO_OBSOLETE_TRANSLATIONS "Remove all obsolete translations in *.ts files. This options will work only when UPDATE_TRANSLATIONS is on"
"off")
# Use: COMPUTE_QT_FILES(QM_FILES ${SOURCE_FILES} ${TRANSLATIONS_FILES})
MACRO(COMPUTE_QM_FILES QM_FILES)
FILE (GLOB TRANSLATION_FILES translations/*.ts)
if (UPDATE_TRANSLATIONS)
if (NO_OBSOLETE_TRANSLATIONS)
QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES} OPTIONS -noobsolete)
else (NO_OBSOLETE_TRANSLATIONS)
QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES})
endif (NO_OBSOLETE_TRANSLATIONS)
else (UPDATE_TRANSLATIONS)
QT4_ADD_TRANSLATION(${QM_FILES} ${TRANSLATION_FILES})
endif (UPDATE_TRANSLATIONS)
ENDMACRO(COMPUTE_QM_FILES)
ADD_SUBDIRECTORY(libcore)
ADD_SUBDIRECTORY(plugins)
ADD_SUBDIRECTORY(renamah)
-INSTALL(DIRECTORY share/renamah
- DESTINATION share)
+#INSTALL(DIRECTORY share/renamah
+# DESTINATION share)
INSTALL(DIRECTORY lib/renamah
DESTINATION lib)
diff --git a/plugins/casefilter/CMakeLists.txt b/plugins/casefilter/CMakeLists.txt
index e0bc4cf..bbc17e9 100644
--- a/plugins/casefilter/CMakeLists.txt
+++ b/plugins/casefilter/CMakeLists.txt
@@ -1,43 +1,46 @@
INCLUDE(${QT_USE_FILE})
SET(CASEFILTER_SOURCES
case_filter_factory.cpp
case_filter.cpp
config_widget.cpp
)
SET(CASEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CASEFILTER_FORMS_H ${CASEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CASEFILTER_MOCH
case_filter.h
case_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CASEFILTER_MOC ${CASEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS} ${CASEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_casefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(casefilter SHARED ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS_H} ${CASEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(casefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(casefilter translations_casefilter)
+
+INSTALL(FILES ${QM_FILES}
+ DESTINATION share/renamah/plugins)
diff --git a/plugins/commandaction/CMakeLists.txt b/plugins/commandaction/CMakeLists.txt
index b5b399f..32ebd8d 100644
--- a/plugins/commandaction/CMakeLists.txt
+++ b/plugins/commandaction/CMakeLists.txt
@@ -1,47 +1,50 @@
INCLUDE(${QT_USE_FILE})
SET(COMMANDACTION_SOURCES
command_action_factory.cpp
command_action.cpp
config_widget.cpp
process_handler.cpp
)
SET(COMMANDACTION_FORMS
config_widget.ui
)
QT4_WRAP_UI(COMMANDACTION_FORMS_H ${COMMANDACTION_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(COMMANDACTION_MOCH
command_action.h
command_action_factory.h
config_widget.h
process_handler.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(COMMANDACTION_MOC ${COMMANDACTION_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS} ${COMMANDACTION_MOCH})
ADD_CUSTOM_TARGET(translations_commandaction DEPENDS ${QM_FILES})
ADD_LIBRARY(commandaction SHARED ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(commandaction core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(commandaction translations_commandaction)
+
+INSTALL(FILES ${QM_FILES}
+ DESTINATION share/renamah/plugins)
diff --git a/plugins/cutterfilter/CMakeLists.txt b/plugins/cutterfilter/CMakeLists.txt
index df9d659..add5327 100644
--- a/plugins/cutterfilter/CMakeLists.txt
+++ b/plugins/cutterfilter/CMakeLists.txt
@@ -1,42 +1,45 @@
INCLUDE(${QT_USE_FILE})
SET(CUTTERFILTER_SOURCES
cutter_filter_factory.cpp
cutter_filter.cpp
config_widget.cpp
)
SET(CUTTERFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CUTTERFILTER_FORMS_H ${CUTTERFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CUTTERFILTER_MOCH
cutter_filter.h
cutter_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CUTTERFILTER_MOC ${CUTTERFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS} ${CUTTERFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_cutterfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(cutterfilter SHARED ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS_H} ${CUTTERFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(cutterfilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(cutterfilter translations_cutterfilter)
+
+INSTALL(FILES ${QM_FILES}
+ DESTINATION share/renamah/plugins)
diff --git a/plugins/datefilter/CMakeLists.txt b/plugins/datefilter/CMakeLists.txt
index 869af4e..6711838 100644
--- a/plugins/datefilter/CMakeLists.txt
+++ b/plugins/datefilter/CMakeLists.txt
@@ -1,44 +1,47 @@
INCLUDE(${QT_USE_FILE})
SET(DATEFILTER_SOURCES
date_filter_factory.cpp
date_filter.cpp
config_widget.cpp
)
SET(DATEFILTER_FORMS
config_widget.ui
help_widget.ui
)
QT4_WRAP_UI(DATEFILTER_FORMS_H ${DATEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(DATEFILTER_MOCH
date_filter.h
date_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(DATEFILTER_MOC ${DATEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS} ${DATEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_datefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(datefilter SHARED ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS_H} ${DATEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(datefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(datefilter translations_datefilter)
+
+INSTALL(FILES ${QM_FILES}
+ DESTINATION share/renamah/plugins)
diff --git a/plugins/numberingfilter/CMakeLists.txt b/plugins/numberingfilter/CMakeLists.txt
index 4458dd9..353c05a 100644
--- a/plugins/numberingfilter/CMakeLists.txt
+++ b/plugins/numberingfilter/CMakeLists.txt
@@ -1,42 +1,45 @@
INCLUDE(${QT_USE_FILE})
SET(NUMBERINGFILTER_SOURCES
numbering_filter_factory.cpp
numbering_filter.cpp
config_widget.cpp
)
SET(NUMBERINGFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(NUMBERINGFILTER_FORMS_H ${NUMBERINGFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(NUMBERINGFILTER_MOCH
numbering_filter.h
numbering_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(NUMBERINGFILTER_MOC ${NUMBERINGFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS} ${NUMBERINGFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_numberingfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(numberingfilter SHARED ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS_H} ${NUMBERINGFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(numberingfilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(numberingfilter translations_numberingfilter)
+
+INSTALL(FILES ${QM_FILES}
+ DESTINATION share/renamah/plugins)
diff --git a/plugins/replacefilter/CMakeLists.txt b/plugins/replacefilter/CMakeLists.txt
index 7be0a8b..f41e5cf 100644
--- a/plugins/replacefilter/CMakeLists.txt
+++ b/plugins/replacefilter/CMakeLists.txt
@@ -1,42 +1,45 @@
INCLUDE(${QT_USE_FILE})
SET(REPLACEFILTER_SOURCES
replace_filter_factory.cpp
replace_filter.cpp
config_widget.cpp
)
SET(REPLACEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(REPLACEFILTER_FORMS_H ${REPLACEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(REPLACEFILTER_MOCH
replace_filter.h
replace_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(REPLACEFILTER_MOC ${REPLACEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS} ${REPLACEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_replacefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(replacefilter SHARED ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS_H} ${REPLACEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(replacefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(replacefilter translations_replacefilter)
+
+INSTALL(FILES ${QM_FILES}
+ DESTINATION share/renamah/plugins)
diff --git a/renamah/CMakeLists.txt b/renamah/CMakeLists.txt
index 5efbb75..e53c579 100644
--- a/renamah/CMakeLists.txt
+++ b/renamah/CMakeLists.txt
@@ -1,108 +1,112 @@
SET(QT_USE_QTXML TRUE)
# SET(QT_USE_QTNETWORK TRUE)
INCLUDE(${QT_USE_FILE})
SET(RENAMAH_SOURCES
main.cpp
main_window.cpp
form_twinning.cpp
simple_dir_model.cpp
twinning_widget.cpp
widget_simple.cpp
file_model.cpp
filter_model.cpp
filter_manager.cpp
plugin_manager.cpp
form_last_operations.cpp
task_manager.cpp
modifier_delegate.cpp
led_widget.cpp
processor.cpp
widget_modifiers.cpp
modifier_manager.cpp
modifier_model.cpp
finalizer_model.cpp
action_manager.cpp
widget_extension_policy.cpp
extension_policy.cpp
widget_filters.cpp
widget_actions.cpp
dialog_manual_rename.cpp
profile.cpp
undo_manager.cpp
global.cpp
paths.cpp
)
SET(RENAMAH_FORMS
main_window.ui
form_twinning.ui
widget_simple.ui
form_last_operations.ui
widget_modifiers.ui
widget_extension_policy.ui
dialog_manual_rename.ui
)
QT4_WRAP_UI(RENAMAH_FORMS_H ${RENAMAH_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/staticlibs)
SET(RENAMAH_MOCH
main_window.h
form_twinning.h
simple_dir_model.h
twinning_widget.h
widget_simple.h
file_model.h
filter_model.h
form_last_operations.h
modifier_delegate.h
led_widget.h
processor.h
widget_modifiers.h
modifier_model.h
finalizer_model.h
widget_extension_policy.h
widget_filters.h
widget_actions.h
dialog_manual_rename.h
undo_manager.h
)
# Translations stuff
COMPUTE_QM_FILES(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH})
ADD_CUSTOM_TARGET(translations_renamah DEPENDS ${QM_FILES})
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(RENAMAH_MOC ${RENAMAH_MOCH})
QT4_ADD_RESOURCES(RENAMAH_RES renamah.qrc)
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
ADD_EXECUTABLE(renamah ${RENAMAH_SOURCES} ${RENAMAH_FORMS_H} ${RENAMAH_MOC} ${RENAMAH_RES})
ADD_DEPENDENCIES(renamah translations_renamah)
TARGET_LINK_LIBRARIES(
renamah renamahcore ${QT_LIBRARIES}
)
INSTALL(TARGETS renamah
RUNTIME DESTINATION bin)
+
+INSTALL(FILES ${QM_FILES}
+ DESTINATION share/renamah/)
+
#INSTALL(DIRECTORY share/applications
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
#INSTALL(DIRECTORY share/pixmaps
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
diff --git a/renamah/main_window.cpp b/renamah/main_window.cpp
index e34697a..38b190a 100644
--- a/renamah/main_window.cpp
+++ b/renamah/main_window.cpp
@@ -1,171 +1,170 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QTranslator>
#include <QSettings>
#include <QLibraryInfo>
#include <QFileDialog>
#include <QShortcut>
#include "plugin_manager.h"
#include "filter_model.h"
#include "processor.h"
#include "profile.h"
#include "undo_manager.h"
#include "paths.h"
#include "main_window.h"
MainWindow::MainWindow(QWidget *parent)
: actionGroupLanguages(0),
QMainWindow(parent) {
setupUi(this);
PluginManager::instance().load();
tabWidgetMain->setCurrentWidget(tabSimple);
connect(&Processor::instance(), SIGNAL(started()), this, SLOT(processorStarted()));
widgetSimple->initAfterPluginLoaded();
actionLanguage->setMenu(&menuLanguages);
QSettings settings;
QString currentLanguage = settings.value("general/language", "").toString();
if (currentLanguage != "")
installLanguage(currentLanguage);
refreshLanguageActions();
connect(&signalMapperLanguages, SIGNAL(mapped(const QString &)),
this, SLOT(languageRequested(const QString &)));
}
void MainWindow::refreshLanguageActions() {
if (actionGroupLanguages)
delete actionGroupLanguages;
actionGroupLanguages = new QActionGroup(this);
menuLanguages.clear();
QAction *actionToCheck = 0;
QSettings settings;
QString currentLanguage = settings.value("general/language", "").toString();
// Get languages list
foreach (const QFileInfo &fileInfo, QDir(Paths::sharePath()).entryInfoList(QStringList() << "*.qm",
QDir::Files)) {
QString baseName = fileInfo.baseName();
int p = baseName.indexOf("_");
if (p > 0) {
QString fileLanguage = baseName.mid(p + 1, baseName.length() - p - 1);
QLocale locale(fileLanguage);
QString language = QLocale::languageToString(locale.language());
QString country = QLocale::countryToString(locale.country());
QAction *action = menuLanguages.addAction(QString("%1 (%2)").arg(language).arg(country));
if (fileLanguage == currentLanguage)
actionToCheck = action;
signalMapperLanguages.setMapping(action, fileLanguage);
connect(action, SIGNAL(triggered()), &signalMapperLanguages, SLOT(map()));
action->setCheckable(true);
actionGroupLanguages->addAction(action);
}
}
if (actionToCheck)
actionToCheck->setChecked(true);
}
void MainWindow::processorStarted() {
tabWidgetMain->setCurrentWidget(tabLastOperations);
}
void MainWindow::languageRequested(const QString &language) {
installLanguage(language);
QSettings settings;
settings.setValue("general/language", language);
}
void MainWindow::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi(this);
} else
QWidget::changeEvent(event);
}
void MainWindow::installLanguage(const QString &language) {
// Remove all existing translators
foreach (QTranslator *translator, translators)
qApp->removeTranslator(translator);
translators.clear();
// Install the Qt translator
QTranslator *qtTranslator = new QTranslator;
qtTranslator->load("qt_" + language,
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
qApp->installTranslator(qtTranslator);
// Install the main app translator
QTranslator *translator = new QTranslator;
translator->load("renamah_" + language,
Paths::sharePath());
qApp->installTranslator(translator);
translators << translator;
// Install all plugins translators
foreach (const QString &fileName, PluginManager::instance().pluginFileNames()) {
- QFileInfo fileInfo(fileName);
- QString baseName = fileInfo.completeBaseName();
- QString qmFileName = fileInfo.absoluteDir().filePath(baseName) + "_" + language + ".qm";
+ QString relativeFileName = QFileInfo(fileName).completeBaseName() + "_" + language + ".qm";
+ QString qmFileName = QDir(QDir(Paths::sharePath()).filePath("plugins")).filePath(relativeFileName);
QTranslator *translator = new QTranslator;
translator->load(qmFileName,
QCoreApplication::applicationDirPath());
qApp->installTranslator(translator);
translators << translator;
}
}
void MainWindow::on_actionLoadProfile_triggered() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a profile to load"),
QDir::home().absolutePath());
if (fileName == "")
return;
if (!Profile::load(fileName))
return;
widgetSimple->newProfile();
}
void MainWindow::on_actionSaveProfile_triggered() {
QString fileName = QFileDialog::getSaveFileName(this, tr("Choose a profile filename to save in"),
QDir::home().absolutePath());
if (fileName == "")
return;
Profile::save(fileName);
}
void MainWindow::on_actionUndo_triggered() {
UndoManager::instance().undo();
}
void MainWindow::on_actionRedo_triggered() {
UndoManager::instance().redo();
}
|
Guid75/renamah
|
81dfba2bd5d7c5b687b3a1ce651091fe29280d3f
|
new plugins reorganization
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 25d0257..9f8c2d2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,48 +1,39 @@
PROJECT(RENAMAH)
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)
FIND_PACKAGE(Qt4 REQUIRED)
include_directories(
${RENAMAH_BINARY_DIR}/libcore
)
option (UPDATE_TRANSLATIONS "Update source translation translations/*.ts files (WARNING: make clean will delete the source .ts files! Danger!)"
"off")
option (NO_OBSOLETE_TRANSLATIONS "Remove all obsolete translations in *.ts files. This options will work only when UPDATE_TRANSLATIONS i on"
"off")
# Use: COMPUTE_QT_FILES(QM_FILES ${SOURCE_FILES} ${TRANSLATIONS_FILES})
MACRO(COMPUTE_QM_FILES QM_FILES)
FILE (GLOB TRANSLATION_FILES translations/*.ts)
if (UPDATE_TRANSLATIONS)
if (NO_OBSOLETE_TRANSLATIONS)
QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES} OPTIONS -noobsolete)
else (NO_OBSOLETE_TRANSLATIONS)
QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES})
endif (NO_OBSOLETE_TRANSLATIONS)
else (UPDATE_TRANSLATIONS)
QT4_ADD_TRANSLATION(${QM_FILES} ${TRANSLATION_FILES})
endif (UPDATE_TRANSLATIONS)
ENDMACRO(COMPUTE_QM_FILES)
ADD_SUBDIRECTORY(libcore)
ADD_SUBDIRECTORY(plugins)
ADD_SUBDIRECTORY(renamah)
-# INSTALL(TARGETS renamah
-# RUNTIME DESTINATION bin)
-#INSTALL(DIRECTORY share/renamah
-# DESTINATION share
-# PATTERN .svn
-# EXCLUDE)
-#INSTALL(DIRECTORY share/applications
-# DESTINATION share
-# PATTERN .svn
-# EXCLUDE)
-#INSTALL(DIRECTORY share/pixmaps
-# DESTINATION share
-# PATTERN .svn
-# EXCLUDE)
+INSTALL(DIRECTORY share/renamah
+ DESTINATION share)
+
+INSTALL(DIRECTORY lib/renamah
+ DESTINATION lib)
diff --git a/libcore/CMakeLists.txt b/libcore/CMakeLists.txt
index e90fb19..84ee1ab 100644
--- a/libcore/CMakeLists.txt
+++ b/libcore/CMakeLists.txt
@@ -1,39 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(LIBCORE_SOURCES
interfaces/modifier_config_widget.cpp
interfaces/modifier.cpp
)
SET(LIBCORE_FORMS
)
QT4_WRAP_UI(LIBCORE_FORMS_H ${LIBCORE_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(LIBCORE_MOCH
interfaces/modifier_config_widget.h
interfaces/modifier.h
interfaces/filter.h
interfaces/action.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
ADD_DEFINITIONS(-DRENAMAH_LIBCORE_LIBRARY)
QT4_WRAP_CPP(LIBCORE_MOC ${LIBCORE_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
-ADD_LIBRARY(core SHARED ${LIBCORE_SOURCES} ${LIBCORE_FORMS_H} ${LIBCORE_MOC})
+ADD_LIBRARY(renamahcore SHARED ${LIBCORE_SOURCES} ${LIBCORE_FORMS_H} ${LIBCORE_MOC})
IF(MSVC)
- TARGET_LINK_LIBRARIES(core ${QT_LIBRARIES})
+ TARGET_LINK_LIBRARIES(renamahcore ${QT_LIBRARIES})
ENDIF(MSVC)
+
+INSTALL(TARGETS renamahcore
+ LIBRARY DESTINATION lib)
diff --git a/plugins/casefilter/CMakeLists.txt b/plugins/casefilter/CMakeLists.txt
index 62b40da..e0bc4cf 100644
--- a/plugins/casefilter/CMakeLists.txt
+++ b/plugins/casefilter/CMakeLists.txt
@@ -1,43 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(CASEFILTER_SOURCES
case_filter_factory.cpp
case_filter.cpp
config_widget.cpp
)
SET(CASEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CASEFILTER_FORMS_H ${CASEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CASEFILTER_MOCH
case_filter.h
case_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CASEFILTER_MOC ${CASEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS} ${CASEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_casefilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(casefilter SHARED ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS_H} ${CASEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(casefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(casefilter translations_casefilter)
diff --git a/plugins/commandaction/CMakeLists.txt b/plugins/commandaction/CMakeLists.txt
index d92bf4a..b5b399f 100644
--- a/plugins/commandaction/CMakeLists.txt
+++ b/plugins/commandaction/CMakeLists.txt
@@ -1,47 +1,47 @@
INCLUDE(${QT_USE_FILE})
SET(COMMANDACTION_SOURCES
command_action_factory.cpp
command_action.cpp
config_widget.cpp
process_handler.cpp
)
SET(COMMANDACTION_FORMS
config_widget.ui
)
QT4_WRAP_UI(COMMANDACTION_FORMS_H ${COMMANDACTION_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(COMMANDACTION_MOCH
command_action.h
command_action_factory.h
config_widget.h
process_handler.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(COMMANDACTION_MOC ${COMMANDACTION_MOCH})
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS} ${COMMANDACTION_MOCH})
ADD_CUSTOM_TARGET(translations_commandaction DEPENDS ${QM_FILES})
ADD_LIBRARY(commandaction SHARED ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(commandaction core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(commandaction translations_commandaction)
diff --git a/plugins/cutterfilter/CMakeLists.txt b/plugins/cutterfilter/CMakeLists.txt
index e70ba3c..df9d659 100644
--- a/plugins/cutterfilter/CMakeLists.txt
+++ b/plugins/cutterfilter/CMakeLists.txt
@@ -1,42 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(CUTTERFILTER_SOURCES
cutter_filter_factory.cpp
cutter_filter.cpp
config_widget.cpp
)
SET(CUTTERFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CUTTERFILTER_FORMS_H ${CUTTERFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CUTTERFILTER_MOCH
cutter_filter.h
cutter_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CUTTERFILTER_MOC ${CUTTERFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS} ${CUTTERFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_cutterfilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(cutterfilter SHARED ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS_H} ${CUTTERFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(cutterfilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(cutterfilter translations_cutterfilter)
diff --git a/plugins/datefilter/CMakeLists.txt b/plugins/datefilter/CMakeLists.txt
index e9afa2c..869af4e 100644
--- a/plugins/datefilter/CMakeLists.txt
+++ b/plugins/datefilter/CMakeLists.txt
@@ -1,44 +1,44 @@
INCLUDE(${QT_USE_FILE})
SET(DATEFILTER_SOURCES
date_filter_factory.cpp
date_filter.cpp
config_widget.cpp
)
SET(DATEFILTER_FORMS
config_widget.ui
help_widget.ui
)
QT4_WRAP_UI(DATEFILTER_FORMS_H ${DATEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(DATEFILTER_MOCH
date_filter.h
date_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(DATEFILTER_MOC ${DATEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS} ${DATEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_datefilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(datefilter SHARED ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS_H} ${DATEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(datefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(datefilter translations_datefilter)
diff --git a/plugins/numberingfilter/CMakeLists.txt b/plugins/numberingfilter/CMakeLists.txt
index 70c486d..4458dd9 100644
--- a/plugins/numberingfilter/CMakeLists.txt
+++ b/plugins/numberingfilter/CMakeLists.txt
@@ -1,42 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(NUMBERINGFILTER_SOURCES
numbering_filter_factory.cpp
numbering_filter.cpp
config_widget.cpp
)
SET(NUMBERINGFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(NUMBERINGFILTER_FORMS_H ${NUMBERINGFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(NUMBERINGFILTER_MOCH
numbering_filter.h
numbering_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(NUMBERINGFILTER_MOC ${NUMBERINGFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS} ${NUMBERINGFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_numberingfilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(numberingfilter SHARED ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS_H} ${NUMBERINGFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(numberingfilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(numberingfilter translations_numberingfilter)
diff --git a/plugins/replacefilter/CMakeLists.txt b/plugins/replacefilter/CMakeLists.txt
index 259cd2e..7be0a8b 100644
--- a/plugins/replacefilter/CMakeLists.txt
+++ b/plugins/replacefilter/CMakeLists.txt
@@ -1,42 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(REPLACEFILTER_SOURCES
replace_filter_factory.cpp
replace_filter.cpp
config_widget.cpp
)
SET(REPLACEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(REPLACEFILTER_FORMS_H ${REPLACEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(REPLACEFILTER_MOCH
replace_filter.h
replace_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(REPLACEFILTER_MOC ${REPLACEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS} ${REPLACEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_replacefilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/lib/renamah/plugins)
ADD_LIBRARY(replacefilter SHARED ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS_H} ${REPLACEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(replacefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(replacefilter translations_replacefilter)
diff --git a/renamah/CMakeLists.txt b/renamah/CMakeLists.txt
index d986cf3..5efbb75 100644
--- a/renamah/CMakeLists.txt
+++ b/renamah/CMakeLists.txt
@@ -1,96 +1,108 @@
SET(QT_USE_QTXML TRUE)
# SET(QT_USE_QTNETWORK TRUE)
INCLUDE(${QT_USE_FILE})
SET(RENAMAH_SOURCES
main.cpp
main_window.cpp
form_twinning.cpp
simple_dir_model.cpp
twinning_widget.cpp
widget_simple.cpp
file_model.cpp
filter_model.cpp
filter_manager.cpp
plugin_manager.cpp
form_last_operations.cpp
task_manager.cpp
modifier_delegate.cpp
led_widget.cpp
processor.cpp
widget_modifiers.cpp
modifier_manager.cpp
modifier_model.cpp
finalizer_model.cpp
action_manager.cpp
widget_extension_policy.cpp
extension_policy.cpp
widget_filters.cpp
widget_actions.cpp
dialog_manual_rename.cpp
profile.cpp
undo_manager.cpp
global.cpp
paths.cpp
)
SET(RENAMAH_FORMS
main_window.ui
form_twinning.ui
widget_simple.ui
form_last_operations.ui
widget_modifiers.ui
widget_extension_policy.ui
dialog_manual_rename.ui
)
QT4_WRAP_UI(RENAMAH_FORMS_H ${RENAMAH_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/staticlibs)
SET(RENAMAH_MOCH
main_window.h
form_twinning.h
simple_dir_model.h
twinning_widget.h
widget_simple.h
file_model.h
filter_model.h
form_last_operations.h
modifier_delegate.h
led_widget.h
processor.h
widget_modifiers.h
modifier_model.h
finalizer_model.h
widget_extension_policy.h
widget_filters.h
widget_actions.h
dialog_manual_rename.h
undo_manager.h
)
# Translations stuff
COMPUTE_QM_FILES(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH})
ADD_CUSTOM_TARGET(translations_renamah DEPENDS ${QM_FILES})
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(RENAMAH_MOC ${RENAMAH_MOCH})
QT4_ADD_RESOURCES(RENAMAH_RES renamah.qrc)
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
ADD_EXECUTABLE(renamah ${RENAMAH_SOURCES} ${RENAMAH_FORMS_H} ${RENAMAH_MOC} ${RENAMAH_RES})
ADD_DEPENDENCIES(renamah translations_renamah)
TARGET_LINK_LIBRARIES(
- renamah core ${QT_LIBRARIES}
+ renamah renamahcore ${QT_LIBRARIES}
)
+
+
+INSTALL(TARGETS renamah
+ RUNTIME DESTINATION bin)
+#INSTALL(DIRECTORY share/applications
+# DESTINATION share
+# PATTERN .svn
+# EXCLUDE)
+#INSTALL(DIRECTORY share/pixmaps
+# DESTINATION share
+# PATTERN .svn
+# EXCLUDE)
diff --git a/renamah/paths.cpp b/renamah/paths.cpp
index c9fe4df..36268ed 100644
--- a/renamah/paths.cpp
+++ b/renamah/paths.cpp
@@ -1,52 +1,71 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QDir>
#include <QCoreApplication>
#include <QDesktopServices>
#include "global.h"
#include "paths.h"
QString Paths::sharePath()
{
QDir appDir(QCoreApplication::applicationDirPath());
if (Global::devMode()) {
return QDir(appDir.filePath("../share/renamah")).canonicalPath();
}
if (Global::localMode())
return appDir.absolutePath();
#if defined(Q_OS_LINUX)
return QDir(appDir.filePath("/usr/share/renamah")).canonicalPath();
#else
return appDir.absolutePath();
#endif
}
+QString Paths::libPath()
+{
+ QDir appDir(QCoreApplication::applicationDirPath());
+
+ if (Global::devMode()) {
+ return QDir(appDir.filePath("../lib/renamah")).canonicalPath();
+ }
+
+ if (Global::localMode())
+ return appDir.absolutePath();
+
+
+#if defined(Q_OS_LINUX)
+ return QDir(appDir.filePath("/usr/lib/renamah")).canonicalPath();
+#else
+ return appDir.absolutePath();
+#endif
+}
+
QString Paths::profilePath()
{
if (Global::devMode() || Global::localMode())
return QDir(QCoreApplication::applicationDirPath()).filePath(qApp->applicationName());
return QDesktopServices::storageLocation(QDesktopServices::DataLocation);
}
diff --git a/renamah/paths.h b/renamah/paths.h
index 2249390..69f7fca 100644
--- a/renamah/paths.h
+++ b/renamah/paths.h
@@ -1,30 +1,31 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef PATHS_H
#define PATHS_H
#include <QString>
namespace Paths
{
QString sharePath();
+ QString libPath();
QString profilePath();
};
#endif
diff --git a/renamah/plugin_manager.cpp b/renamah/plugin_manager.cpp
index bdcb2c4..98f657f 100644
--- a/renamah/plugin_manager.cpp
+++ b/renamah/plugin_manager.cpp
@@ -1,82 +1,82 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QPluginLoader>
#include <QDir>
#include <QCoreApplication>
#include <interfaces/filter.h>
#include <interfaces/filter_factory.h>
#include <interfaces/action_factory.h>
#include "filter_manager.h"
#include "action_manager.h"
#include "paths.h"
#include "plugin_manager.h"
PluginManager *PluginManager::_instance = 0;
PluginManager &PluginManager::instance()
{
if (!_instance)
_instance = new PluginManager;
return *_instance;
}
void PluginManager::load()
{
// Static plugins
foreach (QObject *plugin, QPluginLoader::staticInstances())
dispatchPlugin(plugin);
// Dynamic plugins
- QDir pluginsDir(QDir(Paths::sharePath()).filePath("plugins"));
+ QDir pluginsDir(QDir(Paths::libPath()).filePath("plugins"));
foreach (const QString &fileName, pluginsDir.entryList(QDir::Files))
{
if (QLibrary::isLibrary(fileName)) {
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader.instance();
if (plugin) {
dispatchPlugin(plugin);
_pluginFileNames << pluginsDir.absoluteFilePath(fileName);
}
else
qDebug("Error: %s", qPrintable(loader.errorString()));
}
}
}
void PluginManager::dispatchPlugin(QObject *plugin)
{
Q_ASSERT_X(plugin, "PluginManager::dispatchPlugin()", "<plugin> is 0!");
core::ModifierFactory *factory = qobject_cast<core::FilterFactory*>(plugin);
if (factory)
{
FilterManager::instance().addFactory(factory);
return;
}
factory = qobject_cast<core::ActionFactory*>(plugin);
if (factory)
{
ActionManager::instance().addFactory(factory);
return;
}
}
|
Guid75/renamah
|
3c5c35baff9da4a0a0f95b791dcbd7ca607e7855
|
New translations
|
diff --git a/renamah/main_window.cpp b/renamah/main_window.cpp
index 9e72670..e34697a 100644
--- a/renamah/main_window.cpp
+++ b/renamah/main_window.cpp
@@ -1,171 +1,171 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QTranslator>
#include <QSettings>
#include <QLibraryInfo>
#include <QFileDialog>
#include <QShortcut>
#include "plugin_manager.h"
#include "filter_model.h"
#include "processor.h"
#include "profile.h"
#include "undo_manager.h"
#include "paths.h"
#include "main_window.h"
MainWindow::MainWindow(QWidget *parent)
: actionGroupLanguages(0),
QMainWindow(parent) {
setupUi(this);
PluginManager::instance().load();
tabWidgetMain->setCurrentWidget(tabSimple);
connect(&Processor::instance(), SIGNAL(started()), this, SLOT(processorStarted()));
widgetSimple->initAfterPluginLoaded();
actionLanguage->setMenu(&menuLanguages);
QSettings settings;
QString currentLanguage = settings.value("general/language", "").toString();
if (currentLanguage != "")
installLanguage(currentLanguage);
refreshLanguageActions();
connect(&signalMapperLanguages, SIGNAL(mapped(const QString &)),
this, SLOT(languageRequested(const QString &)));
}
void MainWindow::refreshLanguageActions() {
if (actionGroupLanguages)
delete actionGroupLanguages;
actionGroupLanguages = new QActionGroup(this);
menuLanguages.clear();
QAction *actionToCheck = 0;
QSettings settings;
QString currentLanguage = settings.value("general/language", "").toString();
// Get languages list
- foreach (const QFileInfo &fileInfo, QDir(QCoreApplication::applicationDirPath()).entryInfoList(QStringList() << "*.qm",
- QDir::Files)) {
+ foreach (const QFileInfo &fileInfo, QDir(Paths::sharePath()).entryInfoList(QStringList() << "*.qm",
+ QDir::Files)) {
QString baseName = fileInfo.baseName();
int p = baseName.indexOf("_");
if (p > 0) {
QString fileLanguage = baseName.mid(p + 1, baseName.length() - p - 1);
QLocale locale(fileLanguage);
QString language = QLocale::languageToString(locale.language());
QString country = QLocale::countryToString(locale.country());
QAction *action = menuLanguages.addAction(QString("%1 (%2)").arg(language).arg(country));
if (fileLanguage == currentLanguage)
actionToCheck = action;
signalMapperLanguages.setMapping(action, fileLanguage);
connect(action, SIGNAL(triggered()), &signalMapperLanguages, SLOT(map()));
action->setCheckable(true);
actionGroupLanguages->addAction(action);
}
}
if (actionToCheck)
actionToCheck->setChecked(true);
}
void MainWindow::processorStarted() {
tabWidgetMain->setCurrentWidget(tabLastOperations);
}
void MainWindow::languageRequested(const QString &language) {
installLanguage(language);
QSettings settings;
settings.setValue("general/language", language);
}
void MainWindow::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi(this);
} else
QWidget::changeEvent(event);
}
void MainWindow::installLanguage(const QString &language) {
// Remove all existing translators
foreach (QTranslator *translator, translators)
qApp->removeTranslator(translator);
translators.clear();
// Install the Qt translator
QTranslator *qtTranslator = new QTranslator;
qtTranslator->load("qt_" + language,
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
qApp->installTranslator(qtTranslator);
// Install the main app translator
QTranslator *translator = new QTranslator;
translator->load("renamah_" + language,
Paths::sharePath());
qApp->installTranslator(translator);
translators << translator;
// Install all plugins translators
foreach (const QString &fileName, PluginManager::instance().pluginFileNames()) {
QFileInfo fileInfo(fileName);
QString baseName = fileInfo.completeBaseName();
QString qmFileName = fileInfo.absoluteDir().filePath(baseName) + "_" + language + ".qm";
QTranslator *translator = new QTranslator;
translator->load(qmFileName,
QCoreApplication::applicationDirPath());
qApp->installTranslator(translator);
translators << translator;
}
}
void MainWindow::on_actionLoadProfile_triggered() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a profile to load"),
QDir::home().absolutePath());
if (fileName == "")
return;
if (!Profile::load(fileName))
return;
widgetSimple->newProfile();
}
void MainWindow::on_actionSaveProfile_triggered() {
QString fileName = QFileDialog::getSaveFileName(this, tr("Choose a profile filename to save in"),
QDir::home().absolutePath());
if (fileName == "")
return;
Profile::save(fileName);
}
void MainWindow::on_actionUndo_triggered() {
UndoManager::instance().undo();
}
void MainWindow::on_actionRedo_triggered() {
UndoManager::instance().redo();
}
diff --git a/renamah/translations/renamah_en_US.ts b/renamah/translations/renamah_en_US.ts
index 7e310cf..1fac9f8 100644
--- a/renamah/translations/renamah_en_US.ts
+++ b/renamah/translations/renamah_en_US.ts
@@ -1,447 +1,457 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
<name>DialogManualRename</name>
<message>
- <location filename="../dialog_manual_rename.cpp" line="27"/>
+ <location filename="../dialog_manual_rename.cpp" line="45"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../dialog_manual_rename.cpp" line="27"/>
+ <location filename="../dialog_manual_rename.cpp" line="45"/>
<source>Do you really want to set the original filename?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
- <location filename="../file_model.cpp" line="92"/>
+ <location filename="../file_model.cpp" line="110"/>
<source>Original</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../file_model.cpp" line="93"/>
+ <location filename="../file_model.cpp" line="111"/>
<source>Renamed</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
- <location filename="../form_twinning.cpp" line="190"/>
+ <location filename="../form_twinning.cpp" line="208"/>
<source>Choose a directory for left files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../form_twinning.cpp" line="201"/>
+ <location filename="../form_twinning.cpp" line="219"/>
<source>Choose a directory for right files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.ui" line="25"/>
+ <location filename="../main_window.ui" line="28"/>
<source>Simple</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.ui" line="38"/>
+ <location filename="../main_window.ui" line="41"/>
<source>Last operations</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.ui" line="64"/>
+ <location filename="../main_window.ui" line="67"/>
<source>&File</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.ui" line="73"/>
- <source>Settings</source>
+ <location filename="../main_window.ui" line="76"/>
+ <source>&Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.ui" line="83"/>
+ <location filename="../main_window.ui" line="82"/>
+ <source>&Edit</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../main_window.ui" line="114"/>
+ <source>&Undo</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../main_window.ui" line="117"/>
+ <source>Ctrl+Z</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../main_window.ui" line="122"/>
+ <source>&Redo</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../main_window.ui" line="94"/>
<source>&Quit</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.ui" line="88"/>
+ <location filename="../main_window.ui" line="99"/>
<source>Language</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.ui" line="93"/>
+ <location filename="../main_window.ui" line="104"/>
<source>&Load profile...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.ui" line="98"/>
+ <location filename="../main_window.ui" line="109"/>
<source>&Save profile...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.cpp" line="124"/>
+ <location filename="../main_window.cpp" line="145"/>
<source>Choose a profile to load</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../main_window.cpp" line="136"/>
+ <location filename="../main_window.cpp" line="157"/>
<source>Choose a profile filename to save in</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
- <location filename="../modifier_model.cpp" line="54"/>
+ <location filename="../modifier_model.cpp" line="75"/>
<source>#</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../modifier_model.cpp" line="55"/>
+ <location filename="../modifier_model.cpp" line="76"/>
<source>Mode</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../modifier_model.cpp" line="56"/>
+ <location filename="../modifier_model.cpp" line="77"/>
<source>Action</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
- <location filename="../processor.cpp" line="127"/>
+ <location filename="../processor.cpp" line="145"/>
<source>Rename</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../processor.cpp" line="128"/>
+ <location filename="../processor.cpp" line="146"/>
<source>Copy</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../processor.cpp" line="129"/>
+ <location filename="../processor.cpp" line="147"/>
<source>Move</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../processor.cpp" line="130"/>
+ <location filename="../processor.cpp" line="148"/>
<source>Create link</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
- <location filename="../widget_extension_policy.cpp" line="123"/>
+ <location filename="../widget_extension_policy.cpp" line="141"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_extension_policy.cpp" line="123"/>
+ <location filename="../widget_extension_policy.cpp" line="141"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
- <location filename="../widget_filters.cpp" line="38"/>
+ <location filename="../widget_filters.cpp" line="56"/>
<source>Override the global extension policy</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_filters.cpp" line="39"/>
+ <location filename="../widget_filters.cpp" line="57"/>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_filters.cpp" line="40"/>
+ <location filename="../widget_filters.cpp" line="58"/>
<source>Extension policy</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
- <location filename="../widget_modifiers.cpp" line="48"/>
+ <location filename="../widget_modifiers.cpp" line="66"/>
<source>Add a new %1</source>
<translation type="unfinished"></translation>
</message>
- <message>
- <location filename="../widget_modifiers.cpp" line="65"/>
- <source>Confirmation</source>
- <translation type="unfinished"></translation>
- </message>
- <message>
- <location filename="../widget_modifiers.cpp" line="65"/>
- <source>Do you really want to remove this filter?</source>
- <translation type="unfinished"></translation>
- </message>
<message>
<location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
- <location filename="../widget_simple.cpp" line="233"/>
+ <location filename="../widget_simple.cpp" line="251"/>
<source>Confirmation</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="233"/>
+ <location filename="../widget_simple.cpp" line="251"/>
<source>Do you really want to remove this files?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="96"/>
+ <location filename="../widget_simple.cpp" line="114"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="96"/>
+ <location filename="../widget_simple.cpp" line="114"/>
<source>Do you really want to start the rename process?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="140"/>
+ <location filename="../widget_simple.cpp" line="158"/>
<source>Choose a destination directory</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
- <location filename="../widget_simple.cpp" line="150"/>
+ <location filename="../widget_simple.cpp" line="168"/>
<source>%n files</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="251"/>
+ <location filename="../widget_simple.cpp" line="269"/>
<source>Pick some files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="107"/>
<source>Add some files...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="124"/>
<location filename="../widget_simple.ui" line="462"/>
<source>Remove selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="167"/>
<source>Sort by</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="177"/>
<location filename="../widget_simple.ui" line="486"/>
<source>Up selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="194"/>
<location filename="../widget_simple.ui" line="498"/>
<source>Down selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="330"/>
<source>Click to add some files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="377"/>
<source>Extension policy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="412"/>
<source>Filters</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="425"/>
<source>Finalizers</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="442"/>
<source>by name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="445"/>
<source>Sort files by name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="450"/>
<source>by modification date</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="459"/>
<source>&Remove</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="471"/>
<source>&Add</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="474"/>
<source>Add files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="483"/>
<source>&Up</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="495"/>
<source>&Down</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
diff --git a/renamah/translations/renamah_fr.ts b/renamah/translations/renamah_fr.ts
index 7577268..a96e6a7 100644
--- a/renamah/translations/renamah_fr.ts
+++ b/renamah/translations/renamah_fr.ts
@@ -1,449 +1,471 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>DialogManualRename</name>
<message>
- <location filename="../dialog_manual_rename.cpp" line="27"/>
+ <location filename="../dialog_manual_rename.cpp" line="45"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
- <location filename="../dialog_manual_rename.cpp" line="27"/>
+ <location filename="../dialog_manual_rename.cpp" line="45"/>
<source>Do you really want to set the original filename?</source>
<translatorcomment>bof</translatorcomment>
<translation>Ãtes-vous sûr de vouloir affecter le nom de fichier original ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation>Renommage manuel</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation>Retour au renommage automatique</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation>Valeur originale</translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
- <location filename="../file_model.cpp" line="92"/>
+ <location filename="../file_model.cpp" line="110"/>
<source>Original</source>
<translation>Original</translation>
</message>
<message>
- <location filename="../file_model.cpp" line="93"/>
+ <location filename="../file_model.cpp" line="111"/>
<source>Renamed</source>
<translation>Renommé</translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
- <location filename="../form_twinning.cpp" line="190"/>
+ <location filename="../form_twinning.cpp" line="208"/>
<source>Choose a directory for left files</source>
<translation>Choisissez un répertoire pour les fichiers de gauche</translation>
</message>
<message>
- <location filename="../form_twinning.cpp" line="201"/>
+ <location filename="../form_twinning.cpp" line="219"/>
<source>Choose a directory for right files</source>
<translation>Choisissez un répertoire pour les fichiers de droite</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
<translation>Extension :</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
<translation>*avi,*.mkv</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
<translation>Statut</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
<translation>lancer</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation></translation>
</message>
<message>
- <location filename="../main_window.ui" line="25"/>
+ <location filename="../main_window.ui" line="28"/>
<source>Simple</source>
<translation>Simple</translation>
</message>
<message>
- <location filename="../main_window.ui" line="38"/>
+ <location filename="../main_window.ui" line="41"/>
<source>Last operations</source>
<translation>Dernières opérations</translation>
</message>
<message>
- <location filename="../main_window.ui" line="64"/>
+ <location filename="../main_window.ui" line="67"/>
<source>&File</source>
<translation>&Fichier</translation>
</message>
<message>
- <location filename="../main_window.ui" line="73"/>
+ <location filename="../main_window.ui" line="76"/>
+ <source>&Settings</source>
+ <translation></translation>
+ </message>
+ <message>
+ <location filename="../main_window.ui" line="82"/>
+ <source>&Edit</source>
+ <translation>&Ãditer</translation>
+ </message>
+ <message>
+ <location filename="../main_window.ui" line="114"/>
+ <source>&Undo</source>
+ <translation>&Défaire</translation>
+ </message>
+ <message>
+ <location filename="../main_window.ui" line="117"/>
+ <source>Ctrl+Z</source>
+ <translation></translation>
+ </message>
+ <message>
+ <location filename="../main_window.ui" line="122"/>
+ <source>&Redo</source>
+ <translation>&Refaire</translation>
+ </message>
+ <message>
<source>Settings</source>
- <translation>Paramètres</translation>
+ <translation type="obsolete">Paramètres</translation>
</message>
<message>
- <location filename="../main_window.ui" line="83"/>
+ <location filename="../main_window.ui" line="94"/>
<source>&Quit</source>
<translation>&Quitter</translation>
</message>
<message>
- <location filename="../main_window.ui" line="88"/>
+ <location filename="../main_window.ui" line="99"/>
<source>Language</source>
<translation>Langage</translation>
</message>
<message>
- <location filename="../main_window.ui" line="93"/>
+ <location filename="../main_window.ui" line="104"/>
<source>&Load profile...</source>
<translation>&Charge un profile...</translation>
</message>
<message>
- <location filename="../main_window.ui" line="98"/>
+ <location filename="../main_window.ui" line="109"/>
<source>&Save profile...</source>
<translation>&Sauver le profile...</translation>
</message>
<message>
- <location filename="../main_window.cpp" line="124"/>
+ <location filename="../main_window.cpp" line="145"/>
<source>Choose a profile to load</source>
<translation>Choisissez un profile à charger</translation>
</message>
<message>
- <location filename="../main_window.cpp" line="136"/>
+ <location filename="../main_window.cpp" line="157"/>
<source>Choose a profile filename to save in</source>
<translation>Choisissez un nom de profile à sauver</translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
- <location filename="../modifier_model.cpp" line="54"/>
+ <location filename="../modifier_model.cpp" line="75"/>
<source>#</source>
<translation></translation>
</message>
<message>
- <location filename="../modifier_model.cpp" line="55"/>
+ <location filename="../modifier_model.cpp" line="76"/>
<source>Mode</source>
<translation>Mode</translation>
</message>
<message>
- <location filename="../modifier_model.cpp" line="56"/>
+ <location filename="../modifier_model.cpp" line="77"/>
<source>Action</source>
<translation>Action</translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
- <location filename="../processor.cpp" line="127"/>
+ <location filename="../processor.cpp" line="145"/>
<source>Rename</source>
<translation>Renommer</translation>
</message>
<message>
- <location filename="../processor.cpp" line="128"/>
+ <location filename="../processor.cpp" line="146"/>
<source>Copy</source>
<translation>Copier</translation>
</message>
<message>
- <location filename="../processor.cpp" line="129"/>
+ <location filename="../processor.cpp" line="147"/>
<source>Move</source>
<translation>Déplacer</translation>
</message>
<message>
- <location filename="../processor.cpp" line="130"/>
+ <location filename="../processor.cpp" line="148"/>
<source>Create link</source>
<translation>Créer un lien</translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
- <location filename="../widget_extension_policy.cpp" line="123"/>
+ <location filename="../widget_extension_policy.cpp" line="141"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
- <location filename="../widget_extension_policy.cpp" line="123"/>
+ <location filename="../widget_extension_policy.cpp" line="141"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation>Souhaitez-vous vraiment revenir à la politique d'extension par défaut ?</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation>Choisissez quelle partie des fichiers vous voulez renommer :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation>Le nom de base (sans l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation>Le nom de fichier en entier (avec l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation>Seulement l'extension</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation>Paramètres par défaut</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation>L'extension du fichier commence juste après le :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation>Premier point en partant de la droite</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation>Premier point en partant de la gauche</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation>ième point en partant de la droite</translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
- <location filename="../widget_filters.cpp" line="39"/>
+ <location filename="../widget_filters.cpp" line="57"/>
<source>General</source>
<translation>Général</translation>
</message>
<message>
- <location filename="../widget_filters.cpp" line="40"/>
+ <location filename="../widget_filters.cpp" line="58"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
- <location filename="../widget_filters.cpp" line="38"/>
+ <location filename="../widget_filters.cpp" line="56"/>
<source>Override the global extension policy</source>
<translation>Supplanter la politique d'extension globale</translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
- <location filename="../widget_modifiers.cpp" line="48"/>
+ <location filename="../widget_modifiers.cpp" line="66"/>
<source>Add a new %1</source>
<translation>Ajouter un nouveau %1</translation>
</message>
<message>
- <location filename="../widget_modifiers.cpp" line="65"/>
<source>Confirmation</source>
- <translation>Confirmation</translation>
+ <translation type="obsolete">Confirmation</translation>
</message>
<message>
- <location filename="../widget_modifiers.cpp" line="65"/>
<source>Do you really want to remove this filter?</source>
- <translation>Voulez-vous réellement supprimer ce filtre ?</translation>
+ <translation type="obsolete">Voulez-vous réellement supprimer ce filtre ?</translation>
</message>
<message>
<location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation>Cliquez pour ajouter</translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
- <location filename="../widget_simple.cpp" line="233"/>
+ <location filename="../widget_simple.cpp" line="251"/>
<source>Confirmation</source>
<translation>Confirmation</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="233"/>
+ <location filename="../widget_simple.cpp" line="251"/>
<source>Do you really want to remove this files?</source>
<translation>Ãtes-vous certain de vouloir supprimer ces fichiers ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="96"/>
+ <location filename="../widget_simple.cpp" line="114"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="96"/>
+ <location filename="../widget_simple.cpp" line="114"/>
<source>Do you really want to start the rename process?</source>
<translation>Voulez-vous vraiment démarrer le processus de renommage ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="140"/>
+ <location filename="../widget_simple.cpp" line="158"/>
<source>Choose a destination directory</source>
<translation>Choisissez un répertoire de destination</translation>
</message>
<message numerus="yes">
- <location filename="../widget_simple.cpp" line="150"/>
+ <location filename="../widget_simple.cpp" line="168"/>
<source>%n files</source>
<translation>
<numerusform>%n fichier</numerusform>
<numerusform>%n fichiers</numerusform>
</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="251"/>
+ <location filename="../widget_simple.cpp" line="269"/>
<source>Pick some files</source>
<translation>Choisissez des fichiers</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation>Lancer</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation>Renommage de fichier</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation>Copie renommée dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation>Déplacement renommé dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation>Création des liens dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
- <translation></translation>
+ <translation>...</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="107"/>
<source>Add some files...</source>
<translation>Ajouter des fichiers...</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="330"/>
<source>Click to add some files</source>
<translation>Cliquer pour ajouter des fichiers</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="459"/>
<source>&Remove</source>
<translation>&Supprimer</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="471"/>
<source>&Add</source>
<translation>&Ajouter</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="474"/>
<source>Add files</source>
<translation>Ajouter des fichiers</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="483"/>
<source>&Up</source>
<translation>&Monter</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="495"/>
<source>&Down</source>
<translation>&Descendre</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="124"/>
<location filename="../widget_simple.ui" line="462"/>
<source>Remove selected files</source>
<translation>Supprimer les fichiers sélectionnés</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="442"/>
<source>by name</source>
<translation>par nom</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="445"/>
<source>Sort files by name</source>
<translation>Trier les fichier par nom</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="450"/>
<source>by modification date</source>
<translation>par date de modification</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="167"/>
<source>Sort by</source>
<translation>Trier par</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="177"/>
<location filename="../widget_simple.ui" line="486"/>
<source>Up selected files</source>
<translation>Monter les fichiers sélectionnés</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="194"/>
<location filename="../widget_simple.ui" line="498"/>
<source>Down selected files</source>
<translation>Descendre les fichiers sélectionnés</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="377"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="412"/>
<source>Filters</source>
<translation>Filtres</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="425"/>
<source>Finalizers</source>
<translation>Finaliseurs</translation>
</message>
</context>
</TS>
|
Guid75/renamah
|
964551240c7ed7aa0e0274d9f06e07c0afda3119
|
plugins qm are searched in share/plugin path
|
diff --git a/install_translations.sh b/install_translations.sh
index 0374d75..88a114a 100755
--- a/install_translations.sh
+++ b/install_translations.sh
@@ -1,9 +1,9 @@
#!/bin/sh
-cp renamah/*.qm bin
-cp plugins/cutterfilter/*.qm bin/plugins
-cp plugins/casefilter/*.qm bin/plugins
-cp plugins/commandaction/*.qm bin/plugins
-cp plugins/numberingfilter/*.qm bin/plugins
-cp plugins/replacefilter/*.qm bin/plugins
-cp plugins/datefilter/*.qm bin/plugins
+cp renamah/*.qm share/renamah
+cp plugins/cutterfilter/*.qm share/renamah/plugins
+cp plugins/casefilter/*.qm share/renamah/plugins
+cp plugins/commandaction/*.qm share/renamah/plugins
+cp plugins/numberingfilter/*.qm share/renamah/plugins
+cp plugins/replacefilter/*.qm share/renamah/plugins
+cp plugins/datefilter/*.qm share/renamah/plugins
diff --git a/renamah/main_window.cpp b/renamah/main_window.cpp
index 1dc7c8c..9e72670 100644
--- a/renamah/main_window.cpp
+++ b/renamah/main_window.cpp
@@ -1,170 +1,171 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QTranslator>
#include <QSettings>
#include <QLibraryInfo>
#include <QFileDialog>
#include <QShortcut>
#include "plugin_manager.h"
#include "filter_model.h"
#include "processor.h"
#include "profile.h"
#include "undo_manager.h"
+#include "paths.h"
#include "main_window.h"
MainWindow::MainWindow(QWidget *parent)
: actionGroupLanguages(0),
QMainWindow(parent) {
setupUi(this);
PluginManager::instance().load();
tabWidgetMain->setCurrentWidget(tabSimple);
connect(&Processor::instance(), SIGNAL(started()), this, SLOT(processorStarted()));
widgetSimple->initAfterPluginLoaded();
actionLanguage->setMenu(&menuLanguages);
QSettings settings;
QString currentLanguage = settings.value("general/language", "").toString();
if (currentLanguage != "")
installLanguage(currentLanguage);
refreshLanguageActions();
connect(&signalMapperLanguages, SIGNAL(mapped(const QString &)),
this, SLOT(languageRequested(const QString &)));
}
void MainWindow::refreshLanguageActions() {
if (actionGroupLanguages)
delete actionGroupLanguages;
actionGroupLanguages = new QActionGroup(this);
menuLanguages.clear();
QAction *actionToCheck = 0;
QSettings settings;
QString currentLanguage = settings.value("general/language", "").toString();
// Get languages list
foreach (const QFileInfo &fileInfo, QDir(QCoreApplication::applicationDirPath()).entryInfoList(QStringList() << "*.qm",
QDir::Files)) {
QString baseName = fileInfo.baseName();
int p = baseName.indexOf("_");
if (p > 0) {
QString fileLanguage = baseName.mid(p + 1, baseName.length() - p - 1);
QLocale locale(fileLanguage);
QString language = QLocale::languageToString(locale.language());
QString country = QLocale::countryToString(locale.country());
QAction *action = menuLanguages.addAction(QString("%1 (%2)").arg(language).arg(country));
if (fileLanguage == currentLanguage)
actionToCheck = action;
signalMapperLanguages.setMapping(action, fileLanguage);
connect(action, SIGNAL(triggered()), &signalMapperLanguages, SLOT(map()));
action->setCheckable(true);
actionGroupLanguages->addAction(action);
}
}
if (actionToCheck)
actionToCheck->setChecked(true);
}
void MainWindow::processorStarted() {
tabWidgetMain->setCurrentWidget(tabLastOperations);
}
void MainWindow::languageRequested(const QString &language) {
installLanguage(language);
QSettings settings;
settings.setValue("general/language", language);
}
void MainWindow::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi(this);
} else
QWidget::changeEvent(event);
}
void MainWindow::installLanguage(const QString &language) {
// Remove all existing translators
foreach (QTranslator *translator, translators)
qApp->removeTranslator(translator);
translators.clear();
// Install the Qt translator
QTranslator *qtTranslator = new QTranslator;
qtTranslator->load("qt_" + language,
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
qApp->installTranslator(qtTranslator);
// Install the main app translator
QTranslator *translator = new QTranslator;
translator->load("renamah_" + language,
- QCoreApplication::applicationDirPath());
+ Paths::sharePath());
qApp->installTranslator(translator);
translators << translator;
// Install all plugins translators
foreach (const QString &fileName, PluginManager::instance().pluginFileNames()) {
QFileInfo fileInfo(fileName);
QString baseName = fileInfo.completeBaseName();
QString qmFileName = fileInfo.absoluteDir().filePath(baseName) + "_" + language + ".qm";
QTranslator *translator = new QTranslator;
translator->load(qmFileName,
QCoreApplication::applicationDirPath());
qApp->installTranslator(translator);
translators << translator;
}
}
void MainWindow::on_actionLoadProfile_triggered() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a profile to load"),
QDir::home().absolutePath());
if (fileName == "")
return;
if (!Profile::load(fileName))
return;
widgetSimple->newProfile();
}
void MainWindow::on_actionSaveProfile_triggered() {
QString fileName = QFileDialog::getSaveFileName(this, tr("Choose a profile filename to save in"),
QDir::home().absolutePath());
if (fileName == "")
return;
Profile::save(fileName);
}
void MainWindow::on_actionUndo_triggered() {
UndoManager::instance().undo();
}
void MainWindow::on_actionRedo_triggered() {
UndoManager::instance().redo();
}
|
Guid75/renamah
|
c42965c61358ad049a295de31f2ee58a7c9829a6
|
ignore some files
|
diff --git a/.gitignore b/.gitignore
index 3e0fa96..7b5a6de 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,9 +1,11 @@
*.qm
ui_*
moc_*
*.cxx
Makefile
CMakeFiles
*~
CMakeCache.txt
-cmake_install.cmake
\ No newline at end of file
+cmake_install.cmake
+bin/renamah
+bin/libcore.so
\ No newline at end of file
|
Guid75/renamah
|
b65421405a5961a33cc68cae5ca8baef5cb648e3
|
New file reorganisation
|
diff --git a/plugins/casefilter/CMakeLists.txt b/plugins/casefilter/CMakeLists.txt
index 92cc877..62b40da 100644
--- a/plugins/casefilter/CMakeLists.txt
+++ b/plugins/casefilter/CMakeLists.txt
@@ -1,43 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(CASEFILTER_SOURCES
case_filter_factory.cpp
case_filter.cpp
config_widget.cpp
)
SET(CASEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CASEFILTER_FORMS_H ${CASEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CASEFILTER_MOCH
case_filter.h
case_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CASEFILTER_MOC ${CASEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS} ${CASEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_casefilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
ADD_LIBRARY(casefilter SHARED ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS_H} ${CASEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(casefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(casefilter translations_casefilter)
diff --git a/plugins/commandaction/CMakeLists.txt b/plugins/commandaction/CMakeLists.txt
index d0113c3..d92bf4a 100644
--- a/plugins/commandaction/CMakeLists.txt
+++ b/plugins/commandaction/CMakeLists.txt
@@ -1,47 +1,47 @@
INCLUDE(${QT_USE_FILE})
SET(COMMANDACTION_SOURCES
command_action_factory.cpp
command_action.cpp
config_widget.cpp
process_handler.cpp
)
SET(COMMANDACTION_FORMS
config_widget.ui
)
QT4_WRAP_UI(COMMANDACTION_FORMS_H ${COMMANDACTION_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(COMMANDACTION_MOCH
command_action.h
command_action_factory.h
config_widget.h
process_handler.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(COMMANDACTION_MOC ${COMMANDACTION_MOCH})
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS} ${COMMANDACTION_MOCH})
ADD_CUSTOM_TARGET(translations_commandaction DEPENDS ${QM_FILES})
ADD_LIBRARY(commandaction SHARED ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(commandaction core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(commandaction translations_commandaction)
diff --git a/plugins/cutterfilter/CMakeLists.txt b/plugins/cutterfilter/CMakeLists.txt
index 3a48697..e70ba3c 100644
--- a/plugins/cutterfilter/CMakeLists.txt
+++ b/plugins/cutterfilter/CMakeLists.txt
@@ -1,42 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(CUTTERFILTER_SOURCES
cutter_filter_factory.cpp
cutter_filter.cpp
config_widget.cpp
)
SET(CUTTERFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CUTTERFILTER_FORMS_H ${CUTTERFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CUTTERFILTER_MOCH
cutter_filter.h
cutter_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CUTTERFILTER_MOC ${CUTTERFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS} ${CUTTERFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_cutterfilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
ADD_LIBRARY(cutterfilter SHARED ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS_H} ${CUTTERFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(cutterfilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(cutterfilter translations_cutterfilter)
diff --git a/plugins/datefilter/CMakeLists.txt b/plugins/datefilter/CMakeLists.txt
index 51a2c66..e9afa2c 100644
--- a/plugins/datefilter/CMakeLists.txt
+++ b/plugins/datefilter/CMakeLists.txt
@@ -1,44 +1,44 @@
INCLUDE(${QT_USE_FILE})
SET(DATEFILTER_SOURCES
date_filter_factory.cpp
date_filter.cpp
config_widget.cpp
)
SET(DATEFILTER_FORMS
config_widget.ui
help_widget.ui
)
QT4_WRAP_UI(DATEFILTER_FORMS_H ${DATEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(DATEFILTER_MOCH
date_filter.h
date_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(DATEFILTER_MOC ${DATEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS} ${DATEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_datefilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
ADD_LIBRARY(datefilter SHARED ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS_H} ${DATEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(datefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(datefilter translations_datefilter)
diff --git a/plugins/numberingfilter/CMakeLists.txt b/plugins/numberingfilter/CMakeLists.txt
index cdff17a..70c486d 100644
--- a/plugins/numberingfilter/CMakeLists.txt
+++ b/plugins/numberingfilter/CMakeLists.txt
@@ -1,42 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(NUMBERINGFILTER_SOURCES
numbering_filter_factory.cpp
numbering_filter.cpp
config_widget.cpp
)
SET(NUMBERINGFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(NUMBERINGFILTER_FORMS_H ${NUMBERINGFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(NUMBERINGFILTER_MOCH
numbering_filter.h
numbering_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(NUMBERINGFILTER_MOC ${NUMBERINGFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS} ${NUMBERINGFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_numberingfilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
ADD_LIBRARY(numberingfilter SHARED ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS_H} ${NUMBERINGFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(numberingfilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(numberingfilter translations_numberingfilter)
diff --git a/plugins/replacefilter/CMakeLists.txt b/plugins/replacefilter/CMakeLists.txt
index 75d6d6c..259cd2e 100644
--- a/plugins/replacefilter/CMakeLists.txt
+++ b/plugins/replacefilter/CMakeLists.txt
@@ -1,42 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(REPLACEFILTER_SOURCES
replace_filter_factory.cpp
replace_filter.cpp
config_widget.cpp
)
SET(REPLACEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(REPLACEFILTER_FORMS_H ${REPLACEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(REPLACEFILTER_MOCH
replace_filter.h
replace_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(REPLACEFILTER_MOC ${REPLACEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS} ${REPLACEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_replacefilter DEPENDS ${QM_FILES})
# Destination
-SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
+SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/share/renamah/plugins)
ADD_LIBRARY(replacefilter SHARED ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS_H} ${REPLACEFILTER_MOC})
IF(MSVC)
TARGET_LINK_LIBRARIES(replacefilter core ${QT_LIBRARIES})
ENDIF(MSVC)
ADD_DEPENDENCIES(replacefilter translations_replacefilter)
diff --git a/renamah/CMakeLists.txt b/renamah/CMakeLists.txt
index f9e44f2..d986cf3 100644
--- a/renamah/CMakeLists.txt
+++ b/renamah/CMakeLists.txt
@@ -1,94 +1,96 @@
SET(QT_USE_QTXML TRUE)
# SET(QT_USE_QTNETWORK TRUE)
INCLUDE(${QT_USE_FILE})
SET(RENAMAH_SOURCES
main.cpp
main_window.cpp
form_twinning.cpp
simple_dir_model.cpp
twinning_widget.cpp
widget_simple.cpp
file_model.cpp
filter_model.cpp
filter_manager.cpp
plugin_manager.cpp
form_last_operations.cpp
task_manager.cpp
modifier_delegate.cpp
led_widget.cpp
processor.cpp
widget_modifiers.cpp
modifier_manager.cpp
modifier_model.cpp
finalizer_model.cpp
action_manager.cpp
widget_extension_policy.cpp
extension_policy.cpp
widget_filters.cpp
widget_actions.cpp
dialog_manual_rename.cpp
profile.cpp
undo_manager.cpp
+ global.cpp
+ paths.cpp
)
SET(RENAMAH_FORMS
main_window.ui
form_twinning.ui
widget_simple.ui
form_last_operations.ui
widget_modifiers.ui
widget_extension_policy.ui
dialog_manual_rename.ui
)
QT4_WRAP_UI(RENAMAH_FORMS_H ${RENAMAH_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/staticlibs)
SET(RENAMAH_MOCH
main_window.h
form_twinning.h
simple_dir_model.h
twinning_widget.h
widget_simple.h
file_model.h
filter_model.h
form_last_operations.h
modifier_delegate.h
led_widget.h
processor.h
widget_modifiers.h
modifier_model.h
finalizer_model.h
widget_extension_policy.h
widget_filters.h
widget_actions.h
dialog_manual_rename.h
undo_manager.h
)
# Translations stuff
COMPUTE_QM_FILES(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH})
ADD_CUSTOM_TARGET(translations_renamah DEPENDS ${QM_FILES})
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(RENAMAH_MOC ${RENAMAH_MOCH})
QT4_ADD_RESOURCES(RENAMAH_RES renamah.qrc)
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
ADD_EXECUTABLE(renamah ${RENAMAH_SOURCES} ${RENAMAH_FORMS_H} ${RENAMAH_MOC} ${RENAMAH_RES})
ADD_DEPENDENCIES(renamah translations_renamah)
TARGET_LINK_LIBRARIES(
renamah core ${QT_LIBRARIES}
)
diff --git a/renamah/paths.cpp b/renamah/paths.cpp
index f66dd8f..c9fe4df 100644
--- a/renamah/paths.cpp
+++ b/renamah/paths.cpp
@@ -1,51 +1,52 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QDir>
#include <QCoreApplication>
#include <QDesktopServices>
#include "global.h"
#include "paths.h"
QString Paths::sharePath()
{
QDir appDir(QCoreApplication::applicationDirPath());
- if (Global::devMode())
+ if (Global::devMode()) {
return QDir(appDir.filePath("../share/renamah")).canonicalPath();
+ }
if (Global::localMode())
return appDir.absolutePath();
#if defined(Q_OS_LINUX)
return QDir(appDir.filePath("/usr/share/renamah")).canonicalPath();
#else
return appDir.absolutePath();
#endif
}
QString Paths::profilePath()
{
if (Global::devMode() || Global::localMode())
return QDir(QCoreApplication::applicationDirPath()).filePath(qApp->applicationName());
return QDesktopServices::storageLocation(QDesktopServices::DataLocation);
}
diff --git a/renamah/plugin_manager.cpp b/renamah/plugin_manager.cpp
index b9bef3b..bdcb2c4 100644
--- a/renamah/plugin_manager.cpp
+++ b/renamah/plugin_manager.cpp
@@ -1,81 +1,82 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QPluginLoader>
#include <QDir>
#include <QCoreApplication>
#include <interfaces/filter.h>
#include <interfaces/filter_factory.h>
#include <interfaces/action_factory.h>
#include "filter_manager.h"
#include "action_manager.h"
+#include "paths.h"
#include "plugin_manager.h"
PluginManager *PluginManager::_instance = 0;
PluginManager &PluginManager::instance()
{
if (!_instance)
_instance = new PluginManager;
return *_instance;
}
void PluginManager::load()
{
// Static plugins
foreach (QObject *plugin, QPluginLoader::staticInstances())
dispatchPlugin(plugin);
// Dynamic plugins
- QDir pluginsDir(QDir(QCoreApplication::applicationDirPath()).filePath("plugins"));
+ QDir pluginsDir(QDir(Paths::sharePath()).filePath("plugins"));
foreach (const QString &fileName, pluginsDir.entryList(QDir::Files))
{
if (QLibrary::isLibrary(fileName)) {
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader.instance();
if (plugin) {
dispatchPlugin(plugin);
_pluginFileNames << pluginsDir.absoluteFilePath(fileName);
}
else
qDebug("Error: %s", qPrintable(loader.errorString()));
}
}
}
void PluginManager::dispatchPlugin(QObject *plugin)
{
Q_ASSERT_X(plugin, "PluginManager::dispatchPlugin()", "<plugin> is 0!");
core::ModifierFactory *factory = qobject_cast<core::FilterFactory*>(plugin);
if (factory)
{
FilterManager::instance().addFactory(factory);
return;
}
factory = qobject_cast<core::ActionFactory*>(plugin);
if (factory)
{
ActionManager::instance().addFactory(factory);
return;
}
}
diff --git a/share/renamah/plugins/libcasefilter.so b/share/renamah/plugins/libcasefilter.so
new file mode 100755
index 0000000..c882fe0
Binary files /dev/null and b/share/renamah/plugins/libcasefilter.so differ
diff --git a/share/renamah/plugins/libcommandaction.so b/share/renamah/plugins/libcommandaction.so
new file mode 100755
index 0000000..47a208b
Binary files /dev/null and b/share/renamah/plugins/libcommandaction.so differ
diff --git a/share/renamah/plugins/libcutterfilter.so b/share/renamah/plugins/libcutterfilter.so
new file mode 100755
index 0000000..0ebaf07
Binary files /dev/null and b/share/renamah/plugins/libcutterfilter.so differ
diff --git a/share/renamah/plugins/libdatefilter.so b/share/renamah/plugins/libdatefilter.so
new file mode 100755
index 0000000..126061c
Binary files /dev/null and b/share/renamah/plugins/libdatefilter.so differ
diff --git a/share/renamah/plugins/libnumberingfilter.so b/share/renamah/plugins/libnumberingfilter.so
new file mode 100755
index 0000000..2c4dc6e
Binary files /dev/null and b/share/renamah/plugins/libnumberingfilter.so differ
diff --git a/share/renamah/plugins/libreplacefilter.so b/share/renamah/plugins/libreplacefilter.so
new file mode 100755
index 0000000..096a79c
Binary files /dev/null and b/share/renamah/plugins/libreplacefilter.so differ
|
Guid75/renamah
|
f0537575218fb8c7ef12fc669a22f8324bce68da
|
new files for paths
|
diff --git a/.gitignore b/.gitignore
index f9922c8..3e0fa96 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,9 @@
*.qm
ui_*
moc_*
*.cxx
Makefile
CMakeFiles
*~
CMakeCache.txt
-cmake_install.cmake
-/bin
+cmake_install.cmake
\ No newline at end of file
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..609a19f
--- /dev/null
+++ b/TODO
@@ -0,0 +1,17 @@
+* Dissociation of filtered result and action of the filter (a filter can
+* execute extra-code too and not only rename. We don't want this
+* extra-code to be executed several times but only once at the process
+* time)
+* Add the original filename in filters apply function parameters
+* Be capable to make manually rename operations
+* Do we finalize files when their name is unchanged? An option?
+* Code a system call action which is under unix a call to
+* "sh/bash/whatever" + arguments into a QProcess and under others
+* platform just a simple call using QProcess.
+* Implement a language selector and dynamically load a language file
+* Save/restore profiles
+* Undo system
+* Smart hints for trees
+* Take care of too high roman numbers in numbering plugin
+* Take care of forbidden chars in general
+* Offer a way to sort files with differents criterias
\ No newline at end of file
diff --git a/bin/dev b/bin/dev
new file mode 100644
index 0000000..e69de29
diff --git a/renamah/global.cpp b/renamah/global.cpp
new file mode 100644
index 0000000..f44c130
--- /dev/null
+++ b/renamah/global.cpp
@@ -0,0 +1,38 @@
+/* This file is part of CeB.
+ * Copyright (C) 2005 Guillaume Denry
+ *
+ * CeB 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
+ * any later version.
+ *
+ * CeB 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 CeB; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <QCoreApplication>
+#include <QDir>
+#include <QFile>
+
+#include "global.h"
+
+#define LOCAL_FILENAME "local"
+#define DEV_FILENAME "dev"
+
+bool Global::localMode()
+{
+ QDir appDir(QCoreApplication::applicationDirPath());
+ return QFile(appDir.filePath(LOCAL_FILENAME)).exists();
+}
+
+bool Global::devMode()
+{
+ QDir appDir(QCoreApplication::applicationDirPath());
+ return QFile(appDir.filePath(DEV_FILENAME)).exists();
+}
diff --git a/renamah/global.h b/renamah/global.h
new file mode 100644
index 0000000..1f0094f
--- /dev/null
+++ b/renamah/global.h
@@ -0,0 +1,28 @@
+/*
+ * Renamah
+ * Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
+ *
+ * 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
+ * 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/>.
+ */
+
+#ifndef GLOBAL_H
+#define GLOBAL_H
+
+namespace Global
+{
+ bool localMode();
+ bool devMode();
+};
+
+#endif
diff --git a/renamah/main_window.ui b/renamah/main_window.ui
index fb4f7e8..b208a20 100644
--- a/renamah/main_window.ui
+++ b/renamah/main_window.ui
@@ -1,156 +1,159 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>Renamah</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
+ <property name="margin">
+ <number>0</number>
+ </property>
<item row="0" column="0">
<widget class="QTabWidget" name="tabWidgetMain">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabSimple">
<attribute name="title">
<string>Simple</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetSimple" name="widgetSimple" native="true"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabLastOperations">
<attribute name="title">
<string>Last operations</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_4">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="FormLastOperations" name="widgetLastOperations" native="true"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>23</height>
</rect>
</property>
<widget class="QMenu" name="menu_File">
<property name="title">
<string>&File</string>
</property>
<addaction name="actionLoadProfile"/>
<addaction name="actionSaveProfile"/>
<addaction name="separator"/>
<addaction name="action_Quit"/>
</widget>
<widget class="QMenu" name="menuSettings">
<property name="title">
<string>&Settings</string>
</property>
<addaction name="actionLanguage"/>
</widget>
<widget class="QMenu" name="menuEdit">
<property name="title">
<string>&Edit</string>
</property>
<addaction name="actionUndo"/>
<addaction name="actionRedo"/>
</widget>
<addaction name="menu_File"/>
<addaction name="menuEdit"/>
<addaction name="menuSettings"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<action name="action_Quit">
<property name="text">
<string>&Quit</string>
</property>
</action>
<action name="actionLanguage">
<property name="text">
<string>Language</string>
</property>
</action>
<action name="actionLoadProfile">
<property name="text">
<string>&Load profile...</string>
</property>
</action>
<action name="actionSaveProfile">
<property name="text">
<string>&Save profile...</string>
</property>
</action>
<action name="actionUndo">
<property name="text">
<string>&Undo</string>
</property>
<property name="shortcut">
<string>Ctrl+Z</string>
</property>
</action>
<action name="actionRedo">
<property name="text">
<string>&Redo</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>FormLastOperations</class>
<extends>QWidget</extends>
<header>form_last_operations.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetSimple</class>
<extends>QWidget</extends>
<header>widget_simple.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>action_Quit</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>399</x>
<y>299</y>
</hint>
</hints>
</connection>
</connections>
</ui>
diff --git a/renamah/modifier_model.cpp b/renamah/modifier_model.cpp
index 6c4d042..856fcc3 100644
--- a/renamah/modifier_model.cpp
+++ b/renamah/modifier_model.cpp
@@ -1,383 +1,383 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QMimeData>
#include <interfaces/modifier_factory.h>
#include "undo_manager.h"
#include "modifier_model.h"
ModifierModel::ModifierModel(ModifierManager *manager)
: _manager(manager),
_exclusiveModifier(0),
_disableUndo(false)
{
}
int ModifierModel::rowCount(const QModelIndex &parent) const
{
return _modifiers.count();
}
int ModifierModel::columnCount(const QModelIndex &parent) const
{
return columnNumber;
}
QVariant ModifierModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= _modifiers.count())
return QVariant();
const core::Modifier *modifier = _modifiers[index.row()];
switch (role)
{
case Qt::DisplayRole:
switch (index.column())
{
case colIndex: return index.row() + 1;
case colMode: return "";
case colCaption: return modifier->factory()->info().caption() + " [" + modifier->resume() + "]";
default:;
}
case Qt::ForegroundRole:
if (_exclusiveModifier && _exclusiveModifier != modifier)
return Qt::gray;
break;
default:;
}
return QVariant();
}
QVariant ModifierModel::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role)
{
case Qt::DisplayRole:
switch (section)
{
case colIndex: return tr("#");
case colMode: return tr("Mode");
case colCaption: return tr("Action");
default:;
}
break;
default:;
}
return QVariant();
}
void ModifierModel::init(core::Modifier *modifier) {
connect(modifier, SIGNAL(settingsChanging()), this, SLOT(modifierChanging()));
connect(modifier, SIGNAL(settingsChanged()), this, SLOT(modifierChanged()));
connect(modifier, SIGNAL(settingsChanged()), this, SIGNAL(modifiersChanged()));
}
void ModifierModel::addModifier(core::Modifier *modifier)
{
init(modifier);
beginInsertRows(QModelIndex(), _modifiers.count(), _modifiers.count());
_modifiers << modifier;
_modifierStates[modifier] = true;
endInsertRows();
if (!_disableUndo) {
CreateModifierCommand *command = new CreateModifierCommand(this, _manager, modifier->factory()->info().name());
UndoManager::instance().push(command);
command->activate();
}
emit modifiersChanged();
}
void ModifierModel::insertModifier(int index, core::Modifier *modifier) {
init(modifier);
beginInsertRows(QModelIndex(), index, index);
_modifiers.insert(index, modifier);
_modifierStates[modifier] = true;
endInsertRows();
// TODO : integrate into the undo framework!!!
emit modifiersChanged();
}
void ModifierModel::removeModifier(const QModelIndex &index)
{
if (!index.isValid())
return;
removeRows(index.row(), 1);
}
bool ModifierModel::modifierState(core::Modifier *modifier) const
{
if (_modifierStates.find(modifier) == _modifierStates.end())
return false;
else
return _modifierStates[modifier];
}
void ModifierModel::setModifierState(core::Modifier *modifier, bool state)
{
int modifierRow = _modifiers.indexOf(modifier);
if (modifierRow < 0)
return;
if (_modifierStates[modifier] != state)
{
_modifierStates[modifier] = state;
emit dataChanged(index(modifierRow, 0), index(modifierRow, columnNumber - 1));
emit modifiersChanged();
}
}
void ModifierModel::toggleModifierState(core::Modifier *modifier)
{
if (_modifierStates.find(modifier) == _modifierStates.end())
return;
setModifierState(modifier, !_modifierStates[modifier]);
}
void ModifierModel::setExclusiveModifier(core::Modifier *modifier)
{
if (_exclusiveModifier == modifier)
return;
_exclusiveModifier = modifier;
if (modifier)
_modifierStates[modifier] = true;
// Refresh all
emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
emit modifiersChanged();
}
/*QString ModifierModel::apply(const QString &str) const
{
if (_exclusiveModifier)
return _exclusiveModifier->apply(str);
QString filtered = str;
foreach (core::Filter *filter, _modifiers)
if (_modifierstates[filter])
filtered = filter->apply(filtered);
return filtered;
}*/
core::Modifier *ModifierModel::modifier(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return _modifiers[index.row()];
}
Qt::ItemFlags ModifierModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractListModel::flags(index);
if (index.isValid())
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
else
return Qt::ItemIsDropEnabled | flags;
}
void ModifierModel::toggleExclusiveState(core::Modifier *modifier)
{
if (_exclusiveModifier == modifier)
_exclusiveModifier = 0;
else
_exclusiveModifier = modifier;
if (_exclusiveModifier)
_modifierStates[_exclusiveModifier] = true;
// Refresh all
emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
emit modifiersChanged();
}
Qt::DropActions ModifierModel::supportedDropActions() const {
- return Qt::MoveAction;
+ return Qt::CopyAction;
}
bool ModifierModel::removeRows(int row, int count, const QModelIndex &parent) {
core::Modifier *modifierToRemove = modifier(index(row, 0));
if (!_disableUndo) {
RemoveModifierCommand *command = new RemoveModifierCommand(this, _manager, row, modifierToRemove->factory()->info().name(),
modifierToRemove->serializeProperties());
UndoManager::instance().push(command);
command->activate();
}
beginRemoveRows(QModelIndex(), row, row);
_modifiers.removeAt(_modifiers.indexOf(modifierToRemove));
_modifierStates.remove(modifierToRemove);
if (_exclusiveModifier == modifierToRemove)
_exclusiveModifier = 0;
delete modifierToRemove;
endRemoveRows();
emit modifiersChanged();
return true;
}
#define MIMETYPE QLatin1String("filter-rows")
QStringList ModifierModel::mimeTypes() const
{
QStringList types;
types << MIMETYPE;
return types;
}
QMimeData *ModifierModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *mimeData = new QMimeData;
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
stream << index.row();
}
}
mimeData->setData(MIMETYPE, encodedData);
return mimeData;
}
bool ModifierModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
if (action == Qt::IgnoreAction)
return false;
QByteArray inData = data->data(MIMETYPE);
QDataStream stream(inData);
int sourceRow;
stream >> sourceRow;
int destinationRow = rowCount();
if (row != -1) {
if (row >= rowCount()) {
destinationRow = rowCount();
} else {
if (sourceRow < row)
row--;
destinationRow = row;
}
} else if (parent.isValid()) {
destinationRow = parent.row();
} else if (!parent.isValid()) {
destinationRow = rowCount();
}
moveModifier(sourceRow, destinationRow);
return false;
}
void ModifierModel::clear() {
_exclusiveModifier = 0;
qDeleteAll(_modifiers);
_modifiers.clear();
_modifierStates.clear();
reset();
emit modifiersChanged();
}
void ModifierModel::modifierChanged() {
if (_disableUndo)
return;
core::Modifier *modifier = static_cast<core::Modifier*>(sender());
// Undo managing => compute the diff
QMap<QString,QPair<QString,QVariant> > newProperties = modifier->serializeProperties();
QMap<QString,QPair<QString,QVariant> > &oldProperties = _changingModifierOldProperties;
QMap<QString,QPair<QString,QVariant> > undoProperties, redoProperties;
foreach (const QString &propName, newProperties.keys()) {
QPair<QString,QVariant> &newPair = newProperties[propName];
QPair<QString,QVariant> &oldPair = oldProperties[propName];
if (newPair != oldPair) {
undoProperties.insert(propName, oldPair);
redoProperties.insert(propName, newPair);
}
}
ModifyModifierCommand *command = new ModifyModifierCommand(this, _modifiers.indexOf(modifier), undoProperties, redoProperties);
UndoManager::instance().push(command);
command->activate();
}
void ModifierModel::modifierChanging() {
if (_disableUndo)
return;
core::Modifier *modifier = static_cast<core::Modifier*>(sender());
_changingModifierOldProperties = modifier->serializeProperties();
}
void ModifierModel::beginUndoAction() {
_disableUndo = true;
}
void ModifierModel::endUndoAction() {
_disableUndo = false;
}
void ModifierModel::moveModifier(int sourceRow, int destinationRow) {
Q_ASSERT_X(sourceRow >= 0 && sourceRow < rowCount(), "ModifierModel::moveModifier()", qPrintable(QString("<sourceRow> is out of bound: %d!").arg(sourceRow)));
if (sourceRow == destinationRow) // Save destination => do nothing
return;
if (destinationRow >= rowCount() - 1 &&
sourceRow == rowCount() - 1) // Already at the list queue => do nothing
return;
beginRemoveRows(QModelIndex(), sourceRow, sourceRow);
core::Modifier *modifier = _modifiers.takeAt(sourceRow);
endRemoveRows();
beginInsertRows(QModelIndex(), destinationRow, destinationRow);
_modifiers.insert(destinationRow, modifier);
endInsertRows();
emit modifiersChanged();
if (!_disableUndo) {
MoveModifierCommand *command = new MoveModifierCommand(this, sourceRow, destinationRow);
UndoManager::instance().push(command);
command->activate();
}
}
diff --git a/renamah/paths.cpp b/renamah/paths.cpp
new file mode 100644
index 0000000..f66dd8f
--- /dev/null
+++ b/renamah/paths.cpp
@@ -0,0 +1,51 @@
+/*
+ * Renamah
+ * Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
+ *
+ * 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
+ * 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 <QDir>
+#include <QCoreApplication>
+#include <QDesktopServices>
+
+#include "global.h"
+
+#include "paths.h"
+
+QString Paths::sharePath()
+{
+ QDir appDir(QCoreApplication::applicationDirPath());
+
+ if (Global::devMode())
+ return QDir(appDir.filePath("../share/renamah")).canonicalPath();
+
+ if (Global::localMode())
+ return appDir.absolutePath();
+
+
+#if defined(Q_OS_LINUX)
+ return QDir(appDir.filePath("/usr/share/renamah")).canonicalPath();
+#else
+ return appDir.absolutePath();
+#endif
+}
+
+QString Paths::profilePath()
+{
+ if (Global::devMode() || Global::localMode())
+ return QDir(QCoreApplication::applicationDirPath()).filePath(qApp->applicationName());
+
+ return QDesktopServices::storageLocation(QDesktopServices::DataLocation);
+}
diff --git a/renamah/paths.h b/renamah/paths.h
new file mode 100644
index 0000000..2249390
--- /dev/null
+++ b/renamah/paths.h
@@ -0,0 +1,30 @@
+/*
+ * Renamah
+ * Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
+ *
+ * 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
+ * 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/>.
+ */
+
+#ifndef PATHS_H
+#define PATHS_H
+
+#include <QString>
+
+namespace Paths
+{
+ QString sharePath();
+ QString profilePath();
+};
+
+#endif
diff --git a/renamah/widget_modifiers.ui b/renamah/widget_modifiers.ui
index 290c00d..c540d59 100644
--- a/renamah/widget_modifiers.ui
+++ b/renamah/widget_modifiers.ui
@@ -1,404 +1,404 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WidgetModifiers</class>
<widget class="QWidget" name="WidgetModifiers">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>677</width>
<height>239</height>
</rect>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QSplitter" name="splitterMain">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QWidget" name="widgetModifiers" native="true">
<layout class="QGridLayout" name="gridLayout_12">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayoutModifiers">
<item row="0" column="0" colspan="5">
<widget class="QTreeView" name="treeView">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragEnabled">
<bool>true</bool>
</property>
<property name="dragDropMode">
- <enum>QAbstractItemView::InternalMove</enum>
+ <enum>QAbstractItemView::DragDrop</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="animated">
<bool>true</bool>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="pushButtonAdd">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="pushButtonRemove">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
</widget>
</item>
<item row="1" column="4">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="2">
<widget class="QPushButton" name="pushButtonUp">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
</widget>
</item>
<item row="1" column="3">
<widget class="QPushButton" name="pushButtonDown">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QStackedWidget" name="stackedWidgetConfiguration">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="pageConfiguration">
<layout class="QGridLayout" name="gridLayout_14">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QWidget" name="widgetModifierConfig" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QGridLayout" name="gridLayout_15">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QFrame" name="frameConfiguration">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="palette">
<palette>
<active>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>210</blue>
</color>
</brush>
</colorrole>
</active>
<inactive>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>210</blue>
</color>
</brush>
</colorrole>
</inactive>
<disabled>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>210</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>210</blue>
</color>
</brush>
</colorrole>
</disabled>
</palette>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QGridLayout" name="gridLayout_16">
<property name="verticalSpacing">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QLabel" name="labelModifierCaption">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string notr="true">Title</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelModifierDescription">
<property name="font">
<font>
<pointsize>8</pointsize>
</font>
</property>
<property name="text">
<string notr="true">Modifier description</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="1" column="0">
<widget class="QWidget" name="widgetConfig" native="true"/>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="pageNoModifiers">
<layout class="QGridLayout" name="gridLayout_17">
<item row="1" column="1">
<widget class="QLabel" name="labelAddModifier">
<property name="palette">
<palette>
<active>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
</active>
<inactive>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
</inactive>
<disabled>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>151</red>
<green>150</green>
<blue>150</blue>
</color>
</brush>
</colorrole>
</disabled>
</palette>
</property>
<property name="font">
<font>
<underline>true</underline>
</font>
</property>
<property name="cursor">
<cursorShape>PointingHandCursor</cursorShape>
</property>
<property name="lineWidth">
<number>1</number>
</property>
<property name="text">
<string>Click to add</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="0" column="1">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="1">
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="0">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="2">
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>
</widget>
<resources>
<include location="renamah.qrc"/>
</resources>
<connections/>
</ui>
|
Guid75/renamah
|
9c1acef1f6ac7622449a47c0a01085fa575f8b18
|
A first step toward the windows compilation
|
diff --git a/libcore/CMakeLists.txt b/libcore/CMakeLists.txt
index 2491693..e90fb19 100644
--- a/libcore/CMakeLists.txt
+++ b/libcore/CMakeLists.txt
@@ -1,38 +1,39 @@
INCLUDE(${QT_USE_FILE})
SET(LIBCORE_SOURCES
interfaces/modifier_config_widget.cpp
interfaces/modifier.cpp
)
SET(LIBCORE_FORMS
)
QT4_WRAP_UI(LIBCORE_FORMS_H ${LIBCORE_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(LIBCORE_MOCH
interfaces/modifier_config_widget.h
interfaces/modifier.h
interfaces/filter.h
interfaces/action.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
+ADD_DEFINITIONS(-DRENAMAH_LIBCORE_LIBRARY)
QT4_WRAP_CPP(LIBCORE_MOC ${LIBCORE_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
-IF(WIN32)
- ADD_LIBRARY(core WIN32 ${LIBCORE_SOURCES} ${LIBCORE_FORMS_H} ${LIBCORE_MOC})
-ELSE(WIN32)
- ADD_LIBRARY(core SHARED ${LIBCORE_SOURCES} ${LIBCORE_FORMS_H} ${LIBCORE_MOC})
-ENDIF(WIN32)
+ADD_LIBRARY(core SHARED ${LIBCORE_SOURCES} ${LIBCORE_FORMS_H} ${LIBCORE_MOC})
+
+IF(MSVC)
+ TARGET_LINK_LIBRARIES(core ${QT_LIBRARIES})
+ENDIF(MSVC)
diff --git a/libcore/interfaces/action.h b/libcore/interfaces/action.h
index de65544..0ae0483 100644
--- a/libcore/interfaces/action.h
+++ b/libcore/interfaces/action.h
@@ -1,39 +1,40 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef ACTION_H
#define ACTION_H
class QString;
+#include "global.h"
#include "modifier.h"
namespace core
{
- class Action : public Modifier
+ class Q_RENAMAH_LIBCORE_EXPORT Action : public Modifier
{
Q_OBJECT
public:
Action(QObject *parent = 0) : Modifier(parent) {}
/*! Apply the action on the filename in argument */
virtual void apply(const QString &fileName) const = 0;
};
};
#endif
diff --git a/libcore/interfaces/action_factory.h b/libcore/interfaces/action_factory.h
index dc5c61f..de27faf 100644
--- a/libcore/interfaces/action_factory.h
+++ b/libcore/interfaces/action_factory.h
@@ -1,40 +1,41 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef ACTION_FACTORY_H
#define ACTION_FACTORY_H
+#include "global.h"
#include "modifier_factory.h"
#include "action.h"
namespace core
{
class ActionFactory : public ModifierFactory
{
protected:
Modifier *createModifier() const { return createAction(); }
/*! True method to create a new filter */
virtual Action *createAction() const = 0;
};
};
Q_DECLARE_INTERFACE(core::ActionFactory,
"fr.free.guillaume.denry.Renamah.ActionFactory/1.0")
#endif
diff --git a/libcore/interfaces/filter.h b/libcore/interfaces/filter.h
index 8ee8c35..e40174e 100644
--- a/libcore/interfaces/filter.h
+++ b/libcore/interfaces/filter.h
@@ -1,44 +1,45 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FILTER_H
#define FILTER_H
class QString;
+#include "global.h"
#include "modifier.h"
#include "filter_file_info.h"
namespace core
{
- class Filter : public Modifier
+ class Q_RENAMAH_LIBCORE_EXPORT Filter : public Modifier
{
Q_OBJECT
public:
Filter(QObject *parent = 0) : Modifier(parent) {}
/*! Returns the filtered string of the parameter partToFilter which is a part of the parameter filePath
* \param partToFilter The filename part to filter
* \param filePath the complete file path
*/
virtual QString apply(const FilterFileInfo &fileInfo) const = 0;
};
};
#endif
diff --git a/libcore/interfaces/filter_factory.h b/libcore/interfaces/filter_factory.h
index 3896737..88b6b05 100644
--- a/libcore/interfaces/filter_factory.h
+++ b/libcore/interfaces/filter_factory.h
@@ -1,40 +1,41 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FILTER_FACTORY_H
#define FILTER_FACTORY_H
+#include "global.h"
#include "modifier_factory.h"
#include "filter.h"
namespace core
{
class FilterFactory : public ModifierFactory
{
protected:
Modifier *createModifier() const { return createFilter(); }
/*! True method to create a new filter */
virtual Filter *createFilter() const = 0;
};
};
Q_DECLARE_INTERFACE(core::FilterFactory,
"fr.free.guillaume.denry.Renamah.FilterFactory/1.0")
#endif
diff --git a/libcore/interfaces/filter_file_info.h b/libcore/interfaces/filter_file_info.h
index 6d22ecf..9a3336f 100644
--- a/libcore/interfaces/filter_file_info.h
+++ b/libcore/interfaces/filter_file_info.h
@@ -1,43 +1,45 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef FILTER_FILE_INFO_H
#define FILTER_FILE_INFO_H
class QString;
+#include "global.h"
+
namespace core
{
- class FilterFileInfo
+ class Q_RENAMAH_LIBCORE_EXPORT FilterFileInfo
{
public:
FilterFileInfo(const QString &originalFilePath,
const QString &partToFilter,
int fileIndex) {
this->originalFilePath = originalFilePath;
this->partToFilter = partToFilter;
this->fileIndex = fileIndex;
}
QString originalFilePath; //!< the complete original file path
QString partToFilter; //!< the file part to filter
int fileIndex; //!< the index of the file in all files to filter
};
};
#endif
diff --git a/libcore/interfaces/global.h b/libcore/interfaces/global.h
new file mode 100644
index 0000000..c3b2ce9
--- /dev/null
+++ b/libcore/interfaces/global.h
@@ -0,0 +1,30 @@
+/*
+ * Renamah
+ * Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
+ *
+ * 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
+ * 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/>.
+ */
+
+#ifndef RENAMAH_LIBCORE_GLOBAL_H
+#define RENAMAH_LIBCORE_GLOBAL_H
+
+#include <QtCore/qglobal.h>
+
+#if defined(RENAMAH_LIBCORE_LIBRARY)
+# define Q_RENAMAH_LIBCORE_EXPORT Q_DECL_EXPORT
+#else
+# define Q_RENAMAH_LIBCORE_EXPORT Q_DECL_IMPORT
+#endif
+
+#endif
diff --git a/libcore/interfaces/modifier.h b/libcore/interfaces/modifier.h
index df5e650..2d3477a 100644
--- a/libcore/interfaces/modifier.h
+++ b/libcore/interfaces/modifier.h
@@ -1,65 +1,66 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef MODIFIER_H
#define MODIFIER_H
#include <QObject>
#include <QMap>
#include <QPair>
#include <QVariant>
+#include "global.h"
#include "plugin.h"
namespace core
{
class ModifierFactory;
- class Modifier : public QObject
+ class Q_RENAMAH_LIBCORE_EXPORT Modifier : public QObject
{
Q_OBJECT
public:
Modifier(QObject *parent = 0) : QObject(parent) {}
friend class ModifierFactory;
/*! \return a resume string of the modifier action */
virtual QString resume() const = 0;
/*! \return the factory which generates the modifier */
ModifierFactory *factory() const { return _factory; }
/*! \return a map which contains all serializable properties of the modifier */
QMap<QString,QPair<QString,QVariant> > serializeProperties();
/*! Fill the object properties */
void deserializeProperties(const QMap<QString,QPair<QString,QVariant> > &properties);
signals:
/** Emitted when modifier settings changing, before new value is affected. */
void settingsChanging();
/** Emitted when modifier settings changed */
void settingsChanged();
private:
ModifierFactory *_factory;
};
};
#endif
diff --git a/libcore/interfaces/modifier_config_widget.h b/libcore/interfaces/modifier_config_widget.h
index 6cd4ded..5858359 100644
--- a/libcore/interfaces/modifier_config_widget.h
+++ b/libcore/interfaces/modifier_config_widget.h
@@ -1,59 +1,58 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef MODIFIER_CONFIG_WIDGET_H
#define MODIFIER_CONFIG_WIDGET_H
#include <QWidget>
#include <QEvent>
+#include "global.h"
#include "modifier.h"
namespace core
{
- class ModifierConfigWidget : public QWidget
+ class Q_RENAMAH_LIBCORE_EXPORT ModifierConfigWidget : public QWidget
{
Q_OBJECT
public:
ModifierConfigWidget(QWidget *parent = 0)
: QWidget(parent),
_modifier(0),
languageChanging(false) {}
Modifier *modifier() const { return _modifier; }
void setModifier(Modifier *modifier);
protected:
virtual void changeEvent(QEvent *event);
virtual void languageChanged() {}
bool isLanguageChanging() const { return languageChanging; }
protected slots:
virtual void refreshControls() = 0; //!< Is called at every modifier settings changed and after setModifier()
private:
Modifier *_modifier;
bool languageChanging;
};
};
-#endif \
-
-
+#endif
diff --git a/libcore/interfaces/modifier_factory.h b/libcore/interfaces/modifier_factory.h
index 76ceb5b..92a7df1 100644
--- a/libcore/interfaces/modifier_factory.h
+++ b/libcore/interfaces/modifier_factory.h
@@ -1,50 +1,51 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef MODIFIER_FACTORY_H
#define MODIFIER_FACTORY_H
+#include "global.h"
#include "plugin.h"
#include "modifier.h"
#include "modifier_config_widget.h"
namespace core
{
class ModifierFactory : public Plugin
{
public:
/*! Make a new modifier. Just a call to createModifier() and some parentality done */
Modifier *makeModifier() const {
Modifier *modifier = createModifier();
modifier->_factory = const_cast<ModifierFactory*>(this);
return modifier;
}
/*! Returns a configuration QWidget */
virtual ModifierConfigWidget *makeConfigurationWidget(Modifier *modifier) const { return 0; }
/*! Deletes the configuration widget in argument (mandatory for shared lib) */
virtual void deleteConfigurationWidget(QWidget *widget) const { delete widget; }
protected:
/*! True method to create a new modifier */
virtual Modifier *createModifier() const = 0;
};
};
#endif
diff --git a/libcore/interfaces/plugin.h b/libcore/interfaces/plugin.h
index dbc064a..7e2255f 100644
--- a/libcore/interfaces/plugin.h
+++ b/libcore/interfaces/plugin.h
@@ -1,34 +1,35 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef PLUGIN_H
#define PLUGIN_H
+#include "global.h"
#include "plugin_info.h"
namespace core
{
- class Plugin
+ class Q_RENAMAH_LIBCORE_EXPORT Plugin
{
public:
/*! Returns all infos relatives to the plugin (name, author, etc) */
virtual PluginInfo info() const = 0;
};
};
#endif
diff --git a/libcore/interfaces/plugin_info.h b/libcore/interfaces/plugin_info.h
index 31003cb..8b03578 100644
--- a/libcore/interfaces/plugin_info.h
+++ b/libcore/interfaces/plugin_info.h
@@ -1,48 +1,48 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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/>.
*/
#ifndef PLUGIN_INFO_H
#define PLUGIN_INFO_H
#include <QString>
namespace core
{
- class PluginInfo
+ class Q_RENAMAH_LIBCORE_EXPORT PluginInfo
{
public:
PluginInfo(const QString &name,
const QString &caption,
const QString &description = "",
const QString &author = "") :
_name(name), _caption(caption), _description(description), _author(author) {}
const QString &name() const { return _name; }
const QString &caption() const { return _caption; }
const QString &description() const { return _description; }
const QString &author() const { return _author; }
private:
QString _name;
QString _caption;
QString _description;
QString _author;
};
}
#endif
diff --git a/plugins/casefilter/CMakeLists.txt b/plugins/casefilter/CMakeLists.txt
index e7e914c..92cc877 100644
--- a/plugins/casefilter/CMakeLists.txt
+++ b/plugins/casefilter/CMakeLists.txt
@@ -1,39 +1,43 @@
INCLUDE(${QT_USE_FILE})
SET(CASEFILTER_SOURCES
case_filter_factory.cpp
case_filter.cpp
config_widget.cpp
)
SET(CASEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CASEFILTER_FORMS_H ${CASEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CASEFILTER_MOCH
case_filter.h
case_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CASEFILTER_MOC ${CASEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS} ${CASEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_casefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(casefilter SHARED ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS_H} ${CASEFILTER_MOC})
+IF(MSVC)
+ TARGET_LINK_LIBRARIES(casefilter core ${QT_LIBRARIES})
+ENDIF(MSVC)
+
ADD_DEPENDENCIES(casefilter translations_casefilter)
diff --git a/plugins/commandaction/CMakeLists.txt b/plugins/commandaction/CMakeLists.txt
index addbc40..d0113c3 100644
--- a/plugins/commandaction/CMakeLists.txt
+++ b/plugins/commandaction/CMakeLists.txt
@@ -1,47 +1,47 @@
INCLUDE(${QT_USE_FILE})
SET(COMMANDACTION_SOURCES
command_action_factory.cpp
command_action.cpp
config_widget.cpp
process_handler.cpp
)
SET(COMMANDACTION_FORMS
config_widget.ui
)
QT4_WRAP_UI(COMMANDACTION_FORMS_H ${COMMANDACTION_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(COMMANDACTION_MOCH
command_action.h
command_action_factory.h
config_widget.h
process_handler.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(COMMANDACTION_MOC ${COMMANDACTION_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS} ${COMMANDACTION_MOCH})
ADD_CUSTOM_TARGET(translations_commandaction DEPENDS ${QM_FILES})
-IF(WIN32)
- ADD_LIBRARY(commandaction WIN32 ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
-ELSE(WIN32)
- ADD_LIBRARY(commandaction SHARED ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
-ENDIF(WIN32)
+ADD_LIBRARY(commandaction SHARED ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
+
+IF(MSVC)
+ TARGET_LINK_LIBRARIES(commandaction core ${QT_LIBRARIES})
+ENDIF(MSVC)
ADD_DEPENDENCIES(commandaction translations_commandaction)
diff --git a/plugins/cutterfilter/CMakeLists.txt b/plugins/cutterfilter/CMakeLists.txt
index 90a32bd..3a48697 100644
--- a/plugins/cutterfilter/CMakeLists.txt
+++ b/plugins/cutterfilter/CMakeLists.txt
@@ -1,38 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(CUTTERFILTER_SOURCES
cutter_filter_factory.cpp
cutter_filter.cpp
config_widget.cpp
)
SET(CUTTERFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CUTTERFILTER_FORMS_H ${CUTTERFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CUTTERFILTER_MOCH
cutter_filter.h
cutter_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CUTTERFILTER_MOC ${CUTTERFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS} ${CUTTERFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_cutterfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(cutterfilter SHARED ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS_H} ${CUTTERFILTER_MOC})
+IF(MSVC)
+ TARGET_LINK_LIBRARIES(cutterfilter core ${QT_LIBRARIES})
+ENDIF(MSVC)
+
ADD_DEPENDENCIES(cutterfilter translations_cutterfilter)
diff --git a/plugins/datefilter/CMakeLists.txt b/plugins/datefilter/CMakeLists.txt
index 6211874..51a2c66 100644
--- a/plugins/datefilter/CMakeLists.txt
+++ b/plugins/datefilter/CMakeLists.txt
@@ -1,40 +1,44 @@
INCLUDE(${QT_USE_FILE})
SET(DATEFILTER_SOURCES
date_filter_factory.cpp
date_filter.cpp
config_widget.cpp
)
SET(DATEFILTER_FORMS
config_widget.ui
help_widget.ui
)
QT4_WRAP_UI(DATEFILTER_FORMS_H ${DATEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(DATEFILTER_MOCH
date_filter.h
date_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(DATEFILTER_MOC ${DATEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS} ${DATEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_datefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(datefilter SHARED ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS_H} ${DATEFILTER_MOC})
+IF(MSVC)
+ TARGET_LINK_LIBRARIES(datefilter core ${QT_LIBRARIES})
+ENDIF(MSVC)
+
ADD_DEPENDENCIES(datefilter translations_datefilter)
diff --git a/plugins/numberingfilter/CMakeLists.txt b/plugins/numberingfilter/CMakeLists.txt
index d4fee17..cdff17a 100644
--- a/plugins/numberingfilter/CMakeLists.txt
+++ b/plugins/numberingfilter/CMakeLists.txt
@@ -1,38 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(NUMBERINGFILTER_SOURCES
numbering_filter_factory.cpp
numbering_filter.cpp
config_widget.cpp
)
SET(NUMBERINGFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(NUMBERINGFILTER_FORMS_H ${NUMBERINGFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(NUMBERINGFILTER_MOCH
numbering_filter.h
numbering_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(NUMBERINGFILTER_MOC ${NUMBERINGFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS} ${NUMBERINGFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_numberingfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(numberingfilter SHARED ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS_H} ${NUMBERINGFILTER_MOC})
+IF(MSVC)
+ TARGET_LINK_LIBRARIES(numberingfilter core ${QT_LIBRARIES})
+ENDIF(MSVC)
+
ADD_DEPENDENCIES(numberingfilter translations_numberingfilter)
diff --git a/plugins/replacefilter/CMakeLists.txt b/plugins/replacefilter/CMakeLists.txt
index a5f40ec..75d6d6c 100644
--- a/plugins/replacefilter/CMakeLists.txt
+++ b/plugins/replacefilter/CMakeLists.txt
@@ -1,38 +1,42 @@
INCLUDE(${QT_USE_FILE})
SET(REPLACEFILTER_SOURCES
replace_filter_factory.cpp
replace_filter.cpp
config_widget.cpp
)
SET(REPLACEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(REPLACEFILTER_FORMS_H ${REPLACEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(REPLACEFILTER_MOCH
replace_filter.h
replace_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(REPLACEFILTER_MOC ${REPLACEFILTER_MOCH})
# Translations rules
COMPUTE_QM_FILES(QM_FILES ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS} ${REPLACEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_replacefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(replacefilter SHARED ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS_H} ${REPLACEFILTER_MOC})
+IF(MSVC)
+ TARGET_LINK_LIBRARIES(replacefilter core ${QT_LIBRARIES})
+ENDIF(MSVC)
+
ADD_DEPENDENCIES(replacefilter translations_replacefilter)
diff --git a/renamah/modifier_model.cpp b/renamah/modifier_model.cpp
index 94c0c89..6c4d042 100644
--- a/renamah/modifier_model.cpp
+++ b/renamah/modifier_model.cpp
@@ -1,382 +1,383 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 <QMimeData>
#include <interfaces/modifier_factory.h>
#include "undo_manager.h"
#include "modifier_model.h"
ModifierModel::ModifierModel(ModifierManager *manager)
: _manager(manager),
_exclusiveModifier(0),
_disableUndo(false)
{
}
int ModifierModel::rowCount(const QModelIndex &parent) const
{
return _modifiers.count();
}
int ModifierModel::columnCount(const QModelIndex &parent) const
{
return columnNumber;
}
QVariant ModifierModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= _modifiers.count())
return QVariant();
const core::Modifier *modifier = _modifiers[index.row()];
switch (role)
{
case Qt::DisplayRole:
switch (index.column())
{
case colIndex: return index.row() + 1;
case colMode: return "";
case colCaption: return modifier->factory()->info().caption() + " [" + modifier->resume() + "]";
default:;
}
case Qt::ForegroundRole:
if (_exclusiveModifier && _exclusiveModifier != modifier)
return Qt::gray;
break;
default:;
}
return QVariant();
}
QVariant ModifierModel::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role)
{
case Qt::DisplayRole:
switch (section)
{
case colIndex: return tr("#");
case colMode: return tr("Mode");
case colCaption: return tr("Action");
default:;
}
break;
default:;
}
return QVariant();
}
void ModifierModel::init(core::Modifier *modifier) {
connect(modifier, SIGNAL(settingsChanging()), this, SLOT(modifierChanging()));
connect(modifier, SIGNAL(settingsChanged()), this, SLOT(modifierChanged()));
connect(modifier, SIGNAL(settingsChanged()), this, SIGNAL(modifiersChanged()));
}
void ModifierModel::addModifier(core::Modifier *modifier)
{
init(modifier);
beginInsertRows(QModelIndex(), _modifiers.count(), _modifiers.count());
_modifiers << modifier;
_modifierStates[modifier] = true;
endInsertRows();
if (!_disableUndo) {
CreateModifierCommand *command = new CreateModifierCommand(this, _manager, modifier->factory()->info().name());
UndoManager::instance().push(command);
command->activate();
}
emit modifiersChanged();
}
void ModifierModel::insertModifier(int index, core::Modifier *modifier) {
init(modifier);
beginInsertRows(QModelIndex(), index, index);
_modifiers.insert(index, modifier);
_modifierStates[modifier] = true;
endInsertRows();
// TODO : integrate into the undo framework!!!
emit modifiersChanged();
}
void ModifierModel::removeModifier(const QModelIndex &index)
{
if (!index.isValid())
return;
removeRows(index.row(), 1);
}
bool ModifierModel::modifierState(core::Modifier *modifier) const
{
if (_modifierStates.find(modifier) == _modifierStates.end())
return false;
else
return _modifierStates[modifier];
}
void ModifierModel::setModifierState(core::Modifier *modifier, bool state)
{
int modifierRow = _modifiers.indexOf(modifier);
if (modifierRow < 0)
return;
if (_modifierStates[modifier] != state)
{
_modifierStates[modifier] = state;
emit dataChanged(index(modifierRow, 0), index(modifierRow, columnNumber - 1));
emit modifiersChanged();
}
}
void ModifierModel::toggleModifierState(core::Modifier *modifier)
{
if (_modifierStates.find(modifier) == _modifierStates.end())
return;
setModifierState(modifier, !_modifierStates[modifier]);
}
void ModifierModel::setExclusiveModifier(core::Modifier *modifier)
{
if (_exclusiveModifier == modifier)
return;
_exclusiveModifier = modifier;
if (modifier)
_modifierStates[modifier] = true;
// Refresh all
emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
emit modifiersChanged();
}
/*QString ModifierModel::apply(const QString &str) const
{
if (_exclusiveModifier)
return _exclusiveModifier->apply(str);
QString filtered = str;
foreach (core::Filter *filter, _modifiers)
if (_modifierstates[filter])
filtered = filter->apply(filtered);
return filtered;
}*/
core::Modifier *ModifierModel::modifier(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
- if (index.row() >= 0 && index.row() < rowCount())
- return _modifiers[index.row()];
+ return _modifiers[index.row()];
}
Qt::ItemFlags ModifierModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractListModel::flags(index);
if (index.isValid())
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
else
return Qt::ItemIsDropEnabled | flags;
}
void ModifierModel::toggleExclusiveState(core::Modifier *modifier)
{
if (_exclusiveModifier == modifier)
_exclusiveModifier = 0;
else
_exclusiveModifier = modifier;
if (_exclusiveModifier)
_modifierStates[_exclusiveModifier] = true;
// Refresh all
emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
emit modifiersChanged();
}
Qt::DropActions ModifierModel::supportedDropActions() const {
return Qt::MoveAction;
}
bool ModifierModel::removeRows(int row, int count, const QModelIndex &parent) {
core::Modifier *modifierToRemove = modifier(index(row, 0));
if (!_disableUndo) {
RemoveModifierCommand *command = new RemoveModifierCommand(this, _manager, row, modifierToRemove->factory()->info().name(),
modifierToRemove->serializeProperties());
UndoManager::instance().push(command);
command->activate();
}
beginRemoveRows(QModelIndex(), row, row);
_modifiers.removeAt(_modifiers.indexOf(modifierToRemove));
_modifierStates.remove(modifierToRemove);
if (_exclusiveModifier == modifierToRemove)
_exclusiveModifier = 0;
delete modifierToRemove;
endRemoveRows();
emit modifiersChanged();
+
+ return true;
}
#define MIMETYPE QLatin1String("filter-rows")
QStringList ModifierModel::mimeTypes() const
{
QStringList types;
types << MIMETYPE;
return types;
}
QMimeData *ModifierModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *mimeData = new QMimeData;
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
stream << index.row();
}
}
mimeData->setData(MIMETYPE, encodedData);
return mimeData;
}
bool ModifierModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
if (action == Qt::IgnoreAction)
return false;
QByteArray inData = data->data(MIMETYPE);
QDataStream stream(inData);
int sourceRow;
stream >> sourceRow;
int destinationRow = rowCount();
if (row != -1) {
if (row >= rowCount()) {
destinationRow = rowCount();
} else {
if (sourceRow < row)
row--;
destinationRow = row;
}
} else if (parent.isValid()) {
destinationRow = parent.row();
} else if (!parent.isValid()) {
destinationRow = rowCount();
}
moveModifier(sourceRow, destinationRow);
return false;
}
void ModifierModel::clear() {
_exclusiveModifier = 0;
qDeleteAll(_modifiers);
_modifiers.clear();
_modifierStates.clear();
reset();
emit modifiersChanged();
}
void ModifierModel::modifierChanged() {
if (_disableUndo)
return;
core::Modifier *modifier = static_cast<core::Modifier*>(sender());
// Undo managing => compute the diff
QMap<QString,QPair<QString,QVariant> > newProperties = modifier->serializeProperties();
QMap<QString,QPair<QString,QVariant> > &oldProperties = _changingModifierOldProperties;
QMap<QString,QPair<QString,QVariant> > undoProperties, redoProperties;
foreach (const QString &propName, newProperties.keys()) {
QPair<QString,QVariant> &newPair = newProperties[propName];
QPair<QString,QVariant> &oldPair = oldProperties[propName];
if (newPair != oldPair) {
undoProperties.insert(propName, oldPair);
redoProperties.insert(propName, newPair);
}
}
ModifyModifierCommand *command = new ModifyModifierCommand(this, _modifiers.indexOf(modifier), undoProperties, redoProperties);
UndoManager::instance().push(command);
command->activate();
}
void ModifierModel::modifierChanging() {
if (_disableUndo)
return;
core::Modifier *modifier = static_cast<core::Modifier*>(sender());
_changingModifierOldProperties = modifier->serializeProperties();
}
void ModifierModel::beginUndoAction() {
_disableUndo = true;
}
void ModifierModel::endUndoAction() {
_disableUndo = false;
}
void ModifierModel::moveModifier(int sourceRow, int destinationRow) {
Q_ASSERT_X(sourceRow >= 0 && sourceRow < rowCount(), "ModifierModel::moveModifier()", qPrintable(QString("<sourceRow> is out of bound: %d!").arg(sourceRow)));
if (sourceRow == destinationRow) // Save destination => do nothing
return;
if (destinationRow >= rowCount() - 1 &&
sourceRow == rowCount() - 1) // Already at the list queue => do nothing
return;
beginRemoveRows(QModelIndex(), sourceRow, sourceRow);
core::Modifier *modifier = _modifiers.takeAt(sourceRow);
endRemoveRows();
beginInsertRows(QModelIndex(), destinationRow, destinationRow);
_modifiers.insert(destinationRow, modifier);
endInsertRows();
emit modifiersChanged();
if (!_disableUndo) {
MoveModifierCommand *command = new MoveModifierCommand(this, sourceRow, destinationRow);
UndoManager::instance().push(command);
command->activate();
}
}
diff --git a/renamah/widget_simple.ui b/renamah/widget_simple.ui
index 09f9e93..c2d8069 100644
--- a/renamah/widget_simple.ui
+++ b/renamah/widget_simple.ui
@@ -1,526 +1,526 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WidgetSimple</class>
<widget class="QWidget" name="WidgetSimple">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>676</width>
<height>571</height>
</rect>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QGridLayout" name="gridLayout_6">
<item row="0" column="0">
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QWidget" name="widgetFiles" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<layout class="QGridLayout" name="gridLayout_5">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="4">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButtonProcess">
<property name="text">
<string>Process</string>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/process.png</normaloff>:/images/process.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="comboBoxOperation">
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContents</enum>
</property>
<item>
<property name="text">
<string>Rename files</string>
</property>
</item>
<item>
<property name="text">
<string>Copy renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Move renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Create symbolic links in</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEditDestination">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="toolButtonDestination">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
- <item row="1" column="0" colspan="3">
+ <item row="1" column="0" colspan="4">
<widget class="QFrame" name="frameOperation">
<property name="frameShape">
<enum>QFrame::HLine</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item row="2" column="2" colspan="2">
<widget class="QPushButton" name="pushButtonAddFiles">
<property name="toolTip">
<string>Add some files...</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
</widget>
</item>
<item row="3" column="2" colspan="2">
<widget class="QPushButton" name="pushButtonRemoveFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
</widget>
</item>
<item row="6" column="2" colspan="2">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>258</height>
</size>
</property>
</spacer>
</item>
<item row="7" column="2" colspan="2">
<widget class="QLabel" name="labelFileCount">
<property name="frameShape">
<enum>QFrame::Panel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<property name="text">
<string notr="true">13 files</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="4" column="2" colspan="2">
<widget class="QPushButton" name="pushButtonSort">
<property name="text">
<string>Sort by</string>
</property>
</widget>
</item>
<item row="5" column="2">
<widget class="QPushButton" name="pushButtonUpFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Up selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
</widget>
</item>
<item row="5" column="3">
<widget class="QPushButton" name="pushButtonDownFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Down selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
</widget>
</item>
<item row="2" column="1" rowspan="6">
<widget class="QStackedWidget" name="stackedWidgetFiles">
<property name="currentIndex">
<number>1</number>
</property>
<widget class="QWidget" name="pageFiles">
<layout class="QGridLayout" name="gridLayout_7">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QTreeView" name="treeViewFiles">
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragEnabled">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::InternalMove</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="animated">
<bool>true</bool>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="pageNoFiles">
<layout class="QGridLayout" name="gridLayout_8">
<item row="0" column="1">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>190</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>200</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="1">
<widget class="QLabel" name="labelAddFiles">
<property name="palette">
<palette>
<active>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
</active>
<inactive>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
</inactive>
<disabled>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>151</red>
<green>150</green>
<blue>150</blue>
</color>
</brush>
</colorrole>
</disabled>
</palette>
</property>
<property name="font">
<font>
<underline>true</underline>
</font>
</property>
<property name="cursor">
<cursorShape>PointingHandCursor</cursorShape>
</property>
<property name="lineWidth">
<number>1</number>
</property>
<property name="text">
<string>Click to add some files</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="2">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>200</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="1">
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>90</width>
<height>190</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QTabWidget" name="tabWidgetOperations">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabExtensionPolicy">
<attribute name="title">
<string>Extension policy</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QScrollArea" name="scrollArea">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>652</width>
<height>57</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetExtensionPolicy" name="widgetExtensionPolicy" native="true"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabFilters">
<attribute name="title">
<string>Filters</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_4">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetFilters" name="widgetFilters" native="true"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabEnders">
<attribute name="title">
<string>Finalizers</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_18">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetActions" name="widgetFinalizers" native="true"/>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>
<action name="actionSortByName">
<property name="text">
<string>by name</string>
</property>
<property name="toolTip">
<string>Sort files by name</string>
</property>
</action>
<action name="actionSortByModificationDate">
<property name="text">
<string>by modification date</string>
</property>
</action>
<action name="actionRemoveSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
<property name="text">
<string>&Remove</string>
</property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
</action>
<action name="actionAddFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
<property name="text">
<string>&Add</string>
</property>
<property name="toolTip">
<string>Add files</string>
</property>
</action>
<action name="actionUpSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
<property name="text">
<string>&Up</string>
</property>
<property name="toolTip">
<string>Up selected files</string>
</property>
</action>
<action name="actionDownSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
<property name="text">
<string>&Down</string>
</property>
<property name="toolTip">
<string>Down selected files</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>WidgetExtensionPolicy</class>
<extends>QWidget</extends>
<header>widget_extension_policy.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetActions</class>
<extends>QWidget</extends>
<header>widget_actions.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetFilters</class>
<extends>QWidget</extends>
<header>widget_filters.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources>
<include location="renamah.qrc"/>
</resources>
<connections/>
</ui>
|
Guid75/renamah
|
2f0aaf8f6f330431ca180b3c8e65597baad51dc1
|
Dealing with roman upper limit
|
diff --git a/plugins/numberingfilter/numbering_filter.cpp b/plugins/numberingfilter/numbering_filter.cpp
index 9dd83ae..eca0a2c 100644
--- a/plugins/numberingfilter/numbering_filter.cpp
+++ b/plugins/numberingfilter/numbering_filter.cpp
@@ -1,172 +1,175 @@
/*
* Renamah
* Copyright (C) 2009 Guillaume Denry <guillaume.denry@gmail.com>
*
* 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
* 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 "numbering_filter.h"
NumberingFilter::NumberingFilter(QObject *parent)
: core::Filter(parent),
_start(1), _step(1), _separator("_"), _displayType(Numeric), _base(10), _padding(0),
_insertionMode(Prefix), _customInsertionIndex(0) {
}
QString NumberingFilter::apply(const core::FilterFileInfo &fileInfo) const {
QString trueIndex;
switch (_displayType) {
case Numeric:
trueIndex = QString("%1").arg(_start + _step * fileInfo.fileIndex, _padding,
_base, QChar('0')).toUpper();
break;
case UpperRoman:
trueIndex = toRoman(_start + _step * fileInfo.fileIndex);
break;
case LowerRoman:
trueIndex = toRoman(_start + _step * fileInfo.fileIndex).toLower();
break;
case UpperAlpha:
trueIndex = toAlphabetic(_start + _step * fileInfo.fileIndex, _padding);
break;
case LowerAlpha:
trueIndex = toAlphabetic(_start + _step * fileInfo.fileIndex, _padding).toLower();
break;
default:;
}
switch (_insertionMode) {
case Prefix:
return QString("%1%2%3").arg(trueIndex).arg(_separator).arg(fileInfo.partToFilter);
case Suffix:
return QString("%1%2%3").arg(fileInfo.partToFilter).arg(_separator).arg(trueIndex);
case CustomPosition:
{
QString result = fileInfo.partToFilter;
QString insertionText = trueIndex;
if (_customInsertionIndex > 0)
insertionText = _separator + insertionText;
if (_customInsertionIndex <= result.length() - 1)
insertionText += _separator;
return result.insert(_customInsertionIndex, insertionText);
}
default:;
}
return fileInfo.partToFilter;
}
QString NumberingFilter::resume() const {
return tr("Start: %1, Step: %2").arg(_start).arg(_step);
}
QString NumberingFilter::toRoman(int n) {
+ if (n < 1 || n > 3999)
+ return QString::number(n);
+
QString result;
static int values[] = { 1000, 900, 500, 400, 100,90, 50, 40, 10, 9, 5, 4, 1 };
static QString numerals[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
for (int i = 0; i < 13; i++) {
while (n >= values[i]) {
n -= values[i];
result += numerals[i];
}
}
return result;
}
QString NumberingFilter::toAlphabetic(int n, int padding)
{
QString result;
do {
int q = n / 26;
int r = n - (q * 26);
result = QChar('A' + r) + result;
n = q;
} while (n);
if (result.length() < padding)
result = QString(padding - result.length(), 'A') + result;
return result;
}
void NumberingFilter::setStart(int value) {
if (_start == value)
return;
emit settingsChanging();
_start = value;
emit settingsChanged();
}
void NumberingFilter::setStep(int value) {
if (_step == value)
return;
emit settingsChanging();
_step = value;
emit settingsChanged();
}
void NumberingFilter::setSeparator(const QString &value) {
if (_separator == value)
return;
emit settingsChanging();
_separator = value;
emit settingsChanged();
}
void NumberingFilter::setDisplayType(DisplayType value) {
if (_displayType == value)
return;
emit settingsChanging();
_displayType = value;
emit settingsChanged();
}
void NumberingFilter::setBase(int value) {
if (_base == value)
return;
emit settingsChanging();
_base = value;
emit settingsChanged();
}
void NumberingFilter::setPadding(int value) {
if (_padding == value)
return;
emit settingsChanging();
_padding = value;
emit settingsChanged();
}
void NumberingFilter::setInsertionMode(InsertionMode value) {
if (_insertionMode == value)
return;
emit settingsChanging();
_insertionMode = value;
emit settingsChanged();
}
void NumberingFilter::setCustomInsertionIndex(int value) {
if (_customInsertionIndex == value)
return;
emit settingsChanging();
_customInsertionIndex = value;
emit settingsChanged();
}
|
Guid75/renamah
|
4514b55713910a01851983b44735f7b381e02838
|
dependency added (libqt4-xml)
|
diff --git a/README b/README
index d53d371..f3c0078 100644
--- a/README
+++ b/README
@@ -1,47 +1,48 @@
--------
WELCOME!
--------
Renamah is a(nother) batch renamer written in C++.
The effort is oriented toward:
* ergonomy
* the crossplatform aspect (Qt4)
* modularity (plugin system for filters)
Featuring:
* cascading filters: replace, numbering, cutter, case manipulations, etc
* cascading finalizers: launching of a system command for each files, etc
* undo system
* internationalization (French and English for now)
--------------------
INSTALL INSTRUCTIONS
--------------------
In the renamah root directory, type:
cmake .
make
sudo make install
------------
DEPENDENCIES
------------
To be successfully compiled, Renamah depends on some libraries:
- libqt4-core
- libqt4-gui
+- libqt4-xml
------------
THE END WORD
------------
You can find Renamah homepage at: http://github.com/Guid75/renamah
Thank you for using it!
Guillaume Denry <guillaume.denry@gmail.com>
|
Guid75/renamah
|
08a782972e05fb3a6f7ab48493d81afea7896c38
|
undo framework partially implemented
|
diff --git a/README b/README
index ce56295..d53d371 100644
--- a/README
+++ b/README
@@ -1,47 +1,47 @@
--------
WELCOME!
--------
Renamah is a(nother) batch renamer written in C++.
The effort is oriented toward:
* ergonomy
* the crossplatform aspect (Qt4)
* modularity (plugin system for filters)
Featuring:
* cascading filters: replace, numbering, cutter, case manipulations, etc
* cascading finalizers: launching of a system command for each files, etc
- * undo system (TODO)
+ * undo system
* internationalization (French and English for now)
--------------------
INSTALL INSTRUCTIONS
--------------------
In the renamah root directory, type:
cmake .
make
sudo make install
------------
DEPENDENCIES
------------
To be successfully compiled, Renamah depends on some libraries:
- libqt4-core
- libqt4-gui
------------
THE END WORD
------------
You can find Renamah homepage at: http://github.com/Guid75/renamah
Thank you for using it!
Guillaume Denry <guillaume.denry@gmail.com>
|
Guid75/renamah
|
31c8beddd0c37fc13a966aabc1c4ef8dc8f43bea
|
move actions are integrated in the undo framework
|
diff --git a/renamah/modifier_model.cpp b/renamah/modifier_model.cpp
index 30e929c..8bacad7 100644
--- a/renamah/modifier_model.cpp
+++ b/renamah/modifier_model.cpp
@@ -1,369 +1,364 @@
#include <QMimeData>
#include <interfaces/modifier_factory.h>
#include "undo_manager.h"
#include "modifier_model.h"
ModifierModel::ModifierModel(ModifierManager *manager)
: _manager(manager),
_exclusiveModifier(0),
_disableUndo(false)
{
}
int ModifierModel::rowCount(const QModelIndex &parent) const
{
return _modifiers.count();
}
int ModifierModel::columnCount(const QModelIndex &parent) const
{
return columnNumber;
}
QVariant ModifierModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= _modifiers.count())
return QVariant();
const core::Modifier *modifier = _modifiers[index.row()];
switch (role)
{
case Qt::DisplayRole:
switch (index.column())
{
case colIndex: return index.row() + 1;
case colMode: return "";
case colCaption: return modifier->factory()->info().caption() + " [" + modifier->resume() + "]";
default:;
}
case Qt::ForegroundRole:
if (_exclusiveModifier && _exclusiveModifier != modifier)
return Qt::gray;
break;
default:;
}
return QVariant();
}
QVariant ModifierModel::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role)
{
case Qt::DisplayRole:
switch (section)
{
case colIndex: return tr("#");
case colMode: return tr("Mode");
case colCaption: return tr("Action");
default:;
}
break;
default:;
}
return QVariant();
}
void ModifierModel::init(core::Modifier *modifier) {
connect(modifier, SIGNAL(settingsChanging()), this, SLOT(modifierChanging()));
connect(modifier, SIGNAL(settingsChanged()), this, SLOT(modifierChanged()));
connect(modifier, SIGNAL(settingsChanged()), this, SIGNAL(modifiersChanged()));
}
void ModifierModel::addModifier(core::Modifier *modifier)
{
init(modifier);
beginInsertRows(QModelIndex(), _modifiers.count(), _modifiers.count());
_modifiers << modifier;
_modifierStates[modifier] = true;
endInsertRows();
if (!_disableUndo) {
CreateModifierCommand *command = new CreateModifierCommand(this, _manager, modifier->factory()->info().name());
UndoManager::instance().push(command);
command->activate();
}
emit modifiersChanged();
}
void ModifierModel::insertModifier(int index, core::Modifier *modifier) {
init(modifier);
- beginInsertRows(QModelIndex(), _modifiers.count(), _modifiers.count());
+ beginInsertRows(QModelIndex(), index, index);
_modifiers.insert(index, modifier);
_modifierStates[modifier] = true;
endInsertRows();
// TODO : integrate into the undo framework!!!
emit modifiersChanged();
}
void ModifierModel::removeModifier(const QModelIndex &index)
{
if (!index.isValid())
return;
removeRows(index.row(), 1);
}
bool ModifierModel::modifierState(core::Modifier *modifier) const
{
if (_modifierStates.find(modifier) == _modifierStates.end())
return false;
else
return _modifierStates[modifier];
}
void ModifierModel::setModifierState(core::Modifier *modifier, bool state)
{
int modifierRow = _modifiers.indexOf(modifier);
if (modifierRow < 0)
return;
if (_modifierStates[modifier] != state)
{
_modifierStates[modifier] = state;
emit dataChanged(index(modifierRow, 0), index(modifierRow, columnNumber - 1));
emit modifiersChanged();
}
}
void ModifierModel::toggleModifierState(core::Modifier *modifier)
{
if (_modifierStates.find(modifier) == _modifierStates.end())
return;
setModifierState(modifier, !_modifierStates[modifier]);
}
void ModifierModel::setExclusiveModifier(core::Modifier *modifier)
{
if (_exclusiveModifier == modifier)
return;
_exclusiveModifier = modifier;
if (modifier)
_modifierStates[modifier] = true;
// Refresh all
emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
emit modifiersChanged();
}
/*QString ModifierModel::apply(const QString &str) const
{
if (_exclusiveModifier)
return _exclusiveModifier->apply(str);
QString filtered = str;
foreach (core::Filter *filter, _modifiers)
if (_modifierstates[filter])
filtered = filter->apply(filtered);
return filtered;
}*/
core::Modifier *ModifierModel::modifier(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
if (index.row() >= 0 && index.row() < rowCount())
return _modifiers[index.row()];
}
Qt::ItemFlags ModifierModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractListModel::flags(index);
if (index.isValid())
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
else
return Qt::ItemIsDropEnabled | flags;
}
void ModifierModel::toggleExclusiveState(core::Modifier *modifier)
{
if (_exclusiveModifier == modifier)
_exclusiveModifier = 0;
else
_exclusiveModifier = modifier;
if (_exclusiveModifier)
_modifierStates[_exclusiveModifier] = true;
// Refresh all
emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
emit modifiersChanged();
}
-bool ModifierModel::upModifier(const QModelIndex &modifierIndex)
-{
- if (!modifierIndex.row())
- return false;
-
- _modifiers.swap(modifierIndex.row(), modifierIndex.row() - 1);
- emit dataChanged(index(modifierIndex.row() - 1, 0),
- index(modifierIndex.row(), columnNumber - 1));
- emit modifiersChanged();
- return true;
-}
-
-bool ModifierModel::downModifier(const QModelIndex &modifierIndex)
-{
- if (modifierIndex.row() == rowCount() - 1)
- return false;
-
- _modifiers.swap(modifierIndex.row(), modifierIndex.row() + 1);
- emit dataChanged(index(modifierIndex.row(), 0),
- index(modifierIndex.row() + 1, columnNumber - 1));
- emit modifiersChanged();
- return true;
-}
-
Qt::DropActions ModifierModel::supportedDropActions() const {
return Qt::MoveAction;
}
bool ModifierModel::removeRows(int row, int count, const QModelIndex &parent) {
core::Modifier *modifierToRemove = modifier(index(row, 0));
if (!_disableUndo) {
RemoveModifierCommand *command = new RemoveModifierCommand(this, _manager, row, modifierToRemove->factory()->info().name(),
modifierToRemove->serializeProperties());
UndoManager::instance().push(command);
command->activate();
}
beginRemoveRows(QModelIndex(), row, row);
_modifiers.removeAt(_modifiers.indexOf(modifierToRemove));
_modifierStates.remove(modifierToRemove);
if (_exclusiveModifier == modifierToRemove)
_exclusiveModifier = 0;
delete modifierToRemove;
endRemoveRows();
emit modifiersChanged();
}
#define MIMETYPE QLatin1String("filter-rows")
QStringList ModifierModel::mimeTypes() const
{
QStringList types;
types << MIMETYPE;
return types;
}
QMimeData *ModifierModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *mimeData = new QMimeData;
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
stream << index.row();
}
}
mimeData->setData(MIMETYPE, encodedData);
return mimeData;
}
bool ModifierModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
if (action == Qt::IgnoreAction)
return false;
QByteArray inData = data->data(MIMETYPE);
QDataStream stream(inData);
- int r;
- stream >> r;
+ int sourceRow;
+ stream >> sourceRow;
- core::Modifier *modifier = _modifiers[r];
+ int destinationRow = rowCount();
if (row != -1) {
if (row >= rowCount()) {
- _modifiers.takeAt(r);
- _modifiers << modifier;
- _dropRow = rowCount() - 1;
+ destinationRow = rowCount();
} else {
- if (r < row)
+ if (sourceRow < row)
row--;
- _modifiers.move(r, row);
- _dropRow = row;
+ destinationRow = row;
}
} else if (parent.isValid()) {
- _modifiers.move(r, parent.row());
- _dropRow = parent.row();
+ destinationRow = parent.row();
} else if (!parent.isValid()) {
- _modifiers.takeAt(r);
- _modifiers << modifier;
- _dropRow = rowCount() - 1;
+ destinationRow = rowCount();
}
- emit modifiersChanged();
- emit dropDone();
+ moveModifier(sourceRow, destinationRow);
return false;
}
void ModifierModel::clear() {
_exclusiveModifier = 0;
qDeleteAll(_modifiers);
_modifiers.clear();
_modifierStates.clear();
reset();
emit modifiersChanged();
}
void ModifierModel::modifierChanged() {
if (_disableUndo)
return;
core::Modifier *modifier = static_cast<core::Modifier*>(sender());
// Undo managing => compute the diff
QMap<QString,QPair<QString,QVariant> > newProperties = modifier->serializeProperties();
QMap<QString,QPair<QString,QVariant> > &oldProperties = _changingModifierOldProperties;
QMap<QString,QPair<QString,QVariant> > undoProperties, redoProperties;
foreach (const QString &propName, newProperties.keys()) {
QPair<QString,QVariant> &newPair = newProperties[propName];
QPair<QString,QVariant> &oldPair = oldProperties[propName];
if (newPair != oldPair) {
undoProperties.insert(propName, oldPair);
redoProperties.insert(propName, newPair);
}
}
ModifyModifierCommand *command = new ModifyModifierCommand(this, _modifiers.indexOf(modifier), undoProperties, redoProperties);
UndoManager::instance().push(command);
command->activate();
}
void ModifierModel::modifierChanging() {
if (_disableUndo)
return;
core::Modifier *modifier = static_cast<core::Modifier*>(sender());
_changingModifierOldProperties = modifier->serializeProperties();
}
void ModifierModel::beginUndoAction() {
_disableUndo = true;
}
void ModifierModel::endUndoAction() {
_disableUndo = false;
}
+
+void ModifierModel::moveModifier(int sourceRow, int destinationRow) {
+ Q_ASSERT_X(sourceRow >= 0 && sourceRow < rowCount(), "ModifierModel::moveModifier()", qPrintable(QString("<sourceRow> is out of bound: %d!").arg(sourceRow)));
+
+ if (sourceRow == destinationRow) // Save destination => do nothing
+ return;
+
+ if (destinationRow >= rowCount() - 1 &&
+ sourceRow == rowCount() - 1) // Already at the list queue => do nothing
+ return;
+
+ beginRemoveRows(QModelIndex(), sourceRow, sourceRow);
+ core::Modifier *modifier = _modifiers.takeAt(sourceRow);
+ endRemoveRows();
+ beginInsertRows(QModelIndex(), destinationRow, destinationRow);
+ _modifiers.insert(destinationRow, modifier);
+ endInsertRows();
+
+ emit modifiersChanged();
+
+ if (!_disableUndo) {
+ MoveModifierCommand *command = new MoveModifierCommand(this, sourceRow, destinationRow);
+ UndoManager::instance().push(command);
+ command->activate();
+ }
+}
diff --git a/renamah/modifier_model.h b/renamah/modifier_model.h
index db37fcf..7492317 100644
--- a/renamah/modifier_model.h
+++ b/renamah/modifier_model.h
@@ -1,106 +1,97 @@
#ifndef MODIFIER_MODEL_H
#define MODIFIER_MODEL_H
#include <QAbstractListModel>
#include <QList>
#include <interfaces/filter.h>
#include "modifier_manager.h"
class ModifierModel : public QAbstractListModel
{
Q_OBJECT
public:
static const int colIndex = 3;
static const int colMode = 0;
static const int colCaption = 1;
static const int columnNumber = 2;
ModifierModel(ModifierManager *manager);
/** Returns a modifier in function of a model index */
core::Modifier *modifier(const QModelIndex &index) const;
/** Add a modifier to the model */
void addModifier(core::Modifier *modifier);
/** Insert a modifier into the model */
void insertModifier(int index, core::Modifier *modifier);
/*! Remove the modifier at <index> */
void removeModifier(const QModelIndex &index);
/*! Clear all modifiers */
virtual void clear();
/*! Returns the modifier state */
bool modifierState(core::Modifier *modifier) const;
/*! Activate or deactivate a modifier */
void setModifierState(core::Modifier *modifier, bool state);
/*! Toggle the state of the modifier */
void toggleModifierState(core::Modifier *modifier);
/*! Set a modifier as the uniq modifier, deactivate others */
void setExclusiveModifier(core::Modifier *modifier);
/*! If modifier was not exclusive => set it exclusive */
void toggleExclusiveState(core::Modifier *modifier);
- /*! Up the modifier which index is in parameter
- * \returns true if the operation has been succeed
+ /** Move a modifier from a place to another
+ * destination can be >= rowCount(), in this case, the modifier is moved at the list tail
*/
- bool upModifier(const QModelIndex &modifierIndex);
-
- /*! Down the modifier which index is in parameter
- * \returns true if the operation has been succeed
- */
- bool downModifier(const QModelIndex &modifierIndex);
+ void moveModifier(int source, int destination);
/*! Returns the exclusive modifier */
core::Modifier *exclusiveModifier() const { return _exclusiveModifier; }
void refreshLayout() { emit layoutChanged(); }
- int dropRow() const { return _dropRow; }
-
void beginUndoAction(); // Must be called just before the undo manager makes an undo or a redo action
void endUndoAction(); // Must be called just after the undo manager makes an undo or a redo action
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
Qt::DropActions supportedDropActions() const;
QStringList mimeTypes() const;
QMimeData *mimeData(const QModelIndexList &indexes) const;
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
signals:
void modifiersChanged();
- void dropDone();
protected:
ModifierManager *_manager;
QList<core::Modifier*> _modifiers;
QMap<core::Modifier*, bool> _modifierStates;
core::Modifier *_exclusiveModifier;
QMap<QString,QPair<QString,QVariant> > _changingModifierOldProperties;
private:
- int _dropRow;
bool _disableUndo;
void init(core::Modifier *modifier);
private slots:
void modifierChanging();
void modifierChanged();
};
#endif
diff --git a/renamah/undo_manager.cpp b/renamah/undo_manager.cpp
index 971db88..ef93400 100644
--- a/renamah/undo_manager.cpp
+++ b/renamah/undo_manager.cpp
@@ -1,114 +1,135 @@
#include "undo_manager.h"
UndoManager *UndoManager::_instance = 0;
UndoManager &UndoManager::instance() {
if (!_instance)
_instance = new UndoManager;
return *_instance;
}
/////////////////////////////////
/// ModifierCommand /////////////
/////////////////////////////////
ModifierCommand::ModifierCommand(ModifierModel *model)
: _model(model),
_activated(false) {
}
void ModifierCommand::undo() {
if (!_activated)
return;
_model->beginUndoAction();
makeUndo();
_model->endUndoAction();
}
void ModifierCommand::redo() {
if (!_activated)
return;
_model->beginUndoAction();
makeRedo();
_model->endUndoAction();
}
/////////////////////////////////
/// ModifyModifierCommand ///////
/////////////////////////////////
ModifyModifierCommand::ModifyModifierCommand(ModifierModel *model,
int modifierIndex,
const QMap<QString,QPair<QString,QVariant> > &undoProperties,
const QMap<QString,QPair<QString,QVariant> > &redoProperties)
: ModifierCommand(model),
_modifierIndex(modifierIndex),
_undoProperties(undoProperties),
_redoProperties(redoProperties) {
setText("Modifier modification");
}
void ModifyModifierCommand::makeUndo() {
core::Modifier *modifier = _model->modifier(_model->index(_modifierIndex, 0));
modifier->deserializeProperties(_undoProperties);
}
void ModifyModifierCommand::makeRedo() {
core::Modifier *modifier = _model->modifier(_model->index(_modifierIndex, 0));
modifier->deserializeProperties(_redoProperties);
}
/////////////////////////////////
/// CreateModifierCommand ///////
/////////////////////////////////
CreateModifierCommand::CreateModifierCommand(ModifierModel *model,
ModifierManager *manager,
const QString &factoryName)
: ModifierCommand(model),
_manager(manager),
_factoryName(factoryName) {
setText("Modifier creation");
}
void CreateModifierCommand::makeUndo() {
_model->removeModifier(_model->index(_model->rowCount() - 1, 0));
}
void CreateModifierCommand::makeRedo() {
core::ModifierFactory *factory = _manager->factoryByName(_factoryName);
core::Modifier *modifier = factory->makeModifier();
_model->addModifier(modifier);
}
/////////////////////////////////
/// RemoveModifierCommand ///////
/////////////////////////////////
RemoveModifierCommand::RemoveModifierCommand(ModifierModel *model,
ModifierManager *manager,
int modifierIndex,
const QString &factoryName,
const QMap<QString,QPair<QString,QVariant> > &properties)
: ModifierCommand(model),
_manager(manager),
_modifierIndex(modifierIndex),
_factoryName(factoryName),
_properties(properties) {
setText("Modifier removing");
}
void RemoveModifierCommand::makeUndo() {
core::ModifierFactory *factory = _manager->factoryByName(_factoryName);
core::Modifier *modifier = factory->makeModifier();
modifier->deserializeProperties(_properties);
_model->insertModifier(_modifierIndex, modifier);
}
void RemoveModifierCommand::makeRedo() {
_model->removeModifier(_model->index(_modifierIndex, 0));
}
+/////////////////////////////////
+/// MoveModifierCommand /////////
+/////////////////////////////////
+
+MoveModifierCommand::MoveModifierCommand(ModifierModel *model, int sourceRow, int destinationRow)
+ : ModifierCommand(model),
+ _sourceRow(sourceRow),
+ _destinationRow(destinationRow) {
+ setText("Modifier move");
+}
+
+void MoveModifierCommand::makeUndo() {
+ if (_destinationRow >= _model->rowCount())
+ _model->moveModifier(_model->rowCount() - 1, _sourceRow);
+ else
+ _model->moveModifier(_destinationRow, _sourceRow);
+}
+
+void MoveModifierCommand::makeRedo() {
+ _model->moveModifier(_sourceRow, _destinationRow);
+}
diff --git a/renamah/undo_manager.h b/renamah/undo_manager.h
index 63f7643..8b250b0 100644
--- a/renamah/undo_manager.h
+++ b/renamah/undo_manager.h
@@ -1,98 +1,111 @@
#ifndef UNDO_MANAGER_H
#define UNDO_MANAGER_H
#include <QUndoStack>
#include <QUndoCommand>
#include <QMap>
#include <QPair>
#include <QVariant>
#include "modifier_model.h"
#include "modifier_manager.h"
class ModifierCommand : public QUndoCommand
{
public:
ModifierCommand(ModifierModel *model);
/// undo/redo won't work until this command is activated
void activate() { _activated = true; }
void undo();
void redo();
protected:
ModifierModel *_model;
virtual void makeUndo() = 0;
virtual void makeRedo() = 0;
private:
bool _activated;
};
class ModifyModifierCommand : public ModifierCommand
{
public:
ModifyModifierCommand(ModifierModel *model,
int modifierIndex,
const QMap<QString,QPair<QString,QVariant> > &undoProperties,
const QMap<QString,QPair<QString,QVariant> > &redoProperties);
void makeUndo();
void makeRedo();
private:
int _modifierIndex;
QMap<QString,QPair<QString,QVariant> > _undoProperties;
QMap<QString,QPair<QString,QVariant> > _redoProperties;
};
class CreateModifierCommand : public ModifierCommand
{
public:
CreateModifierCommand(ModifierModel *model,
ModifierManager *manager,
const QString &factoryName);
void makeUndo();
void makeRedo();
private:
ModifierManager *_manager;
QString _factoryName;
};
class RemoveModifierCommand : public ModifierCommand
{
public:
RemoveModifierCommand(ModifierModel *model,
ModifierManager *manager,
int modifierIndex,
const QString &factoryName,
const QMap<QString,QPair<QString,QVariant> > &properties);
void makeUndo();
void makeRedo();
private:
ModifierManager *_manager;
int _modifierIndex;
QString _factoryName;
QMap<QString,QPair<QString,QVariant> > _properties;
};
+class MoveModifierCommand : public ModifierCommand
+{
+public:
+ MoveModifierCommand(ModifierModel *model, int sourceRow, int destinationRow);
+
+ void makeUndo();
+ void makeRedo();
+
+private:
+ int _sourceRow;
+ int _destinationRow;
+};
+
class UndoManager : public QUndoStack
{
Q_OBJECT
public:
static UndoManager &instance();
private:
UndoManager(QObject *parent = 0) : QUndoStack(parent) {}
static UndoManager *_instance;
};
#endif
diff --git a/renamah/widget_modifiers.cpp b/renamah/widget_modifiers.cpp
index 7f3fc4c..11df5a2 100644
--- a/renamah/widget_modifiers.cpp
+++ b/renamah/widget_modifiers.cpp
@@ -1,242 +1,234 @@
#include <QMessageBox>
#include <QMouseEvent>
#include <QHeaderView>
#include <QMetaProperty>
#include "modifier_delegate.h"
#include "widget_modifiers.h"
WidgetModifiers::WidgetModifiers(QWidget *parent)
: QWidget(parent),
_modifierManager(0),
_modifierModel(0) {
setupUi(this);
connect(&signalMapperAddModifier, SIGNAL(mapped(const QString &)),
this, SLOT(addModifier(const QString &)));
pushButtonAdd->setMenu(&menuAddModifier);
connect(&menuAddModifier, SIGNAL(aboutToShow()), this, SLOT(aboutToShowAddModifierMenu()));
treeView->setItemDelegate(new ModifierDelegate);
labelAddModifier->installEventFilter(this);
treeView->viewport()->installEventFilter(this);
treeView->installEventFilter(this);
}
void WidgetModifiers::init(ModifierManager *modifierManager, ModifierModel &modifierModel) {
_modifierManager = modifierManager;
_modifierModel = &modifierModel;
retranslate();
treeView->setModel(_modifierModel);
- connect(_modifierModel, SIGNAL(dropDone()),
- this, SLOT(filterDropDone()));
connect(_modifierModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
this, SLOT(modifiersInserted(const QModelIndex &, int, int)));
treeView->header()->setResizeMode(0, QHeaderView::ResizeToContents);
treeView->header()->setResizeMode(1, QHeaderView::ResizeToContents);
connect(treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(currentModifierChanged(const QModelIndex &, const QModelIndex &)));
currentModifierChanged(QModelIndex(), QModelIndex());
}
void WidgetModifiers::retranslate() {
labelAddModifier->setText(tr("Add a new %1").arg(_modifierManager->modifierTypeName()));
core::Modifier *modifier = currentModifier();
if (!modifier)
return;
core::ModifierFactory *factory = modifier->factory();
labelModifierCaption->setText(factory->info().caption());
labelModifierDescription->setText(factory->info().description());
}
void WidgetModifiers::on_pushButtonRemove_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
- if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this filter?"),
- QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
- return;
-
_modifierModel->removeModifier(index);
}
void WidgetModifiers::on_pushButtonUp_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
- int row = index.row();
- if (_modifierModel->upModifier(index))
- treeView->setCurrentIndex(_modifierModel->index(row - 1, 0));
+ if (!index.row())
+ return;
+
+ _modifierModel->moveModifier(index.row(), index.row() - 1);
}
void WidgetModifiers::on_pushButtonDown_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
- int row = index.row();
- if (_modifierModel->downModifier(index))
- treeView->setCurrentIndex(_modifierModel->index(row + 1, 0));
+ if (index.row() == _modifierModel->rowCount() - 1)
+ return;
+
+ _modifierModel->moveModifier(index.row(), index.row() + 1);
}
void WidgetModifiers::aboutToShowAddModifierMenu() {
menuAddModifier.clear();
foreach (core::ModifierFactory *factory, _modifierManager->factories())
{
QAction *action = menuAddModifier.addAction(factory->info().caption() + " (" + factory->info().description() + ")");
connect(action, SIGNAL(triggered()), &signalMapperAddModifier, SLOT(map()));
signalMapperAddModifier.setMapping(action, factory->info().name());
}
}
void WidgetModifiers::addModifier(const QString &factoryName) {
core::ModifierFactory *factory = _modifierManager->factoryByName(factoryName);
Q_ASSERT_X(factory, "WidgetModifiers::addModifierClicked()", "<factoryName> seems to have no factory correspondant");
_modifierModel->addModifier(factory->makeModifier());
stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
}
void WidgetModifiers::currentModifierChanged(const QModelIndex ¤t, const QModelIndex &previous) {
if (previous.isValid())
{
core::Modifier *previousModifier = _modifierModel->modifier(previous);
core::ModifierFactory *previousFactory = previousModifier->factory();
if (_configWidget)
{
previousFactory->deleteConfigurationWidget(_configWidget);
_configWidget = 0;
}
}
if (!current.isValid())
{
stackedWidgetConfiguration->setCurrentWidget(pageNoModifiers);
currentModifierChanged(0);
return;
}
stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
core::Modifier *modifier = _modifierModel->modifier(current);
core::ModifierFactory *factory = modifier->factory();
_configWidget = modifier->factory()->makeConfigurationWidget(modifier);
if (_configWidget)
{
setConfigWidget(_configWidget);
frameConfiguration->setVisible(true);
labelModifierCaption->setText(factory->info().caption());
labelModifierDescription->setText(factory->info().description());
connect(modifier, SIGNAL(settingsChanged()), this, SLOT(widgetModifierChanged()));
}
currentModifierChanged(modifier);
}
bool WidgetModifiers::eventFilter(QObject *obj, QEvent *ev) {
if (obj == labelAddModifier && ev->type() == QEvent::MouseButtonPress)
{
QMouseEvent *event = static_cast<QMouseEvent*>(ev);
menuAddModifier.popup(event->globalPos());
} else if (obj == treeView->viewport() && ev->type() == QEvent::MouseButtonPress)
{
QMouseEvent *event = static_cast<QMouseEvent*>(ev);
QPoint p = event->pos();
QModelIndex index = treeView->indexAt(p);
if (index.column() == ModifierModel::colMode)
{
if (modifierStateRect(index).contains(p))
_modifierModel->toggleModifierState(_modifierModel->modifier(index));
else
{
if (modifierOnlyRect(index).contains(p))
_modifierModel->toggleExclusiveState(_modifierModel->modifier(index));
}
}
} else if (obj == treeView && ev->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(ev);
if (keyEvent->key() == Qt::Key_Delete)
{
on_pushButtonRemove_clicked();
}
}
return QWidget::eventFilter(obj, ev);
}
QRect WidgetModifiers::modifierStateRect(const QModelIndex &index) const {
QRect indexRect = treeView->visualRect(index);
QRect res(indexRect.left(), indexRect.top(), 16, 16);
if (indexRect.width() > 32)
res.translate((indexRect.width() - 32) / 2, 0);
if (indexRect.height() > 16)
res.translate(0, (indexRect.height() - 16) / 2);
return res;
}
QRect WidgetModifiers::modifierOnlyRect(const QModelIndex &index) const {
QRect indexRect = treeView->visualRect(index);
QRect res(indexRect.left() + 16, indexRect.top(), 16, 16);
if (indexRect.width() > 32)
res.translate((indexRect.width() - 32) / 2, 0);
if (indexRect.height() > 16)
res.translate(0, (indexRect.height() - 16) / 2);
return res;
}
void WidgetModifiers::widgetModifierChanged() {
if (treeView->currentIndex().isValid())
{
_modifierModel->refreshLayout();
treeView->update(treeView->currentIndex());
}
}
core::Modifier *WidgetModifiers::currentModifier() const {
return _modifierModel->modifier(treeView->currentIndex());
}
void WidgetModifiers::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi(this);
retranslate();
} else
QWidget::changeEvent(event);
}
-void WidgetModifiers::filterDropDone() {
- treeView->setCurrentIndex(_modifierModel->index(_modifierModel->dropRow(), 0));
-}
-
void WidgetModifiers::newProfile() {
if (_modifierModel->rowCount())
treeView->setCurrentIndex(_modifierModel->index(0, 0));
}
void WidgetModifiers::modifiersInserted(const QModelIndex &parent, int start, int end) {
treeView->setCurrentIndex(_modifierModel->index(start));
}
diff --git a/renamah/widget_modifiers.h b/renamah/widget_modifiers.h
index cb25651..c4cbf25 100644
--- a/renamah/widget_modifiers.h
+++ b/renamah/widget_modifiers.h
@@ -1,57 +1,56 @@
#ifndef WIDGET_MODIFIERS_H
#define WIDGET_MODIFIERS_H
#include <QMenu>
#include <QSignalMapper>
#include "modifier_manager.h"
#include "modifier_model.h"
#include "ui_widget_modifiers.h"
class WidgetModifiers : public QWidget, protected Ui::WidgetModifiers
{
Q_OBJECT
public:
WidgetModifiers(QWidget *parent = 0);
virtual void init(ModifierManager *modifierManager, ModifierModel &modifierModel);
/*! Called after each profile loaded */
virtual void newProfile();
public slots:
void addModifier(const QString &factoryName);
protected:
bool eventFilter(QObject *obj, QEvent *ev);
void changeEvent(QEvent *event);
core::Modifier *currentModifier() const;
virtual void setConfigWidget(QWidget *widget) = 0;
virtual void currentModifierChanged(core::Modifier *modifier) {};
private:
core::ModifierConfigWidget *_configWidget;
QMenu menuAddModifier;
QSignalMapper signalMapperAddModifier;
ModifierManager *_modifierManager;
ModifierModel *_modifierModel;
QRect modifierStateRect(const QModelIndex &index) const;
QRect modifierOnlyRect(const QModelIndex &index) const;
void retranslate();
private slots:
void on_pushButtonRemove_clicked();
void on_pushButtonUp_clicked();
void on_pushButtonDown_clicked();
void aboutToShowAddModifierMenu();
void currentModifierChanged(const QModelIndex ¤t, const QModelIndex &previous);
void widgetModifierChanged();
- void filterDropDone();
void modifiersInserted(const QModelIndex &parent, int start, int end);
};
#endif
|
Guid75/renamah
|
8cac66955597ed200bf70ea1d214fb2de12bccfa
|
undo framework integrated
|
diff --git a/libcore/interfaces/modifier.h b/libcore/interfaces/modifier.h
index d88506e..7eb8424 100644
--- a/libcore/interfaces/modifier.h
+++ b/libcore/interfaces/modifier.h
@@ -1,45 +1,47 @@
#ifndef MODIFIER_H
#define MODIFIER_H
#include <QObject>
#include <QMap>
#include <QPair>
#include <QVariant>
#include "plugin.h"
namespace core
{
class ModifierFactory;
class Modifier : public QObject
{
Q_OBJECT
public:
Modifier(QObject *parent = 0) : QObject(parent) {}
friend class ModifierFactory;
/*! \return a resume string of the modifier action */
virtual QString resume() const = 0;
/*! \return the factory which generates the modifier */
ModifierFactory *factory() const { return _factory; }
/*! \return a map which contains all serializable properties of the modifier */
QMap<QString,QPair<QString,QVariant> > serializeProperties();
/*! Fill the object properties */
void deserializeProperties(const QMap<QString,QPair<QString,QVariant> > &properties);
signals:
- /*! Emitted when modifier settings changed */
+ /** Emitted when modifier settings changing, before new value is affected. */
+ void settingsChanging();
+ /** Emitted when modifier settings changed */
void settingsChanged();
private:
ModifierFactory *_factory;
};
};
#endif
diff --git a/plugins/casefilter/case_filter.cpp b/plugins/casefilter/case_filter.cpp
index 748717f..c8e4ae8 100644
--- a/plugins/casefilter/case_filter.cpp
+++ b/plugins/casefilter/case_filter.cpp
@@ -1,88 +1,90 @@
#include <QFileInfo>
#include <QDir>
#include <QTextBoundaryFinder>
#include "case_filter.h"
QString CaseFilter::apply(const core::FilterFileInfo &fileInfo) const {
QString result = fileInfo.partToFilter;
switch (_operation)
{
case LowerCase:
result = result.toLower();
break;
case UpperCase:
result = result.toUpper();
break;
case UpFirstLetter:
if (result.length()) {
if (_lowerOtherChars)
result = result[0].toUpper() +
result.mid(1, result.length() - 1).toLower();
else
result[0] = result[0].toUpper();
}
break;
case UpWordsFirstLetter:
{
QTextBoundaryFinder finder(QTextBoundaryFinder::Word, result);
int p;
int start = 1;
if (finder.isAtBoundary())
result[0] = result[0].toUpper();
while ((p = finder.toNextBoundary()) >= 0)
{
if (finder.boundaryReasons() & QTextBoundaryFinder::StartWord)
{
start = p + 1;
result[p] = result[p].toUpper();
} else if (finder.boundaryReasons() & QTextBoundaryFinder::EndWord &&
p >= start &&
_lowerOtherChars)
{
result.replace(start, p - start, result.mid(start, p - start).toLower());
}
}
break;
}
default:;
}
return result;
}
QString CaseFilter::operationCaption(Operation operation)
{
switch (operation)
{
case LowerCase: return tr("lower case", "case counts!");
case UpperCase: return tr("UPPER CASE", "case counts!");
case UpFirstLetter: return tr("First letter in upcase", "case counts!");
case UpWordsFirstLetter: return tr("Words First Letter In Upcase", "case counts!");
default: return "";
}
}
QString CaseFilter::resume() const
{
return operationCaption(_operation);
}
void CaseFilter::setOperation(Operation value) {
if (_operation == value)
return;
+ emit settingsChanging();
_operation = value;
emit settingsChanged();
}
void CaseFilter::setLowerOtherChars(bool value) {
if (_lowerOtherChars == value)
return;
+ emit settingsChanging();
_lowerOtherChars = value;
emit settingsChanged();
}
diff --git a/plugins/commandaction/command_action.cpp b/plugins/commandaction/command_action.cpp
index b840ac6..adbef55 100644
--- a/plugins/commandaction/command_action.cpp
+++ b/plugins/commandaction/command_action.cpp
@@ -1,40 +1,42 @@
#include "process_handler.h"
#include "command_action.h"
void CommandAction::apply(const QString &fileName) const
{
if (_command == "")
return;
QProcess *process = ProcessHandler::instance().createProcess();
QString program = "/bin/sh";
QStringList arguments;
arguments << "-c";
arguments << QString("%1").arg(_command.arg(fileName));
process->start(program, arguments);
process->waitForFinished();
}
QString CommandAction::resume() const
{
return "$ " + _command;
}
void CommandAction::setCommand(const QString &value)
{
if (_command == value)
return;
+ emit settingsChanging();
_command = value;
emit settingsChanged();
}
void CommandAction::setDontWaitForEnd(bool value)
{
if (_dontWaitForEnd == value)
return;
+ emit settingsChanging();
_dontWaitForEnd = value;
emit settingsChanged();
}
diff --git a/plugins/cutterfilter/cutter_filter.cpp b/plugins/cutterfilter/cutter_filter.cpp
index 08b629b..5137f3f 100644
--- a/plugins/cutterfilter/cutter_filter.cpp
+++ b/plugins/cutterfilter/cutter_filter.cpp
@@ -1,122 +1,127 @@
#include "cutter_filter.h"
CutterFilter::CutterFilter(QObject *parent)
: core::Filter(parent),
_startMarkerPosition(FromLeft),
_startMarkerIndex(1),
_endMarkerPosition(FromRight),
_endMarkerIndex(1),
_operation(Keep)
{
}
QString CutterFilter::apply(const core::FilterFileInfo &fileInfo) const {
QString result = fileInfo.partToFilter;
int trueStartIndex = _startMarkerPosition == FromRight ?
result.length() - _startMarkerIndex + 1 : _startMarkerIndex;
int trueEndIndex = _endMarkerPosition == FromRight ?
result.length() - _endMarkerIndex + 1 : _endMarkerIndex;
if (trueEndIndex < trueStartIndex) // Impossible case
return result;
switch (_operation) {
case Keep:
result = result.mid(trueStartIndex - 1, trueEndIndex - trueStartIndex + 1);
break;
case Remove:
result = result.remove(trueStartIndex - 1, trueEndIndex - trueStartIndex + 1);
break;
default:;
}
return result;
}
QString CutterFilter::resume() const {
// "Keep from 1 (from left) to 7 (from right)
return "TODO";
}
void CutterFilter::setStartMarkerPosition(Position value, bool correct) {
if (_startMarkerPosition == value)
return;
+ emit settingsChanging();
_startMarkerPosition = value;
if (correct)
correctEndMarker();
emit settingsChanged();
}
void CutterFilter::setStartMarkerIndex(int value, bool correct) {
if (_startMarkerIndex == value)
return;
+ emit settingsChanging();
_startMarkerIndex = value;
if (correct)
correctEndMarker();
emit settingsChanged();
}
void CutterFilter::setEndMarkerPosition(Position value, bool correct) {
if (_endMarkerPosition == value)
return;
+ emit settingsChanging();
_endMarkerPosition = value;
if (correct)
correctStartMarker();
emit settingsChanged();
}
void CutterFilter::setEndMarkerIndex(int value, bool correct) {
if (_endMarkerIndex == value)
return;
+ emit settingsChanging();
_endMarkerIndex = value;
if (correct)
correctStartMarker();
emit settingsChanged();
}
void CutterFilter::setOperation(Operation value) {
if (_operation == value)
return;
+ emit settingsChanging();
_operation = value;
emit settingsChanged();
}
void CutterFilter::correctStartMarker() {
switch (_endMarkerPosition) {
case FromLeft:
if (_startMarkerPosition == FromRight)
_startMarkerPosition = FromLeft;
if (_startMarkerPosition == FromLeft && _startMarkerIndex > _endMarkerIndex)
_startMarkerIndex = _endMarkerIndex;
break;
case FromRight:
if (_startMarkerPosition == FromRight && _startMarkerIndex < _endMarkerIndex)
_startMarkerIndex = _endMarkerIndex;
break;
default:;
}
}
void CutterFilter::correctEndMarker() {
switch (_startMarkerPosition) {
case FromLeft:
if (_endMarkerPosition == FromLeft && _endMarkerIndex < _startMarkerIndex)
_endMarkerIndex = _startMarkerIndex;
break;
case FromRight:
if (_endMarkerPosition == FromLeft)
_endMarkerPosition = FromRight;
if (_endMarkerPosition == FromRight && _endMarkerIndex > _startMarkerIndex)
_endMarkerIndex = _startMarkerIndex;
break;
}
}
diff --git a/plugins/datefilter/date_filter.cpp b/plugins/datefilter/date_filter.cpp
index 6bb7db9..5d31024 100644
--- a/plugins/datefilter/date_filter.cpp
+++ b/plugins/datefilter/date_filter.cpp
@@ -1,149 +1,156 @@
#include <QFileInfo>
#include "date_filter.h"
DateFilter::DateFilter(QObject *parent)
: core::Filter(parent),
_type(LastModificationDate),
_format(DefaultFormat),
_separator("_"),
_insertionMode(Suffix),
_customInsertionIndex(0) {
}
QString DateFilter::apply(const core::FilterFileInfo &fileInfo) const {
QString result = fileInfo.partToFilter;
QFileInfo info(fileInfo.originalFilePath);
QDateTime dateTime;
// Get the date time according to the type
switch (_type) {
case LastModificationDate:
dateTime = info.lastModified();
break;
case LastAccessDate:
dateTime = info.lastRead();
break;
case CreationDate:
dateTime = info.created();
break;
case CurrentDate:
dateTime = QDateTime::currentDateTime();
break;
case CustomDate:
dateTime = _customDateTime;
break;
default:
return result;
}
QString text;
if (_format == CustomFormat)
text = dateTime.toString(_customFormat);
else
text = dateTime.toString(formatToQtDateFormat(_format));
switch (_insertionMode) {
case Prefix:
return QString("%1%2%3").arg(text).arg(_separator).arg(fileInfo.partToFilter);
case Suffix:
return QString("%1%2%3").arg(fileInfo.partToFilter).arg(_separator).arg(text);
case CustomPosition:
{
QString result = fileInfo.partToFilter;
QString insertionText = text;
if (_customInsertionIndex > 0)
insertionText = _separator + insertionText;
if (_customInsertionIndex <= result.length() - 1)
insertionText += _separator;
return result.insert(_customInsertionIndex, insertionText);
}
default:;
}
return fileInfo.partToFilter;
}
QString DateFilter::resume() const {
// "Keep from 1 (from left) to 7 (from right)
return typeToString(_type);
}
void DateFilter::setType(Type value) {
if (_type == value)
return;
+ emit settingsChanging();
_type = value;
emit settingsChanged();
}
void DateFilter::setCustomDateTime(const QDateTime &value) {
if (_customDateTime == value)
return;
+ emit settingsChanging();
_customDateTime = value;
emit settingsChanged();
}
void DateFilter::setFormat(Format value) {
if (_format == value)
return;
+ emit settingsChanging();
_format = value;
emit settingsChanged();
}
void DateFilter::setCustomFormat(const QString &value) {
if (_customFormat == value)
return;
+ emit settingsChanging();
_customFormat = value;
emit settingsChanged();
}
void DateFilter::setSeparator(const QString &value) {
if (_separator == value)
return;
+ emit settingsChanging();
_separator = value;
emit settingsChanged();
}
void DateFilter::setInsertionMode(InsertionMode value) {
if (_insertionMode == value)
return;
+ emit settingsChanging();
_insertionMode = value;
emit settingsChanged();
}
void DateFilter::setCustomInsertionIndex(int value) {
if (_customInsertionIndex == value)
return;
+ emit settingsChanging();
_customInsertionIndex = value;
emit settingsChanged();
}
Qt::DateFormat DateFilter::formatToQtDateFormat(Format format) {
switch (format) {
case DefaultFormat: return Qt::TextDate;
case ISOFormat: return Qt::ISODate;
default:;
}
return Qt::TextDate;
}
QString DateFilter::typeToString(Type type) {
switch (type) {
case LastModificationDate: return tr("Last modification");
case LastAccessDate: return tr("Last access");
case CreationDate: return tr("Creation");
case CurrentDate: return tr("Current");
case CustomDate: return tr("Custom");
default:;
}
return "";
}
diff --git a/plugins/numberingfilter/numbering_filter.cpp b/plugins/numberingfilter/numbering_filter.cpp
index dd8c70b..db16bc2 100644
--- a/plugins/numberingfilter/numbering_filter.cpp
+++ b/plugins/numberingfilter/numbering_filter.cpp
@@ -1,146 +1,154 @@
#include "numbering_filter.h"
NumberingFilter::NumberingFilter(QObject *parent)
: core::Filter(parent),
_start(1), _step(1), _separator("_"), _displayType(Numeric), _base(10), _padding(0),
_insertionMode(Prefix), _customInsertionIndex(0) {
}
QString NumberingFilter::apply(const core::FilterFileInfo &fileInfo) const {
QString trueIndex;
switch (_displayType) {
case Numeric:
trueIndex = QString("%1").arg(_start + _step * fileInfo.fileIndex, _padding,
_base, QChar('0')).toUpper();
break;
case UpperRoman:
trueIndex = toRoman(_start + _step * fileInfo.fileIndex);
break;
case LowerRoman:
trueIndex = toRoman(_start + _step * fileInfo.fileIndex).toLower();
break;
case UpperAlpha:
trueIndex = toAlphabetic(_start + _step * fileInfo.fileIndex, _padding);
break;
case LowerAlpha:
trueIndex = toAlphabetic(_start + _step * fileInfo.fileIndex, _padding).toLower();
break;
default:;
}
switch (_insertionMode) {
case Prefix:
return QString("%1%2%3").arg(trueIndex).arg(_separator).arg(fileInfo.partToFilter);
case Suffix:
return QString("%1%2%3").arg(fileInfo.partToFilter).arg(_separator).arg(trueIndex);
case CustomPosition:
{
QString result = fileInfo.partToFilter;
QString insertionText = trueIndex;
if (_customInsertionIndex > 0)
insertionText = _separator + insertionText;
if (_customInsertionIndex <= result.length() - 1)
insertionText += _separator;
return result.insert(_customInsertionIndex, insertionText);
}
default:;
}
return fileInfo.partToFilter;
}
QString NumberingFilter::resume() const {
return tr("Start: %1, Step: %2").arg(_start).arg(_step);
}
QString NumberingFilter::toRoman(int n) {
QString result;
static int values[] = { 1000, 900, 500, 400, 100,90, 50, 40, 10, 9, 5, 4, 1 };
static QString numerals[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
for (int i = 0; i < 13; i++) {
while (n >= values[i]) {
n -= values[i];
result += numerals[i];
}
}
return result;
}
QString NumberingFilter::toAlphabetic(int n, int padding)
{
QString result;
do {
int q = n / 26;
int r = n - (q * 26);
result = QChar('A' + r) + result;
n = q;
} while (n);
if (result.length() < padding)
result = QString(padding - result.length(), 'A') + result;
return result;
}
void NumberingFilter::setStart(int value) {
if (_start == value)
return;
+ emit settingsChanging();
_start = value;
emit settingsChanged();
}
void NumberingFilter::setStep(int value) {
if (_step == value)
return;
+ emit settingsChanging();
_step = value;
emit settingsChanged();
}
void NumberingFilter::setSeparator(const QString &value) {
if (_separator == value)
return;
+ emit settingsChanging();
_separator = value;
emit settingsChanged();
}
void NumberingFilter::setDisplayType(DisplayType value) {
if (_displayType == value)
return;
+ emit settingsChanging();
_displayType = value;
emit settingsChanged();
}
void NumberingFilter::setBase(int value) {
if (_base == value)
return;
+ emit settingsChanging();
_base = value;
emit settingsChanged();
}
void NumberingFilter::setPadding(int value) {
if (_padding == value)
return;
+ emit settingsChanging();
_padding = value;
emit settingsChanged();
}
void NumberingFilter::setInsertionMode(InsertionMode value) {
if (_insertionMode == value)
return;
+ emit settingsChanging();
_insertionMode = value;
emit settingsChanged();
}
void NumberingFilter::setCustomInsertionIndex(int value) {
if (_customInsertionIndex == value)
return;
+ emit settingsChanging();
_customInsertionIndex = value;
emit settingsChanged();
}
diff --git a/plugins/replacefilter/replace_filter.cpp b/plugins/replacefilter/replace_filter.cpp
index 3784ad4..8d8d10a 100644
--- a/plugins/replacefilter/replace_filter.cpp
+++ b/plugins/replacefilter/replace_filter.cpp
@@ -1,72 +1,76 @@
#include <QFileInfo>
#include <QDir>
#include "replace_filter.h"
ReplaceFilter::ReplaceFilter(QObject *parent)
: core::Filter(parent),
_target(QRegExp("", Qt::CaseInsensitive, QRegExp::FixedString)) {
}
QString ReplaceFilter::apply(const core::FilterFileInfo &fileInfo) const {
if (_target.pattern().isEmpty())
return fileInfo.partToFilter;
QString result = fileInfo.partToFilter;
return result.replace(_target, _replacement);
}
QString ReplaceFilter::resume() const {
return _target.pattern() + " -> " + _replacement;
}
void ReplaceFilter::setTargetPattern(const QString &value) {
if (_target.pattern() == value)
return;
+ emit settingsChanging();
_target.setPattern(value);
emit settingsChanged();
}
void ReplaceFilter::setTargetPatternSyntax(PatternSyntax value) {
if (_target.patternSyntax() == toQRegExpPatternSyntax(value))
return;
+ emit settingsChanging();
_target.setPatternSyntax(toQRegExpPatternSyntax(value));
emit settingsChanged();
}
void ReplaceFilter::setReplacement(const QString &value) {
if (_replacement == value)
return;
+ emit settingsChanging();
_replacement = value;
emit settingsChanged();
}
void ReplaceFilter::setCaseSensitive(bool value) {
if (value && _target.caseSensitivity() == Qt::CaseSensitive)
return;
else if (!value && _target.caseSensitivity() == Qt::CaseInsensitive)
return;
+ emit settingsChanging();
_target.setCaseSensitivity(value ? Qt::CaseSensitive : Qt::CaseInsensitive);
emit settingsChanged();
}
QRegExp::PatternSyntax ReplaceFilter::toQRegExpPatternSyntax(PatternSyntax patternSyntax) {
switch (patternSyntax) {
case RegExp: return QRegExp::RegExp2;
case Wildcard: return QRegExp::Wildcard;
case FixedString: return QRegExp::FixedString;
default: return QRegExp::RegExp2;
}
}
ReplaceFilter::PatternSyntax ReplaceFilter::toPatternSyntax(QRegExp::PatternSyntax patternSyntax) {
switch (patternSyntax) {
case QRegExp::Wildcard: return Wildcard;
case QRegExp::FixedString: return FixedString;
default: return RegExp;
}
}
diff --git a/renamah/CMakeLists.txt b/renamah/CMakeLists.txt
index f4d0f77..f9e44f2 100644
--- a/renamah/CMakeLists.txt
+++ b/renamah/CMakeLists.txt
@@ -1,92 +1,94 @@
SET(QT_USE_QTXML TRUE)
# SET(QT_USE_QTNETWORK TRUE)
INCLUDE(${QT_USE_FILE})
SET(RENAMAH_SOURCES
main.cpp
main_window.cpp
form_twinning.cpp
simple_dir_model.cpp
twinning_widget.cpp
widget_simple.cpp
file_model.cpp
filter_model.cpp
filter_manager.cpp
plugin_manager.cpp
form_last_operations.cpp
task_manager.cpp
modifier_delegate.cpp
led_widget.cpp
processor.cpp
widget_modifiers.cpp
modifier_manager.cpp
modifier_model.cpp
finalizer_model.cpp
action_manager.cpp
widget_extension_policy.cpp
extension_policy.cpp
widget_filters.cpp
widget_actions.cpp
dialog_manual_rename.cpp
profile.cpp
+ undo_manager.cpp
)
SET(RENAMAH_FORMS
main_window.ui
form_twinning.ui
widget_simple.ui
form_last_operations.ui
widget_modifiers.ui
widget_extension_policy.ui
dialog_manual_rename.ui
)
QT4_WRAP_UI(RENAMAH_FORMS_H ${RENAMAH_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/staticlibs)
SET(RENAMAH_MOCH
main_window.h
form_twinning.h
simple_dir_model.h
twinning_widget.h
widget_simple.h
file_model.h
filter_model.h
form_last_operations.h
modifier_delegate.h
led_widget.h
processor.h
widget_modifiers.h
modifier_model.h
finalizer_model.h
widget_extension_policy.h
widget_filters.h
widget_actions.h
dialog_manual_rename.h
+ undo_manager.h
)
# Translations stuff
COMPUTE_QM_FILES(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH})
ADD_CUSTOM_TARGET(translations_renamah DEPENDS ${QM_FILES})
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(RENAMAH_MOC ${RENAMAH_MOCH})
QT4_ADD_RESOURCES(RENAMAH_RES renamah.qrc)
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
ADD_EXECUTABLE(renamah ${RENAMAH_SOURCES} ${RENAMAH_FORMS_H} ${RENAMAH_MOC} ${RENAMAH_RES})
ADD_DEPENDENCIES(renamah translations_renamah)
TARGET_LINK_LIBRARIES(
renamah core ${QT_LIBRARIES}
)
diff --git a/renamah/filter_model.cpp b/renamah/filter_model.cpp
index cd57df8..39ed1fe 100644
--- a/renamah/filter_model.cpp
+++ b/renamah/filter_model.cpp
@@ -1,88 +1,89 @@
#include <QFileInfo>
#include <interfaces/filter_factory.h>
+#include "filter_manager.h"
#include "filter_model.h"
FilterModel *FilterModel::_instance = 0;
FilterModel &FilterModel::instance()
{
if (!_instance)
_instance = new FilterModel;
return *_instance;
}
FilterModel::FilterModel()
- : ModifierModel()
+ : ModifierModel(&FilterManager::instance())
{
}
QString FilterModel::apply(const QString &filePath, int fileIndex) const
{
QList<core::Filter*> filters;
if (exclusiveModifier())
filters << static_cast<core::Filter*>(exclusiveModifier());
else
foreach (core::Modifier *modifier, _modifiers)
{
if (_modifierStates[modifier])
filters << static_cast<core::Filter*>(modifier);
}
QDir dir = QFileInfo(filePath).dir();
QString tmpFilePath = filePath;
foreach (core::Filter *filter, filters)
{
if (localExtensionPolicyStates[filter])
tmpFilePath = localExtensionPolicies[filter].applyFilterOnFilePath(*filter, fileIndex, tmpFilePath, filePath);
else
tmpFilePath = _extensionPolicy.applyFilterOnFilePath(*filter, fileIndex, tmpFilePath, filePath);
}
return tmpFilePath;
}
void FilterModel::setExtensionPolicy(const ExtensionPolicy &policy)
{
if (policy == _extensionPolicy)
return;
_extensionPolicy = policy;
emit modifiersChanged();
}
bool FilterModel::isLocalExtensionPolicyEnabled(core::Filter *filter) const {
return localExtensionPolicyStates[filter];
}
void FilterModel::setLocalExtensionPolicyEnabled(core::Filter *filter, bool state)
{
localExtensionPolicyStates[filter] = state;
emit modifiersChanged();
}
ExtensionPolicy FilterModel::localExtensionPolicy(core::Filter *filter) const
{
return localExtensionPolicies[filter];
}
void FilterModel::setLocalExtensionPolicy(core::Filter *filter, const ExtensionPolicy &policy)
{
QMap<core::Filter*, ExtensionPolicy>::iterator it = localExtensionPolicies.find(filter);
if (it == localExtensionPolicies.end())
localExtensionPolicies.insert(filter, policy);
else
*it = policy;
emit modifiersChanged();
}
void FilterModel::clear() {
localExtensionPolicies.clear();
localExtensionPolicyStates.clear();
_extensionPolicy = ExtensionPolicy();
ModifierModel::clear();
}
diff --git a/renamah/finalizer_model.cpp b/renamah/finalizer_model.cpp
index c255d7b..dbfc797 100644
--- a/renamah/finalizer_model.cpp
+++ b/renamah/finalizer_model.cpp
@@ -1,37 +1,38 @@
#include <interfaces/action.h>
+#include "action_manager.h"
#include "finalizer_model.h"
FinalizerModel *FinalizerModel::_instance = 0;
FinalizerModel &FinalizerModel::instance()
{
if (!_instance)
_instance = new FinalizerModel;
return *_instance;
}
FinalizerModel::FinalizerModel()
- : ModifierModel()
+ : ModifierModel(&ActionManager::instance())
{
}
void FinalizerModel::apply(const QString &fileName) const
{
if (exclusiveModifier())
{
static_cast<core::Action*>(exclusiveModifier())->apply(fileName);
return;
}
foreach (core::Modifier *modifier, _modifiers)
{
core::Action *action = static_cast<core::Action*>(modifier);
if (_modifierStates[modifier])
{
action->apply(fileName);
}
}
}
diff --git a/renamah/main.cpp b/renamah/main.cpp
index 228afa8..cf0f24b 100644
--- a/renamah/main.cpp
+++ b/renamah/main.cpp
@@ -1,21 +1,17 @@
#include <QApplication>
-#include <QtPlugin>
-#include <QLibraryInfo>
-#include <QTranslator>
-#include <QSettings>
#include "main_window.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setOrganizationName("GuidSofts");
app.setApplicationName("Renamah");
app.setApplicationVersion("0.01a");
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
diff --git a/renamah/main_window.cpp b/renamah/main_window.cpp
index 8811fe8..4a2264d 100644
--- a/renamah/main_window.cpp
+++ b/renamah/main_window.cpp
@@ -1,142 +1,152 @@
#include <QTranslator>
#include <QSettings>
#include <QLibraryInfo>
#include <QFileDialog>
+#include <QShortcut>
#include "plugin_manager.h"
#include "filter_model.h"
#include "processor.h"
#include "profile.h"
+#include "undo_manager.h"
#include "main_window.h"
MainWindow::MainWindow(QWidget *parent)
: actionGroupLanguages(0),
QMainWindow(parent) {
setupUi(this);
PluginManager::instance().load();
tabWidgetMain->setCurrentWidget(tabSimple);
connect(&Processor::instance(), SIGNAL(started()), this, SLOT(processorStarted()));
widgetSimple->initAfterPluginLoaded();
actionLanguage->setMenu(&menuLanguages);
QSettings settings;
QString currentLanguage = settings.value("general/language", "").toString();
if (currentLanguage != "")
installLanguage(currentLanguage);
refreshLanguageActions();
connect(&signalMapperLanguages, SIGNAL(mapped(const QString &)),
this, SLOT(languageRequested(const QString &)));
}
void MainWindow::refreshLanguageActions() {
if (actionGroupLanguages)
delete actionGroupLanguages;
actionGroupLanguages = new QActionGroup(this);
menuLanguages.clear();
QAction *actionToCheck = 0;
QSettings settings;
QString currentLanguage = settings.value("general/language", "").toString();
// Get languages list
foreach (const QFileInfo &fileInfo, QDir(QCoreApplication::applicationDirPath()).entryInfoList(QStringList() << "*.qm",
QDir::Files)) {
QString baseName = fileInfo.baseName();
int p = baseName.indexOf("_");
if (p > 0) {
QString fileLanguage = baseName.mid(p + 1, baseName.length() - p - 1);
QLocale locale(fileLanguage);
QString language = QLocale::languageToString(locale.language());
QString country = QLocale::countryToString(locale.country());
QAction *action = menuLanguages.addAction(QString("%1 (%2)").arg(language).arg(country));
if (fileLanguage == currentLanguage)
actionToCheck = action;
signalMapperLanguages.setMapping(action, fileLanguage);
connect(action, SIGNAL(triggered()), &signalMapperLanguages, SLOT(map()));
action->setCheckable(true);
actionGroupLanguages->addAction(action);
}
}
if (actionToCheck)
actionToCheck->setChecked(true);
}
void MainWindow::processorStarted() {
tabWidgetMain->setCurrentWidget(tabLastOperations);
}
void MainWindow::languageRequested(const QString &language) {
installLanguage(language);
QSettings settings;
settings.setValue("general/language", language);
}
void MainWindow::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi(this);
} else
QWidget::changeEvent(event);
}
void MainWindow::installLanguage(const QString &language) {
// Remove all existing translators
foreach (QTranslator *translator, translators)
qApp->removeTranslator(translator);
translators.clear();
// Install the Qt translator
QTranslator *qtTranslator = new QTranslator;
qtTranslator->load("qt_" + language,
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
qApp->installTranslator(qtTranslator);
// Install the main app translator
QTranslator *translator = new QTranslator;
translator->load("renamah_" + language,
QCoreApplication::applicationDirPath());
qApp->installTranslator(translator);
translators << translator;
// Install all plugins translators
foreach (const QString &fileName, PluginManager::instance().pluginFileNames()) {
QFileInfo fileInfo(fileName);
QString baseName = fileInfo.completeBaseName();
QString qmFileName = fileInfo.absoluteDir().filePath(baseName) + "_" + language + ".qm";
QTranslator *translator = new QTranslator;
translator->load(qmFileName,
QCoreApplication::applicationDirPath());
qApp->installTranslator(translator);
translators << translator;
}
}
void MainWindow::on_actionLoadProfile_triggered() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a profile to load"),
QDir::home().absolutePath());
if (fileName == "")
return;
if (!Profile::load(fileName))
return;
widgetSimple->newProfile();
}
void MainWindow::on_actionSaveProfile_triggered() {
QString fileName = QFileDialog::getSaveFileName(this, tr("Choose a profile filename to save in"),
QDir::home().absolutePath());
if (fileName == "")
return;
Profile::save(fileName);
}
+
+void MainWindow::on_actionUndo_triggered() {
+ UndoManager::instance().undo();
+}
+
+void MainWindow::on_actionRedo_triggered() {
+ UndoManager::instance().redo();
+}
diff --git a/renamah/main_window.h b/renamah/main_window.h
index 6aaafa3..a943ebc 100644
--- a/renamah/main_window.h
+++ b/renamah/main_window.h
@@ -1,33 +1,35 @@
#include <QMenu>
#include <QSignalMapper>
#include <QTranslator>
#include <QActionGroup>
#include "ui_main_window.h"
class MainWindow : public QMainWindow, private Ui::MainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
protected:
void changeEvent(QEvent *event);
private:
QMenu menuLanguages;
QActionGroup *actionGroupLanguages;
QSignalMapper signalMapperLanguages;
QList<QTranslator*> translators;
void refreshLanguageActions();
void installLanguage(const QString &language);
private slots:
void processorStarted();
void languageRequested(const QString &language);
void on_actionLoadProfile_triggered();
void on_actionSaveProfile_triggered();
+ void on_actionUndo_triggered();
+ void on_actionRedo_triggered();
};
diff --git a/renamah/main_window.ui b/renamah/main_window.ui
index f154d69..fb4f7e8 100644
--- a/renamah/main_window.ui
+++ b/renamah/main_window.ui
@@ -1,135 +1,156 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>Renamah</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QTabWidget" name="tabWidgetMain">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabSimple">
<attribute name="title">
<string>Simple</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetSimple" name="widgetSimple" native="true"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabLastOperations">
<attribute name="title">
<string>Last operations</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_4">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="FormLastOperations" name="widgetLastOperations" native="true"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>23</height>
</rect>
</property>
<widget class="QMenu" name="menu_File">
<property name="title">
<string>&File</string>
</property>
<addaction name="actionLoadProfile"/>
<addaction name="actionSaveProfile"/>
<addaction name="separator"/>
<addaction name="action_Quit"/>
</widget>
<widget class="QMenu" name="menuSettings">
<property name="title">
- <string>Settings</string>
+ <string>&Settings</string>
</property>
<addaction name="actionLanguage"/>
</widget>
+ <widget class="QMenu" name="menuEdit">
+ <property name="title">
+ <string>&Edit</string>
+ </property>
+ <addaction name="actionUndo"/>
+ <addaction name="actionRedo"/>
+ </widget>
<addaction name="menu_File"/>
+ <addaction name="menuEdit"/>
<addaction name="menuSettings"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<action name="action_Quit">
<property name="text">
<string>&Quit</string>
</property>
</action>
<action name="actionLanguage">
<property name="text">
<string>Language</string>
</property>
</action>
<action name="actionLoadProfile">
<property name="text">
<string>&Load profile...</string>
</property>
</action>
<action name="actionSaveProfile">
<property name="text">
<string>&Save profile...</string>
</property>
</action>
+ <action name="actionUndo">
+ <property name="text">
+ <string>&Undo</string>
+ </property>
+ <property name="shortcut">
+ <string>Ctrl+Z</string>
+ </property>
+ </action>
+ <action name="actionRedo">
+ <property name="text">
+ <string>&Redo</string>
+ </property>
+ </action>
</widget>
<customwidgets>
<customwidget>
<class>FormLastOperations</class>
<extends>QWidget</extends>
<header>form_last_operations.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetSimple</class>
<extends>QWidget</extends>
<header>widget_simple.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>action_Quit</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>399</x>
<y>299</y>
</hint>
</hints>
</connection>
</connections>
</ui>
diff --git a/renamah/modifier_model.cpp b/renamah/modifier_model.cpp
index 29e6e5e..30e929c 100644
--- a/renamah/modifier_model.cpp
+++ b/renamah/modifier_model.cpp
@@ -1,291 +1,369 @@
#include <QMimeData>
#include <interfaces/modifier_factory.h>
+#include "undo_manager.h"
#include "modifier_model.h"
-ModifierModel::ModifierModel()
- : _exclusiveModifier(0)
+ModifierModel::ModifierModel(ModifierManager *manager)
+ : _manager(manager),
+ _exclusiveModifier(0),
+ _disableUndo(false)
{
}
int ModifierModel::rowCount(const QModelIndex &parent) const
{
return _modifiers.count();
}
int ModifierModel::columnCount(const QModelIndex &parent) const
{
return columnNumber;
}
QVariant ModifierModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= _modifiers.count())
return QVariant();
const core::Modifier *modifier = _modifiers[index.row()];
switch (role)
{
case Qt::DisplayRole:
switch (index.column())
{
case colIndex: return index.row() + 1;
case colMode: return "";
case colCaption: return modifier->factory()->info().caption() + " [" + modifier->resume() + "]";
default:;
}
case Qt::ForegroundRole:
if (_exclusiveModifier && _exclusiveModifier != modifier)
return Qt::gray;
break;
default:;
}
return QVariant();
}
QVariant ModifierModel::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role)
{
case Qt::DisplayRole:
switch (section)
{
case colIndex: return tr("#");
case colMode: return tr("Mode");
case colCaption: return tr("Action");
default:;
}
break;
default:;
}
return QVariant();
}
+void ModifierModel::init(core::Modifier *modifier) {
+ connect(modifier, SIGNAL(settingsChanging()), this, SLOT(modifierChanging()));
+ connect(modifier, SIGNAL(settingsChanged()), this, SLOT(modifierChanged()));
+ connect(modifier, SIGNAL(settingsChanged()), this, SIGNAL(modifiersChanged()));
+}
+
void ModifierModel::addModifier(core::Modifier *modifier)
{
- connect(modifier, SIGNAL(settingsChanged()), this, SIGNAL(modifiersChanged()));
+ init(modifier);
beginInsertRows(QModelIndex(), _modifiers.count(), _modifiers.count());
_modifiers << modifier;
_modifierStates[modifier] = true;
endInsertRows();
+ if (!_disableUndo) {
+ CreateModifierCommand *command = new CreateModifierCommand(this, _manager, modifier->factory()->info().name());
+ UndoManager::instance().push(command);
+ command->activate();
+ }
+
+ emit modifiersChanged();
+}
+
+void ModifierModel::insertModifier(int index, core::Modifier *modifier) {
+ init(modifier);
+
+ beginInsertRows(QModelIndex(), _modifiers.count(), _modifiers.count());
+ _modifiers.insert(index, modifier);
+ _modifierStates[modifier] = true;
+ endInsertRows();
+
+ // TODO : integrate into the undo framework!!!
+
emit modifiersChanged();
}
void ModifierModel::removeModifier(const QModelIndex &index)
{
if (!index.isValid())
return;
removeRows(index.row(), 1);
}
bool ModifierModel::modifierState(core::Modifier *modifier) const
{
if (_modifierStates.find(modifier) == _modifierStates.end())
return false;
else
return _modifierStates[modifier];
}
void ModifierModel::setModifierState(core::Modifier *modifier, bool state)
{
int modifierRow = _modifiers.indexOf(modifier);
if (modifierRow < 0)
return;
if (_modifierStates[modifier] != state)
{
_modifierStates[modifier] = state;
emit dataChanged(index(modifierRow, 0), index(modifierRow, columnNumber - 1));
emit modifiersChanged();
}
}
void ModifierModel::toggleModifierState(core::Modifier *modifier)
{
if (_modifierStates.find(modifier) == _modifierStates.end())
return;
setModifierState(modifier, !_modifierStates[modifier]);
}
void ModifierModel::setExclusiveModifier(core::Modifier *modifier)
{
if (_exclusiveModifier == modifier)
return;
_exclusiveModifier = modifier;
if (modifier)
_modifierStates[modifier] = true;
// Refresh all
emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
emit modifiersChanged();
}
/*QString ModifierModel::apply(const QString &str) const
{
if (_exclusiveModifier)
return _exclusiveModifier->apply(str);
QString filtered = str;
foreach (core::Filter *filter, _modifiers)
if (_modifierstates[filter])
filtered = filter->apply(filtered);
return filtered;
}*/
core::Modifier *ModifierModel::modifier(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
if (index.row() >= 0 && index.row() < rowCount())
return _modifiers[index.row()];
}
Qt::ItemFlags ModifierModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractListModel::flags(index);
if (index.isValid())
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
else
return Qt::ItemIsDropEnabled | flags;
}
void ModifierModel::toggleExclusiveState(core::Modifier *modifier)
{
if (_exclusiveModifier == modifier)
_exclusiveModifier = 0;
else
_exclusiveModifier = modifier;
if (_exclusiveModifier)
_modifierStates[_exclusiveModifier] = true;
// Refresh all
emit dataChanged(index(0, 0), index(rowCount() - 1, columnNumber - 1));
emit modifiersChanged();
}
bool ModifierModel::upModifier(const QModelIndex &modifierIndex)
{
if (!modifierIndex.row())
return false;
_modifiers.swap(modifierIndex.row(), modifierIndex.row() - 1);
emit dataChanged(index(modifierIndex.row() - 1, 0),
index(modifierIndex.row(), columnNumber - 1));
emit modifiersChanged();
return true;
}
bool ModifierModel::downModifier(const QModelIndex &modifierIndex)
{
if (modifierIndex.row() == rowCount() - 1)
return false;
_modifiers.swap(modifierIndex.row(), modifierIndex.row() + 1);
emit dataChanged(index(modifierIndex.row(), 0),
index(modifierIndex.row() + 1, columnNumber - 1));
emit modifiersChanged();
return true;
}
Qt::DropActions ModifierModel::supportedDropActions() const {
return Qt::MoveAction;
}
bool ModifierModel::removeRows(int row, int count, const QModelIndex &parent) {
core::Modifier *modifierToRemove = modifier(index(row, 0));
+ if (!_disableUndo) {
+ RemoveModifierCommand *command = new RemoveModifierCommand(this, _manager, row, modifierToRemove->factory()->info().name(),
+ modifierToRemove->serializeProperties());
+ UndoManager::instance().push(command);
+ command->activate();
+ }
+
beginRemoveRows(QModelIndex(), row, row);
_modifiers.removeAt(_modifiers.indexOf(modifierToRemove));
_modifierStates.remove(modifierToRemove);
if (_exclusiveModifier == modifierToRemove)
_exclusiveModifier = 0;
delete modifierToRemove;
endRemoveRows();
emit modifiersChanged();
}
#define MIMETYPE QLatin1String("filter-rows")
QStringList ModifierModel::mimeTypes() const
{
QStringList types;
types << MIMETYPE;
return types;
}
QMimeData *ModifierModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *mimeData = new QMimeData;
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
stream << index.row();
}
}
mimeData->setData(MIMETYPE, encodedData);
return mimeData;
}
bool ModifierModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
if (action == Qt::IgnoreAction)
return false;
QByteArray inData = data->data(MIMETYPE);
QDataStream stream(inData);
int r;
stream >> r;
core::Modifier *modifier = _modifiers[r];
if (row != -1) {
if (row >= rowCount()) {
_modifiers.takeAt(r);
_modifiers << modifier;
_dropRow = rowCount() - 1;
} else {
if (r < row)
row--;
_modifiers.move(r, row);
_dropRow = row;
}
} else if (parent.isValid()) {
_modifiers.move(r, parent.row());
_dropRow = parent.row();
} else if (!parent.isValid()) {
_modifiers.takeAt(r);
_modifiers << modifier;
_dropRow = rowCount() - 1;
}
emit modifiersChanged();
emit dropDone();
return false;
}
void ModifierModel::clear() {
_exclusiveModifier = 0;
qDeleteAll(_modifiers);
_modifiers.clear();
_modifierStates.clear();
reset();
emit modifiersChanged();
}
+
+void ModifierModel::modifierChanged() {
+ if (_disableUndo)
+ return;
+
+ core::Modifier *modifier = static_cast<core::Modifier*>(sender());
+
+ // Undo managing => compute the diff
+ QMap<QString,QPair<QString,QVariant> > newProperties = modifier->serializeProperties();
+ QMap<QString,QPair<QString,QVariant> > &oldProperties = _changingModifierOldProperties;
+ QMap<QString,QPair<QString,QVariant> > undoProperties, redoProperties;
+
+ foreach (const QString &propName, newProperties.keys()) {
+ QPair<QString,QVariant> &newPair = newProperties[propName];
+ QPair<QString,QVariant> &oldPair = oldProperties[propName];
+
+ if (newPair != oldPair) {
+ undoProperties.insert(propName, oldPair);
+ redoProperties.insert(propName, newPair);
+ }
+ }
+
+ ModifyModifierCommand *command = new ModifyModifierCommand(this, _modifiers.indexOf(modifier), undoProperties, redoProperties);
+ UndoManager::instance().push(command);
+ command->activate();
+}
+
+void ModifierModel::modifierChanging() {
+ if (_disableUndo)
+ return;
+
+ core::Modifier *modifier = static_cast<core::Modifier*>(sender());
+
+ _changingModifierOldProperties = modifier->serializeProperties();
+}
+
+void ModifierModel::beginUndoAction() {
+ _disableUndo = true;
+}
+
+void ModifierModel::endUndoAction() {
+ _disableUndo = false;
+}
diff --git a/renamah/modifier_model.h b/renamah/modifier_model.h
index 493e43b..db37fcf 100644
--- a/renamah/modifier_model.h
+++ b/renamah/modifier_model.h
@@ -1,89 +1,106 @@
#ifndef MODIFIER_MODEL_H
#define MODIFIER_MODEL_H
#include <QAbstractListModel>
#include <QList>
#include <interfaces/filter.h>
+#include "modifier_manager.h"
+
class ModifierModel : public QAbstractListModel
{
Q_OBJECT
public:
static const int colIndex = 3;
static const int colMode = 0;
static const int colCaption = 1;
static const int columnNumber = 2;
- ModifierModel();
+ ModifierModel(ModifierManager *manager);
- /*! Returns a modifier in function of a model index */
+ /** Returns a modifier in function of a model index */
core::Modifier *modifier(const QModelIndex &index) const;
- /*! Add a modifier to the model */
+ /** Add a modifier to the model */
void addModifier(core::Modifier *modifier);
+ /** Insert a modifier into the model */
+ void insertModifier(int index, core::Modifier *modifier);
+
/*! Remove the modifier at <index> */
void removeModifier(const QModelIndex &index);
/*! Clear all modifiers */
virtual void clear();
/*! Returns the modifier state */
bool modifierState(core::Modifier *modifier) const;
/*! Activate or deactivate a modifier */
void setModifierState(core::Modifier *modifier, bool state);
/*! Toggle the state of the modifier */
void toggleModifierState(core::Modifier *modifier);
/*! Set a modifier as the uniq modifier, deactivate others */
void setExclusiveModifier(core::Modifier *modifier);
/*! If modifier was not exclusive => set it exclusive */
void toggleExclusiveState(core::Modifier *modifier);
/*! Up the modifier which index is in parameter
* \returns true if the operation has been succeed
*/
bool upModifier(const QModelIndex &modifierIndex);
/*! Down the modifier which index is in parameter
* \returns true if the operation has been succeed
*/
bool downModifier(const QModelIndex &modifierIndex);
/*! Returns the exclusive modifier */
core::Modifier *exclusiveModifier() const { return _exclusiveModifier; }
void refreshLayout() { emit layoutChanged(); }
int dropRow() const { return _dropRow; }
+ void beginUndoAction(); // Must be called just before the undo manager makes an undo or a redo action
+ void endUndoAction(); // Must be called just after the undo manager makes an undo or a redo action
+
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
Qt::DropActions supportedDropActions() const;
QStringList mimeTypes() const;
QMimeData *mimeData(const QModelIndexList &indexes) const;
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
signals:
void modifiersChanged();
void dropDone();
protected:
+ ModifierManager *_manager;
QList<core::Modifier*> _modifiers;
QMap<core::Modifier*, bool> _modifierStates;
core::Modifier *_exclusiveModifier;
+ QMap<QString,QPair<QString,QVariant> > _changingModifierOldProperties;
private:
int _dropRow;
+ bool _disableUndo;
+
+ void init(core::Modifier *modifier);
+
+private slots:
+ void modifierChanging();
+ void modifierChanged();
};
#endif
diff --git a/renamah/undo_manager.cpp b/renamah/undo_manager.cpp
new file mode 100644
index 0000000..971db88
--- /dev/null
+++ b/renamah/undo_manager.cpp
@@ -0,0 +1,114 @@
+#include "undo_manager.h"
+
+UndoManager *UndoManager::_instance = 0;
+
+UndoManager &UndoManager::instance() {
+ if (!_instance)
+ _instance = new UndoManager;
+
+ return *_instance;
+}
+
+/////////////////////////////////
+/// ModifierCommand /////////////
+/////////////////////////////////
+
+ModifierCommand::ModifierCommand(ModifierModel *model)
+ : _model(model),
+ _activated(false) {
+}
+
+void ModifierCommand::undo() {
+ if (!_activated)
+ return;
+
+ _model->beginUndoAction();
+ makeUndo();
+ _model->endUndoAction();
+}
+
+void ModifierCommand::redo() {
+ if (!_activated)
+ return;
+
+ _model->beginUndoAction();
+ makeRedo();
+ _model->endUndoAction();
+}
+
+/////////////////////////////////
+/// ModifyModifierCommand ///////
+/////////////////////////////////
+
+ModifyModifierCommand::ModifyModifierCommand(ModifierModel *model,
+ int modifierIndex,
+ const QMap<QString,QPair<QString,QVariant> > &undoProperties,
+ const QMap<QString,QPair<QString,QVariant> > &redoProperties)
+ : ModifierCommand(model),
+ _modifierIndex(modifierIndex),
+ _undoProperties(undoProperties),
+ _redoProperties(redoProperties) {
+ setText("Modifier modification");
+}
+
+void ModifyModifierCommand::makeUndo() {
+ core::Modifier *modifier = _model->modifier(_model->index(_modifierIndex, 0));
+ modifier->deserializeProperties(_undoProperties);
+}
+
+void ModifyModifierCommand::makeRedo() {
+ core::Modifier *modifier = _model->modifier(_model->index(_modifierIndex, 0));
+ modifier->deserializeProperties(_redoProperties);
+}
+
+/////////////////////////////////
+/// CreateModifierCommand ///////
+/////////////////////////////////
+
+CreateModifierCommand::CreateModifierCommand(ModifierModel *model,
+ ModifierManager *manager,
+ const QString &factoryName)
+ : ModifierCommand(model),
+ _manager(manager),
+ _factoryName(factoryName) {
+ setText("Modifier creation");
+}
+
+void CreateModifierCommand::makeUndo() {
+ _model->removeModifier(_model->index(_model->rowCount() - 1, 0));
+}
+
+void CreateModifierCommand::makeRedo() {
+ core::ModifierFactory *factory = _manager->factoryByName(_factoryName);
+ core::Modifier *modifier = factory->makeModifier();
+ _model->addModifier(modifier);
+}
+
+/////////////////////////////////
+/// RemoveModifierCommand ///////
+/////////////////////////////////
+
+RemoveModifierCommand::RemoveModifierCommand(ModifierModel *model,
+ ModifierManager *manager,
+ int modifierIndex,
+ const QString &factoryName,
+ const QMap<QString,QPair<QString,QVariant> > &properties)
+ : ModifierCommand(model),
+ _manager(manager),
+ _modifierIndex(modifierIndex),
+ _factoryName(factoryName),
+ _properties(properties) {
+ setText("Modifier removing");
+}
+
+void RemoveModifierCommand::makeUndo() {
+ core::ModifierFactory *factory = _manager->factoryByName(_factoryName);
+ core::Modifier *modifier = factory->makeModifier();
+ modifier->deserializeProperties(_properties);
+ _model->insertModifier(_modifierIndex, modifier);
+}
+
+void RemoveModifierCommand::makeRedo() {
+ _model->removeModifier(_model->index(_modifierIndex, 0));
+}
+
diff --git a/renamah/undo_manager.h b/renamah/undo_manager.h
new file mode 100644
index 0000000..63f7643
--- /dev/null
+++ b/renamah/undo_manager.h
@@ -0,0 +1,98 @@
+#ifndef UNDO_MANAGER_H
+#define UNDO_MANAGER_H
+
+#include <QUndoStack>
+#include <QUndoCommand>
+#include <QMap>
+#include <QPair>
+#include <QVariant>
+
+#include "modifier_model.h"
+#include "modifier_manager.h"
+
+class ModifierCommand : public QUndoCommand
+{
+public:
+ ModifierCommand(ModifierModel *model);
+
+ /// undo/redo won't work until this command is activated
+ void activate() { _activated = true; }
+
+ void undo();
+ void redo();
+
+protected:
+ ModifierModel *_model;
+
+ virtual void makeUndo() = 0;
+ virtual void makeRedo() = 0;
+
+private:
+ bool _activated;
+};
+
+class ModifyModifierCommand : public ModifierCommand
+{
+public:
+ ModifyModifierCommand(ModifierModel *model,
+ int modifierIndex,
+ const QMap<QString,QPair<QString,QVariant> > &undoProperties,
+ const QMap<QString,QPair<QString,QVariant> > &redoProperties);
+
+ void makeUndo();
+ void makeRedo();
+
+private:
+ int _modifierIndex;
+ QMap<QString,QPair<QString,QVariant> > _undoProperties;
+ QMap<QString,QPair<QString,QVariant> > _redoProperties;
+};
+
+class CreateModifierCommand : public ModifierCommand
+{
+public:
+ CreateModifierCommand(ModifierModel *model,
+ ModifierManager *manager,
+ const QString &factoryName);
+
+ void makeUndo();
+ void makeRedo();
+
+private:
+ ModifierManager *_manager;
+ QString _factoryName;
+};
+
+class RemoveModifierCommand : public ModifierCommand
+{
+public:
+ RemoveModifierCommand(ModifierModel *model,
+ ModifierManager *manager,
+ int modifierIndex,
+ const QString &factoryName,
+ const QMap<QString,QPair<QString,QVariant> > &properties);
+
+ void makeUndo();
+ void makeRedo();
+
+private:
+ ModifierManager *_manager;
+ int _modifierIndex;
+ QString _factoryName;
+ QMap<QString,QPair<QString,QVariant> > _properties;
+};
+
+class UndoManager : public QUndoStack
+{
+ Q_OBJECT
+
+public:
+ static UndoManager &instance();
+
+private:
+ UndoManager(QObject *parent = 0) : QUndoStack(parent) {}
+
+ static UndoManager *_instance;
+};
+
+#endif
diff --git a/renamah/widget_modifiers.cpp b/renamah/widget_modifiers.cpp
index b8a6f44..7f3fc4c 100644
--- a/renamah/widget_modifiers.cpp
+++ b/renamah/widget_modifiers.cpp
@@ -1,238 +1,242 @@
#include <QMessageBox>
#include <QMouseEvent>
#include <QHeaderView>
#include <QMetaProperty>
#include "modifier_delegate.h"
#include "widget_modifiers.h"
WidgetModifiers::WidgetModifiers(QWidget *parent)
: QWidget(parent),
_modifierManager(0),
_modifierModel(0) {
setupUi(this);
connect(&signalMapperAddModifier, SIGNAL(mapped(const QString &)),
this, SLOT(addModifier(const QString &)));
pushButtonAdd->setMenu(&menuAddModifier);
connect(&menuAddModifier, SIGNAL(aboutToShow()), this, SLOT(aboutToShowAddModifierMenu()));
treeView->setItemDelegate(new ModifierDelegate);
labelAddModifier->installEventFilter(this);
treeView->viewport()->installEventFilter(this);
treeView->installEventFilter(this);
}
void WidgetModifiers::init(ModifierManager *modifierManager, ModifierModel &modifierModel) {
_modifierManager = modifierManager;
_modifierModel = &modifierModel;
retranslate();
treeView->setModel(_modifierModel);
connect(_modifierModel, SIGNAL(dropDone()),
this, SLOT(filterDropDone()));
+ connect(_modifierModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
+ this, SLOT(modifiersInserted(const QModelIndex &, int, int)));
treeView->header()->setResizeMode(0, QHeaderView::ResizeToContents);
treeView->header()->setResizeMode(1, QHeaderView::ResizeToContents);
connect(treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(currentModifierChanged(const QModelIndex &, const QModelIndex &)));
currentModifierChanged(QModelIndex(), QModelIndex());
}
void WidgetModifiers::retranslate() {
labelAddModifier->setText(tr("Add a new %1").arg(_modifierManager->modifierTypeName()));
core::Modifier *modifier = currentModifier();
if (!modifier)
return;
core::ModifierFactory *factory = modifier->factory();
labelModifierCaption->setText(factory->info().caption());
labelModifierDescription->setText(factory->info().description());
}
void WidgetModifiers::on_pushButtonRemove_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this filter?"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
_modifierModel->removeModifier(index);
}
void WidgetModifiers::on_pushButtonUp_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
int row = index.row();
if (_modifierModel->upModifier(index))
treeView->setCurrentIndex(_modifierModel->index(row - 1, 0));
}
void WidgetModifiers::on_pushButtonDown_clicked() {
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
int row = index.row();
if (_modifierModel->downModifier(index))
treeView->setCurrentIndex(_modifierModel->index(row + 1, 0));
}
void WidgetModifiers::aboutToShowAddModifierMenu() {
menuAddModifier.clear();
foreach (core::ModifierFactory *factory, _modifierManager->factories())
{
QAction *action = menuAddModifier.addAction(factory->info().caption() + " (" + factory->info().description() + ")");
connect(action, SIGNAL(triggered()), &signalMapperAddModifier, SLOT(map()));
signalMapperAddModifier.setMapping(action, factory->info().name());
}
}
void WidgetModifiers::addModifier(const QString &factoryName) {
core::ModifierFactory *factory = _modifierManager->factoryByName(factoryName);
Q_ASSERT_X(factory, "WidgetModifiers::addModifierClicked()", "<factoryName> seems to have no factory correspondant");
_modifierModel->addModifier(factory->makeModifier());
- QModelIndex index = _modifierModel->index(_modifierModel->rowCount() - 1);
- treeView->setCurrentIndex(_modifierModel->index(_modifierModel->rowCount() - 1));
stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
}
void WidgetModifiers::currentModifierChanged(const QModelIndex ¤t, const QModelIndex &previous) {
if (previous.isValid())
{
core::Modifier *previousModifier = _modifierModel->modifier(previous);
core::ModifierFactory *previousFactory = previousModifier->factory();
if (_configWidget)
{
previousFactory->deleteConfigurationWidget(_configWidget);
_configWidget = 0;
}
}
if (!current.isValid())
{
stackedWidgetConfiguration->setCurrentWidget(pageNoModifiers);
currentModifierChanged(0);
return;
}
stackedWidgetConfiguration->setCurrentWidget(pageConfiguration);
core::Modifier *modifier = _modifierModel->modifier(current);
core::ModifierFactory *factory = modifier->factory();
_configWidget = modifier->factory()->makeConfigurationWidget(modifier);
if (_configWidget)
{
setConfigWidget(_configWidget);
frameConfiguration->setVisible(true);
labelModifierCaption->setText(factory->info().caption());
labelModifierDescription->setText(factory->info().description());
connect(modifier, SIGNAL(settingsChanged()), this, SLOT(widgetModifierChanged()));
}
currentModifierChanged(modifier);
}
bool WidgetModifiers::eventFilter(QObject *obj, QEvent *ev) {
if (obj == labelAddModifier && ev->type() == QEvent::MouseButtonPress)
{
QMouseEvent *event = static_cast<QMouseEvent*>(ev);
menuAddModifier.popup(event->globalPos());
} else if (obj == treeView->viewport() && ev->type() == QEvent::MouseButtonPress)
{
QMouseEvent *event = static_cast<QMouseEvent*>(ev);
QPoint p = event->pos();
QModelIndex index = treeView->indexAt(p);
if (index.column() == ModifierModel::colMode)
{
if (modifierStateRect(index).contains(p))
_modifierModel->toggleModifierState(_modifierModel->modifier(index));
else
{
if (modifierOnlyRect(index).contains(p))
_modifierModel->toggleExclusiveState(_modifierModel->modifier(index));
}
}
} else if (obj == treeView && ev->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(ev);
if (keyEvent->key() == Qt::Key_Delete)
{
on_pushButtonRemove_clicked();
}
}
return QWidget::eventFilter(obj, ev);
}
QRect WidgetModifiers::modifierStateRect(const QModelIndex &index) const {
QRect indexRect = treeView->visualRect(index);
QRect res(indexRect.left(), indexRect.top(), 16, 16);
if (indexRect.width() > 32)
res.translate((indexRect.width() - 32) / 2, 0);
if (indexRect.height() > 16)
res.translate(0, (indexRect.height() - 16) / 2);
return res;
}
QRect WidgetModifiers::modifierOnlyRect(const QModelIndex &index) const {
QRect indexRect = treeView->visualRect(index);
QRect res(indexRect.left() + 16, indexRect.top(), 16, 16);
if (indexRect.width() > 32)
res.translate((indexRect.width() - 32) / 2, 0);
if (indexRect.height() > 16)
res.translate(0, (indexRect.height() - 16) / 2);
return res;
}
void WidgetModifiers::widgetModifierChanged() {
if (treeView->currentIndex().isValid())
{
_modifierModel->refreshLayout();
treeView->update(treeView->currentIndex());
}
}
core::Modifier *WidgetModifiers::currentModifier() const {
return _modifierModel->modifier(treeView->currentIndex());
}
void WidgetModifiers::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
retranslateUi(this);
retranslate();
} else
QWidget::changeEvent(event);
}
void WidgetModifiers::filterDropDone() {
treeView->setCurrentIndex(_modifierModel->index(_modifierModel->dropRow(), 0));
}
void WidgetModifiers::newProfile() {
if (_modifierModel->rowCount())
treeView->setCurrentIndex(_modifierModel->index(0, 0));
}
+
+void WidgetModifiers::modifiersInserted(const QModelIndex &parent, int start, int end) {
+ treeView->setCurrentIndex(_modifierModel->index(start));
+}
diff --git a/renamah/widget_modifiers.h b/renamah/widget_modifiers.h
index 9054b59..cb25651 100644
--- a/renamah/widget_modifiers.h
+++ b/renamah/widget_modifiers.h
@@ -1,56 +1,57 @@
#ifndef WIDGET_MODIFIERS_H
#define WIDGET_MODIFIERS_H
#include <QMenu>
#include <QSignalMapper>
#include "modifier_manager.h"
#include "modifier_model.h"
#include "ui_widget_modifiers.h"
class WidgetModifiers : public QWidget, protected Ui::WidgetModifiers
{
Q_OBJECT
public:
WidgetModifiers(QWidget *parent = 0);
virtual void init(ModifierManager *modifierManager, ModifierModel &modifierModel);
/*! Called after each profile loaded */
virtual void newProfile();
public slots:
void addModifier(const QString &factoryName);
protected:
bool eventFilter(QObject *obj, QEvent *ev);
void changeEvent(QEvent *event);
core::Modifier *currentModifier() const;
virtual void setConfigWidget(QWidget *widget) = 0;
virtual void currentModifierChanged(core::Modifier *modifier) {};
private:
core::ModifierConfigWidget *_configWidget;
QMenu menuAddModifier;
QSignalMapper signalMapperAddModifier;
ModifierManager *_modifierManager;
ModifierModel *_modifierModel;
QRect modifierStateRect(const QModelIndex &index) const;
QRect modifierOnlyRect(const QModelIndex &index) const;
void retranslate();
private slots:
void on_pushButtonRemove_clicked();
void on_pushButtonUp_clicked();
void on_pushButtonDown_clicked();
void aboutToShowAddModifierMenu();
void currentModifierChanged(const QModelIndex ¤t, const QModelIndex &previous);
void widgetModifierChanged();
void filterDropDone();
+ void modifiersInserted(const QModelIndex &parent, int start, int end);
};
#endif
|
Guid75/renamah
|
c6a601fa8fcbd3b44af298d443e758032ba700cd
|
new french translation
|
diff --git a/renamah/translations/renamah_en_US.ts b/renamah/translations/renamah_en_US.ts
index 93f8b69..7e310cf 100644
--- a/renamah/translations/renamah_en_US.ts
+++ b/renamah/translations/renamah_en_US.ts
@@ -1,442 +1,447 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
<name>DialogManualRename</name>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Do you really want to set the original filename?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
<location filename="../file_model.cpp" line="92"/>
<source>Original</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../file_model.cpp" line="93"/>
<source>Renamed</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
<location filename="../form_twinning.cpp" line="190"/>
<source>Choose a directory for left files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.cpp" line="201"/>
<source>Choose a directory for right files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="25"/>
<source>Simple</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="38"/>
<source>Last operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="64"/>
<source>&File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="73"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="83"/>
<source>&Quit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="88"/>
<source>Language</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="93"/>
<source>&Load profile...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="98"/>
<source>&Save profile...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.cpp" line="124"/>
<source>Choose a profile to load</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.cpp" line="136"/>
<source>Choose a profile filename to save in</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
<location filename="../modifier_model.cpp" line="54"/>
<source>#</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="55"/>
<source>Mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="56"/>
<source>Action</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
<location filename="../processor.cpp" line="127"/>
<source>Rename</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="128"/>
<source>Copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="129"/>
<source>Move</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="130"/>
<source>Create link</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
<location filename="../widget_filters.cpp" line="38"/>
<source>Override the global extension policy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="39"/>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="40"/>
<source>Extension policy</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
<location filename="../widget_modifiers.cpp" line="48"/>
<source>Add a new %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Confirmation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Do you really want to remove this filter?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
- <location filename="../widget_simple.cpp" line="226"/>
+ <location filename="../widget_simple.cpp" line="233"/>
<source>Confirmation</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="226"/>
+ <location filename="../widget_simple.cpp" line="233"/>
<source>Do you really want to remove this files?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="91"/>
+ <location filename="../widget_simple.cpp" line="96"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="91"/>
+ <location filename="../widget_simple.cpp" line="96"/>
<source>Do you really want to start the rename process?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="135"/>
+ <location filename="../widget_simple.cpp" line="140"/>
<source>Choose a destination directory</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
- <location filename="../widget_simple.cpp" line="145"/>
+ <location filename="../widget_simple.cpp" line="150"/>
<source>%n files</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="241"/>
+ <location filename="../widget_simple.cpp" line="251"/>
<source>Pick some files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="141"/>
+ <location filename="../widget_simple.ui" line="107"/>
<source>Add some files...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="158"/>
- <location filename="../widget_simple.ui" line="334"/>
+ <location filename="../widget_simple.ui" line="124"/>
+ <location filename="../widget_simple.ui" line="462"/>
<source>Remove selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="201"/>
+ <location filename="../widget_simple.ui" line="167"/>
<source>Sort by</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="211"/>
- <location filename="../widget_simple.ui" line="358"/>
+ <location filename="../widget_simple.ui" line="177"/>
+ <location filename="../widget_simple.ui" line="486"/>
<source>Up selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="228"/>
- <location filename="../widget_simple.ui" line="370"/>
+ <location filename="../widget_simple.ui" line="194"/>
+ <location filename="../widget_simple.ui" line="498"/>
<source>Down selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="249"/>
+ <location filename="../widget_simple.ui" line="330"/>
+ <source>Click to add some files</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="377"/>
<source>Extension policy</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="284"/>
+ <location filename="../widget_simple.ui" line="412"/>
<source>Filters</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="297"/>
+ <location filename="../widget_simple.ui" line="425"/>
<source>Finalizers</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="314"/>
+ <location filename="../widget_simple.ui" line="442"/>
<source>by name</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="317"/>
+ <location filename="../widget_simple.ui" line="445"/>
<source>Sort files by name</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="322"/>
+ <location filename="../widget_simple.ui" line="450"/>
<source>by modification date</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="331"/>
+ <location filename="../widget_simple.ui" line="459"/>
<source>&Remove</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="343"/>
+ <location filename="../widget_simple.ui" line="471"/>
<source>&Add</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="346"/>
+ <location filename="../widget_simple.ui" line="474"/>
<source>Add files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="355"/>
+ <location filename="../widget_simple.ui" line="483"/>
<source>&Up</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="367"/>
+ <location filename="../widget_simple.ui" line="495"/>
<source>&Down</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
diff --git a/renamah/translations/renamah_fr.ts b/renamah/translations/renamah_fr.ts
index 1f590e7..7577268 100644
--- a/renamah/translations/renamah_fr.ts
+++ b/renamah/translations/renamah_fr.ts
@@ -1,444 +1,449 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>DialogManualRename</name>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Do you really want to set the original filename?</source>
<translatorcomment>bof</translatorcomment>
<translation>Ãtes-vous sûr de vouloir affecter le nom de fichier original ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation>Renommage manuel</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation>Retour au renommage automatique</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation>Valeur originale</translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
<location filename="../file_model.cpp" line="92"/>
<source>Original</source>
<translation>Original</translation>
</message>
<message>
<location filename="../file_model.cpp" line="93"/>
<source>Renamed</source>
<translation>Renommé</translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
<location filename="../form_twinning.cpp" line="190"/>
<source>Choose a directory for left files</source>
<translation>Choisissez un répertoire pour les fichiers de gauche</translation>
</message>
<message>
<location filename="../form_twinning.cpp" line="201"/>
<source>Choose a directory for right files</source>
<translation>Choisissez un répertoire pour les fichiers de droite</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
<translation>Extension :</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
<translation>*avi,*.mkv</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
<translation>Statut</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
<translation>lancer</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation></translation>
</message>
<message>
<location filename="../main_window.ui" line="25"/>
<source>Simple</source>
<translation>Simple</translation>
</message>
<message>
<location filename="../main_window.ui" line="38"/>
<source>Last operations</source>
<translation>Dernières opérations</translation>
</message>
<message>
<location filename="../main_window.ui" line="64"/>
<source>&File</source>
<translation>&Fichier</translation>
</message>
<message>
<location filename="../main_window.ui" line="73"/>
<source>Settings</source>
<translation>Paramètres</translation>
</message>
<message>
<location filename="../main_window.ui" line="83"/>
<source>&Quit</source>
<translation>&Quitter</translation>
</message>
<message>
<location filename="../main_window.ui" line="88"/>
<source>Language</source>
<translation>Langage</translation>
</message>
<message>
<location filename="../main_window.ui" line="93"/>
<source>&Load profile...</source>
<translation>&Charge un profile...</translation>
</message>
<message>
<location filename="../main_window.ui" line="98"/>
<source>&Save profile...</source>
<translation>&Sauver le profile...</translation>
</message>
<message>
<location filename="../main_window.cpp" line="124"/>
<source>Choose a profile to load</source>
<translation>Choisissez un profile à charger</translation>
</message>
<message>
<location filename="../main_window.cpp" line="136"/>
<source>Choose a profile filename to save in</source>
<translation>Choisissez un nom de profile à sauver</translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
<location filename="../modifier_model.cpp" line="54"/>
<source>#</source>
<translation></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="55"/>
<source>Mode</source>
<translation>Mode</translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="56"/>
<source>Action</source>
<translation>Action</translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
<location filename="../processor.cpp" line="127"/>
<source>Rename</source>
<translation>Renommer</translation>
</message>
<message>
<location filename="../processor.cpp" line="128"/>
<source>Copy</source>
<translation>Copier</translation>
</message>
<message>
<location filename="../processor.cpp" line="129"/>
<source>Move</source>
<translation>Déplacer</translation>
</message>
<message>
<location filename="../processor.cpp" line="130"/>
<source>Create link</source>
<translation>Créer un lien</translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation>Souhaitez-vous vraiment revenir à la politique d'extension par défaut ?</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation>Choisissez quelle partie des fichiers vous voulez renommer :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation>Le nom de base (sans l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation>Le nom de fichier en entier (avec l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation>Seulement l'extension</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation>Paramètres par défaut</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation>L'extension du fichier commence juste après le :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation>Premier point en partant de la droite</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation>Premier point en partant de la gauche</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation>ième point en partant de la droite</translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
<location filename="../widget_filters.cpp" line="39"/>
<source>General</source>
<translation>Général</translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="40"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="38"/>
<source>Override the global extension policy</source>
<translation>Supplanter la politique d'extension globale</translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
<location filename="../widget_modifiers.cpp" line="48"/>
<source>Add a new %1</source>
<translation>Ajouter un nouveau %1</translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Confirmation</source>
<translation>Confirmation</translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Do you really want to remove this filter?</source>
<translation>Voulez-vous réellement supprimer ce filtre ?</translation>
</message>
<message>
<location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation>Cliquez pour ajouter</translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
- <location filename="../widget_simple.cpp" line="226"/>
+ <location filename="../widget_simple.cpp" line="233"/>
<source>Confirmation</source>
<translation>Confirmation</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="226"/>
+ <location filename="../widget_simple.cpp" line="233"/>
<source>Do you really want to remove this files?</source>
<translation>Ãtes-vous certain de vouloir supprimer ces fichiers ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="91"/>
+ <location filename="../widget_simple.cpp" line="96"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="91"/>
+ <location filename="../widget_simple.cpp" line="96"/>
<source>Do you really want to start the rename process?</source>
<translation>Voulez-vous vraiment démarrer le processus de renommage ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="135"/>
+ <location filename="../widget_simple.cpp" line="140"/>
<source>Choose a destination directory</source>
<translation>Choisissez un répertoire de destination</translation>
</message>
<message numerus="yes">
- <location filename="../widget_simple.cpp" line="145"/>
+ <location filename="../widget_simple.cpp" line="150"/>
<source>%n files</source>
<translation>
<numerusform>%n fichier</numerusform>
<numerusform>%n fichiers</numerusform>
</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="241"/>
+ <location filename="../widget_simple.cpp" line="251"/>
<source>Pick some files</source>
<translation>Choisissez des fichiers</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation>Lancer</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation>Renommage de fichier</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation>Copie renommée dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation>Déplacement renommé dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation>Création des liens dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
<translation></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="141"/>
+ <location filename="../widget_simple.ui" line="107"/>
<source>Add some files...</source>
<translation>Ajouter des fichiers...</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="331"/>
+ <location filename="../widget_simple.ui" line="330"/>
+ <source>Click to add some files</source>
+ <translation>Cliquer pour ajouter des fichiers</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="459"/>
<source>&Remove</source>
<translation>&Supprimer</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="343"/>
+ <location filename="../widget_simple.ui" line="471"/>
<source>&Add</source>
<translation>&Ajouter</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="346"/>
+ <location filename="../widget_simple.ui" line="474"/>
<source>Add files</source>
<translation>Ajouter des fichiers</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="355"/>
+ <location filename="../widget_simple.ui" line="483"/>
<source>&Up</source>
<translation>&Monter</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="367"/>
+ <location filename="../widget_simple.ui" line="495"/>
<source>&Down</source>
<translation>&Descendre</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="158"/>
- <location filename="../widget_simple.ui" line="334"/>
+ <location filename="../widget_simple.ui" line="124"/>
+ <location filename="../widget_simple.ui" line="462"/>
<source>Remove selected files</source>
<translation>Supprimer les fichiers sélectionnés</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="314"/>
+ <location filename="../widget_simple.ui" line="442"/>
<source>by name</source>
<translation>par nom</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="317"/>
+ <location filename="../widget_simple.ui" line="445"/>
<source>Sort files by name</source>
<translation>Trier les fichier par nom</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="322"/>
+ <location filename="../widget_simple.ui" line="450"/>
<source>by modification date</source>
<translation>par date de modification</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="201"/>
+ <location filename="../widget_simple.ui" line="167"/>
<source>Sort by</source>
<translation>Trier par</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="211"/>
- <location filename="../widget_simple.ui" line="358"/>
+ <location filename="../widget_simple.ui" line="177"/>
+ <location filename="../widget_simple.ui" line="486"/>
<source>Up selected files</source>
<translation>Monter les fichiers sélectionnés</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="228"/>
- <location filename="../widget_simple.ui" line="370"/>
+ <location filename="../widget_simple.ui" line="194"/>
+ <location filename="../widget_simple.ui" line="498"/>
<source>Down selected files</source>
<translation>Descendre les fichiers sélectionnés</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="249"/>
+ <location filename="../widget_simple.ui" line="377"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="284"/>
+ <location filename="../widget_simple.ui" line="412"/>
<source>Filters</source>
<translation>Filtres</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="297"/>
+ <location filename="../widget_simple.ui" line="425"/>
<source>Finalizers</source>
<translation>Finaliseurs</translation>
</message>
</context>
</TS>
|
Guid75/renamah
|
a95c4d10d5c7761bb06c0e8f2c7f5cc8af58bcc9
|
don't add files which are already in the model
|
diff --git a/renamah/file_model.cpp b/renamah/file_model.cpp
index 99e2c6b..8af5722 100644
--- a/renamah/file_model.cpp
+++ b/renamah/file_model.cpp
@@ -1,364 +1,365 @@
#include <QFileInfo>
#include <QPair>
#include <QIcon>
#include <QMimeData>
#include <QDateTime>
#include "filter_model.h"
#include "file_model.h"
FileModel *FileModel::_instance = 0;
FileModel &FileModel::instance()
{
if (!_instance)
_instance = new FileModel;
return *_instance;
}
int FileModel::rowCount(const QModelIndex &parent) const
{
return _originals.count();
}
int FileModel::columnCount(const QModelIndex &parent) const
{
return 2;
}
QVariant FileModel::data(const QModelIndex &index, int role) const
{
QString original = _originals[index.row()];
QFileInfo originalFileInfo(original);
QString renamed;
bool manual = false;
if (_manualMapping.find(original) != _manualMapping.end()) {
manual = true;
renamed = _manualMapping[original];
}
else if (_renamedMapping.find(original) != _renamedMapping.end())
renamed = _renamedMapping[original];
else
{
renamed = FilterModel::instance().apply(original, index.row());
const_cast<QMap<QString,QString> &>(_renamedMapping)[original] = renamed;
}
switch (role)
{
case Qt::DisplayRole:
switch (index.column())
{
case 0: return originalFileInfo.fileName();
case 1: return QFileInfo(renamed).fileName();
default:;
}
break;
case Qt::ForegroundRole:
switch (index.column())
{
case 1:
if (manual)
return Qt::red;
else if (renamed != original)
return Qt::blue;
break;
default:;
}
break;
case Qt::DecorationRole:
if (index.column() == 1) {
if (manual)
return QIcon(":/images/hand.png");
else if (renamed != original)
return QIcon(":/images/automatic.png");
else
return QIcon(":/images/blank.png");
}
default:;
}
return QVariant();
}
QVariant FileModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole)
switch (section)
{
case 0: return tr("Original");
case 1: return tr("Renamed");
default:;
}
return QVariant();
}
void FileModel::addFile(const QString &filePath)
{
- // TODO: check for already existing file
+ if (_originals.indexOf(filePath) >= 0)
+ return;
beginInsertRows(QModelIndex(), _originals.count(), _originals.count());
- _originals << filePath;
+ _originals << filePath;
endInsertRows();
invalidate();
}
bool FileModel::removeRows(int row, int count, const QModelIndex &parent)
{
if (row < 0 || row > rowCount() - 1 ||
row + count < 0 || row + count > rowCount())
return false;
beginRemoveRows(parent, row, row + count - 1);
while (count)
{
QString fileName = _originals[row];
_originals.removeAt(row);
_renamedMapping.remove(fileName);
_manualMapping.remove(fileName);
count--;
}
endRemoveRows();
invalidate();
}
void FileModel::invalidate() {
_renamedMapping.clear();
if (rowCount())
emit dataChanged(index(0, 1), index(rowCount() - 1, 1));
}
QString FileModel::originalFileName(const QModelIndex &index) const {
if (index.row() < 0 || index.row() >= rowCount())
return "";
return _originals[index.row()];
}
QString FileModel::renamedFileName(const QModelIndex &index) const {
if (index.row() < 0 || index.row() >= rowCount())
return "";
QString original = _originals[index.row()];
if (_manualMapping.find(original) != _manualMapping.end())
return _manualMapping[original];
else
return FilterModel::instance().apply(original, index.row());
}
void FileModel::setManualRenaming(const QModelIndex &index, const QString &renamedFileName) {
QString original = originalFileName(index);
if (original == "")
return;
_manualMapping[original] = renamedFileName;
_renamedMapping.remove(original);
emit dataChanged(this->index(index.row(), 0), this->index(index.row(), columnCount() - 1));
}
void FileModel::removeManualRenaming(const QModelIndex &index) {
QString original = originalFileName(index);
if (original == "")
return;
_manualMapping.remove(original);
_renamedMapping.remove(original);
emit dataChanged(this->index(index.row(), 0), this->index(index.row(), columnCount() - 1));
}
Qt::ItemFlags FileModel::flags(const QModelIndex &index) const {
Qt::ItemFlags flags = QAbstractListModel::flags(index);
if (index.isValid())
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | flags;
else
return Qt::ItemIsDropEnabled | flags;
}
Qt::DropActions FileModel::supportedDropActions() const {
return Qt::MoveAction;
}
#define MIMETYPE QLatin1String("file-rows")
QStringList FileModel::mimeTypes() const {
QStringList types;
types << MIMETYPE;
return types;
}
QMimeData *FileModel::mimeData(const QModelIndexList &indexes) const {
QMimeData *mimeData = new QMimeData;
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
QList<int> rowsToMove;
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
if (rowsToMove.indexOf(index.row()) < 0) {
rowsToMove << index.row();
stream << index.row();
}
}
}
mimeData->setData(MIMETYPE, encodedData);
return mimeData;
}
bool FileModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
if (action == Qt::IgnoreAction)
return false;
_dropRows.clear();
// Get the rows to move
QList<int> rowsToMove;
QByteArray inData = data->data(MIMETYPE);
QDataStream stream(inData);
while (!stream.atEnd()) {
int r;
stream >> r;
rowsToMove << r;
}
qSort(rowsToMove);
QStringList filesToMove;
int insertionIndex = row;
int parentInsertionIndex = parent.isValid() ? parent.row() : -1;
foreach (int rowIndex, rowsToMove) {
if (rowIndex < row)
insertionIndex--;
if (rowIndex < parent.row()) {
parentInsertionIndex--;
}
filesToMove << _originals[rowIndex];
}
for (int i = 0; i < rowsToMove.count(); ++i) {
_originals.removeAt(rowsToMove[i] - i);
}
if (insertionIndex != -1) {
if (insertionIndex >= rowCount()) {
foreach (const QString &fileName, filesToMove) {
_dropRows << _originals.count();
_originals << fileName;
}
} else {
int i = 0;
foreach (const QString &fileName, filesToMove) {
_dropRows << insertionIndex + i;
_originals.insert(insertionIndex + i, fileName);
i++;
}
}
} else if (parent.isValid()) {
if (parentInsertionIndex == parent.row()) {
int i = 0;
foreach (const QString &fileName, filesToMove) {
_dropRows << parentInsertionIndex + i;
_originals.insert(parentInsertionIndex + i, fileName);
i++;
}
} else {
int i = 0;
foreach (const QString &fileName, filesToMove) {
_dropRows << parentInsertionIndex + i + 1;
_originals.insert(parentInsertionIndex + i + 1, fileName);
i++;
}
}
} else if (!parent.isValid()) {
foreach (const QString &fileName, filesToMove) {
_dropRows << _originals.count();
_originals << fileName;
}
}
invalidate();
emit dropDone();
return false;
}
void FileModel::upRows(const QModelIndexList &indexes) {
if (!indexes.count())
return;
_dropRows.clear();
QList<int> rows;
foreach (const QModelIndex &index, indexes)
rows << index.row();
qSort(rows);
if (rows[0] <= 0)
return;
foreach (int row, rows) {
_originals.move(row, row - 1);
_dropRows << row - 1;
}
invalidate();
}
void FileModel::downRows(const QModelIndexList &indexes) {
if (!indexes.count())
return;
_dropRows.clear();
QList<int> rows;
foreach (const QModelIndex &index, indexes)
rows << index.row();
qSort(rows.begin(), rows.end(), qGreater<int>());
if (rows[0] >= _originals.count() - 1)
return;
foreach (int row, rows) {
_originals.move(row, row + 1);
_dropRows << row + 1;
}
invalidate();
}
bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
{
return s1.toLower() < s2.toLower();
}
bool modificationDateLessThan(const QString &fileName1, const QString &fileName2)
{
return QFileInfo(fileName1).lastModified() < QFileInfo(fileName2).lastModified();
}
void FileModel::sort(SortType sortType) {
switch (sortType) {
case SortByName:
qSort(_originals.begin(), _originals.end(), caseInsensitiveLessThan);
invalidate();
break;
case SortByModificationDate:
qSort(_originals.begin(), _originals.end(), modificationDateLessThan);
invalidate();
break;
default:;
}
}
|
Guid75/renamah
|
dc984a85cd61729677d7948bb0fb29bea6020d38
|
a label to add files when the file grid is empty (stacked widget involved)
|
diff --git a/renamah/widget_simple.cpp b/renamah/widget_simple.cpp
index 58b30de..fffe86f 100644
--- a/renamah/widget_simple.cpp
+++ b/renamah/widget_simple.cpp
@@ -1,280 +1,293 @@
#include <QFileDialog>
#include <QMessageBox>
#include <QHeaderView>
#include <QKeyEvent>
#include <QMouseEvent>
#include <interfaces/filter_factory.h>
#include "file_model.h"
#include "filter_model.h"
#include "filter_manager.h"
#include "processor.h"
#include "finalizer_model.h"
#include "action_manager.h"
#include "dialog_manual_rename.h"
#include "widget_simple.h"
WidgetSimple::WidgetSimple(QWidget *parent)
: uiRetranslating(false), QWidget(parent) {
setupUi(this);
menuSort = new QMenu(this);
pushButtonSort->setMenu(menuSort);
menuSort->addAction(actionSortByName);
menuSort->addAction(actionSortByModificationDate);
// Filters
widgetFilters->init(&FilterManager::instance(), FilterModel::instance());
connect(&FilterModel::instance(), SIGNAL(modifiersChanged()),
&FileModel::instance(), SLOT(invalidate()));
refreshFileCount();
// Finalizers
widgetFinalizers->init(&ActionManager::instance(), FinalizerModel::instance());
connect(&FinalizerModel::instance(), SIGNAL(modifiersChanged()),
&FileModel::instance(), SLOT(invalidate()));
// Files
treeViewFiles->setModel(&FileModel::instance());
treeViewFiles->header()->resizeSection(0, width() / 2);
connect(&FileModel::instance(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
this, SLOT(filesInserted(const QModelIndex &, int, int)));
connect(&FileModel::instance(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
this, SLOT(filesRemoved(const QModelIndex &, int, int)));
connect(&FileModel::instance(), SIGNAL(modelReset()),
this, SLOT(filesModelReset()));
connect(&FileModel::instance(), SIGNAL(dropDone()),
this, SLOT(filesDropDone()));
connect(treeViewFiles->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(treeViewFilesSelectionChanged(const QItemSelection &, const QItemSelection &)));
treeViewFiles->installEventFilter(this);
treeViewFiles->viewport()->installEventFilter(this);
+ labelAddFiles->installEventFilter(this);
+
on_comboBoxOperation_currentIndexChanged(0);
tabWidgetOperations->setCurrentWidget(tabFilters);
widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
connect(widgetExtensionPolicy, SIGNAL(extensionPolicyChanged()),
this, SLOT(generalExtensionPolicyChanged()));
QList<int> sizes;
sizes << 0 << 260;
splitter->setSizes(sizes);
}
void WidgetSimple::initAfterPluginLoaded() {
widgetFilters->addModifier("date");
widgetFilters->addModifier("cutter");
widgetFilters->addModifier("numbering");
// widgetFinalizers->addModifier("command");
// TEMP : Fill with some files
foreach (const QFileInfo &fileInfo, QDir::home().entryInfoList(QDir::Files))
FileModel::instance().addFile(fileInfo.absoluteFilePath());
+
+ if (FileModel::instance().rowCount())
+ stackedWidgetFiles->setCurrentWidget(pageFiles);
}
void WidgetSimple::on_pushButtonProcess_clicked() {
// Fill processor with tasks
Processor::instance().clearTasks();
for (int row = 0; row < FileModel::instance().rowCount(); ++row)
{
QString original = FileModel::instance().originalFileName(FileModel::instance().index(row, 0));
QString renamed = FilterModel::instance().apply(original, row);
if (renamed != original)
Processor::instance().addTask(original, FilterModel::instance().apply(original, row));
}
if (!Processor::instance().hasTasks() ||
QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to start the rename process?"),
QMessageBox::Yes | QMessageBox::Cancel) != QMessageBox::Yes)
return;
Processor::instance().go();
}
void WidgetSimple::on_comboBoxOperation_currentIndexChanged(int index) {
if (uiRetranslating)
return;
switch (index)
{
case 0:
lineEditDestination->setEnabled(false);
toolButtonDestination->setEnabled(false);
Processor::instance().setDestinationOperation(Processor::Rename);
break;
default:
lineEditDestination->setEnabled(true);
toolButtonDestination->setEnabled(true);
switch (index)
{
case 1:
Processor::instance().setDestinationOperation(Processor::Copy);
break;
case 2:
Processor::instance().setDestinationOperation(Processor::Move);
break;
case 3:
Processor::instance().setDestinationOperation(Processor::SymLink);
break;
default:;
}
if (lineEditDestination->text() == "")
on_toolButtonDestination_clicked();
}
}
void WidgetSimple::on_toolButtonDestination_clicked() {
QString dirName = "";
if (QDir(lineEditDestination->text()).exists())
dirName = lineEditDestination->text();
dirName = QFileDialog::getExistingDirectory(this, tr("Choose a destination directory"), dirName);
if (dirName == "")
return;
lineEditDestination->setText(dirName);
Processor::instance().setDestinationDir(dirName);
}
void WidgetSimple::refreshFileCount() {
labelFileCount->setText(tr("%n files", "", FileModel::instance().rowCount()));
}
void WidgetSimple::generalExtensionPolicyChanged() {
FilterModel::instance().setExtensionPolicy(widgetExtensionPolicy->extensionPolicy());
}
bool WidgetSimple::eventFilter(QObject *watched, QEvent *event) {
if (watched == treeViewFiles && event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Delete)
on_pushButtonRemoveFiles_clicked();
} else if (watched == treeViewFiles->viewport() && event->type() == QEvent::MouseButtonDblClick) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton)
modifyCurrentFileName();
+ } else if (watched == labelAddFiles && event->type() == QEvent::MouseButtonPress) {
+ actionAddFiles->trigger();
}
return QWidget::eventFilter(watched, event);
}
void WidgetSimple::modifyCurrentFileName() {
QModelIndex index = treeViewFiles->currentIndex();
if (!index.isValid())
return;
QDir dir = QFileInfo(FileModel::instance().originalFileName(index)).absoluteDir();
DialogManualRename dialog(this);
dialog.init(QFileInfo(FileModel::instance().originalFileName(index)).fileName(),
QFileInfo(FileModel::instance().renamedFileName(index)).fileName());
if (dialog.exec() != QDialog::Accepted)
return;
if (dialog.automaticRename())
FileModel::instance().removeManualRenaming(index);
else
FileModel::instance().setManualRenaming(index, dir.absoluteFilePath(dialog.fileName()));
}
void WidgetSimple::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
// Operation combobox
uiRetranslating = true;
int oldOperationCurrentIndex = comboBoxOperation->currentIndex();
retranslateUi(this);
comboBoxOperation->setCurrentIndex(oldOperationCurrentIndex);
uiRetranslating = false;
refreshFileCount();
} else
QWidget::changeEvent(event);
}
void WidgetSimple::newProfile() {
widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
widgetFilters->newProfile();
widgetFinalizers->newProfile();
}
void WidgetSimple::filesDropDone() {
int i = 0;
foreach (int row, FileModel::instance().dropRows()) {
QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select | QItemSelectionModel::Rows;
treeViewFiles->selectionModel()->select(FileModel::instance().index(row, 0), i ? flags : QItemSelectionModel::Clear | flags);
i++;
}
}
void WidgetSimple::on_actionSortByName_triggered() {
FileModel::instance().sort(FileModel::SortByName);
}
void WidgetSimple::on_actionSortByModificationDate_triggered() {
FileModel::instance().sort(FileModel::SortByModificationDate);
}
void WidgetSimple::on_actionRemoveSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (!list.count())
return;
if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this files?"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
QMap<int, int> rowsAndHeights;
foreach (const QItemSelectionRange &range, treeViewFiles->selectionModel()->selection())
rowsAndHeights.insert(range.top(), range.height());
QList<int> rows = rowsAndHeights.keys();
for (int i = rows.count() - 1; i >= 0; --i)
FileModel::instance().removeRows(rows[i], rowsAndHeights[rows[i]], QModelIndex());
+
+ if (!FileModel::instance().rowCount())
+ stackedWidgetFiles->setCurrentWidget(pageNoFiles);
}
void WidgetSimple::on_actionAddFiles_triggered() {
QStringList files = QFileDialog::getOpenFileNames(this, tr("Pick some files"),
QDir::home().absolutePath());
foreach (const QString &file, files)
FileModel::instance().addFile(file);
+
+ if (FileModel::instance().rowCount())
+ stackedWidgetFiles->setCurrentWidget(pageFiles);
}
void WidgetSimple::contextMenuEvent(QContextMenuEvent *event) {
QMenu popupMenu;
popupMenu.addAction(actionAddFiles);
if (treeViewFiles->selectionModel()->selectedRows().count()) {
popupMenu.addAction(actionRemoveSelectedFiles);
popupMenu.addSeparator();
popupMenu.addAction(actionUpSelectedFiles);
popupMenu.addAction(actionDownSelectedFiles);
}
popupMenu.exec(event->globalPos());
}
void WidgetSimple::treeViewFilesSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) {
pushButtonRemoveFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
pushButtonUpFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
pushButtonDownFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
}
void WidgetSimple::on_actionUpSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (list.count()) {
FileModel::instance().upRows(list);
filesDropDone();
}
}
void WidgetSimple::on_actionDownSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (list.count()) {
FileModel::instance().downRows(list);
filesDropDone();
}
}
diff --git a/renamah/widget_simple.ui b/renamah/widget_simple.ui
index e14b519..09f9e93 100644
--- a/renamah/widget_simple.ui
+++ b/renamah/widget_simple.ui
@@ -1,398 +1,526 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WidgetSimple</class>
<widget class="QWidget" name="WidgetSimple">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>676</width>
<height>571</height>
</rect>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QGridLayout" name="gridLayout_6">
<item row="0" column="0">
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QWidget" name="widgetFiles" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<layout class="QGridLayout" name="gridLayout_5">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0" colspan="3">
+ <item row="0" column="0" colspan="4">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButtonProcess">
<property name="text">
<string>Process</string>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/process.png</normaloff>:/images/process.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="comboBoxOperation">
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContents</enum>
</property>
<item>
<property name="text">
<string>Rename files</string>
</property>
</item>
<item>
<property name="text">
<string>Copy renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Move renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Create symbolic links in</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEditDestination">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="toolButtonDestination">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
- <item row="1" column="0" colspan="2">
+ <item row="1" column="0" colspan="3">
<widget class="QFrame" name="frameOperation">
<property name="frameShape">
<enum>QFrame::HLine</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
- <item row="2" column="0" rowspan="7">
- <widget class="QTreeView" name="treeViewFiles">
- <property name="acceptDrops">
- <bool>true</bool>
- </property>
- <property name="dragEnabled">
- <bool>true</bool>
- </property>
- <property name="dragDropMode">
- <enum>QAbstractItemView::InternalMove</enum>
- </property>
- <property name="alternatingRowColors">
- <bool>true</bool>
- </property>
- <property name="selectionMode">
- <enum>QAbstractItemView::ExtendedSelection</enum>
- </property>
- <property name="rootIsDecorated">
- <bool>false</bool>
- </property>
- <property name="itemsExpandable">
- <bool>false</bool>
- </property>
- <property name="animated">
- <bool>true</bool>
- </property>
- <property name="allColumnsShowFocus">
- <bool>true</bool>
- </property>
- <property name="expandsOnDoubleClick">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item row="2" column="1" colspan="2">
+ <item row="2" column="2" colspan="2">
<widget class="QPushButton" name="pushButtonAddFiles">
<property name="toolTip">
<string>Add some files...</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
</widget>
</item>
- <item row="3" column="1" colspan="2">
+ <item row="3" column="2" colspan="2">
<widget class="QPushButton" name="pushButtonRemoveFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
</widget>
</item>
- <item row="7" column="1" colspan="2">
+ <item row="6" column="2" colspan="2">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>258</height>
</size>
</property>
</spacer>
</item>
- <item row="8" column="1" colspan="2">
+ <item row="7" column="2" colspan="2">
<widget class="QLabel" name="labelFileCount">
<property name="frameShape">
<enum>QFrame::Panel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<property name="text">
<string notr="true">13 files</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
- <item row="4" column="1" colspan="2">
+ <item row="4" column="2" colspan="2">
<widget class="QPushButton" name="pushButtonSort">
<property name="text">
<string>Sort by</string>
</property>
</widget>
</item>
- <item row="5" column="1">
+ <item row="5" column="2">
<widget class="QPushButton" name="pushButtonUpFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Up selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
</widget>
</item>
- <item row="5" column="2">
+ <item row="5" column="3">
<widget class="QPushButton" name="pushButtonDownFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Down selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
</widget>
</item>
+ <item row="2" column="1" rowspan="6">
+ <widget class="QStackedWidget" name="stackedWidgetFiles">
+ <property name="currentIndex">
+ <number>1</number>
+ </property>
+ <widget class="QWidget" name="pageFiles">
+ <layout class="QGridLayout" name="gridLayout_7">
+ <property name="margin">
+ <number>0</number>
+ </property>
+ <item row="0" column="0">
+ <widget class="QTreeView" name="treeViewFiles">
+ <property name="acceptDrops">
+ <bool>true</bool>
+ </property>
+ <property name="dragEnabled">
+ <bool>true</bool>
+ </property>
+ <property name="dragDropMode">
+ <enum>QAbstractItemView::InternalMove</enum>
+ </property>
+ <property name="alternatingRowColors">
+ <bool>true</bool>
+ </property>
+ <property name="selectionMode">
+ <enum>QAbstractItemView::ExtendedSelection</enum>
+ </property>
+ <property name="rootIsDecorated">
+ <bool>false</bool>
+ </property>
+ <property name="itemsExpandable">
+ <bool>false</bool>
+ </property>
+ <property name="animated">
+ <bool>true</bool>
+ </property>
+ <property name="allColumnsShowFocus">
+ <bool>true</bool>
+ </property>
+ <property name="expandsOnDoubleClick">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="pageNoFiles">
+ <layout class="QGridLayout" name="gridLayout_8">
+ <item row="0" column="1">
+ <spacer name="verticalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>190</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="1" column="0">
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>200</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="labelAddFiles">
+ <property name="palette">
+ <palette>
+ <active>
+ <colorrole role="WindowText">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>0</red>
+ <green>0</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ </active>
+ <inactive>
+ <colorrole role="WindowText">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>0</red>
+ <green>0</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ </inactive>
+ <disabled>
+ <colorrole role="WindowText">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>151</red>
+ <green>150</green>
+ <blue>150</blue>
+ </color>
+ </brush>
+ </colorrole>
+ </disabled>
+ </palette>
+ </property>
+ <property name="font">
+ <font>
+ <underline>true</underline>
+ </font>
+ </property>
+ <property name="cursor">
+ <cursorShape>PointingHandCursor</cursorShape>
+ </property>
+ <property name="lineWidth">
+ <number>1</number>
+ </property>
+ <property name="text">
+ <string>Click to add some files</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="2">
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>200</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="2" column="1">
+ <spacer name="verticalSpacer_3">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>90</width>
+ <height>190</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
</layout>
</item>
</layout>
</widget>
<widget class="QTabWidget" name="tabWidgetOperations">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabExtensionPolicy">
<attribute name="title">
<string>Extension policy</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QScrollArea" name="scrollArea">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>652</width>
<height>57</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetExtensionPolicy" name="widgetExtensionPolicy" native="true"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabFilters">
<attribute name="title">
<string>Filters</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_4">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetFilters" name="widgetFilters" native="true"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabEnders">
<attribute name="title">
<string>Finalizers</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_18">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetActions" name="widgetFinalizers" native="true"/>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>
<action name="actionSortByName">
<property name="text">
<string>by name</string>
</property>
<property name="toolTip">
<string>Sort files by name</string>
</property>
</action>
<action name="actionSortByModificationDate">
<property name="text">
<string>by modification date</string>
</property>
</action>
<action name="actionRemoveSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
<property name="text">
<string>&Remove</string>
</property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
</action>
<action name="actionAddFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
<property name="text">
<string>&Add</string>
</property>
<property name="toolTip">
<string>Add files</string>
</property>
</action>
<action name="actionUpSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
<property name="text">
<string>&Up</string>
</property>
<property name="toolTip">
<string>Up selected files</string>
</property>
</action>
<action name="actionDownSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
<property name="text">
<string>&Down</string>
</property>
<property name="toolTip">
<string>Down selected files</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>WidgetExtensionPolicy</class>
<extends>QWidget</extends>
<header>widget_extension_policy.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetActions</class>
<extends>QWidget</extends>
<header>widget_actions.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetFilters</class>
<extends>QWidget</extends>
<header>widget_filters.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources>
<include location="renamah.qrc"/>
</resources>
<connections/>
</ui>
|
Guid75/renamah
|
75cef54cd7027c09528b8614571dff68423ed7ab
|
obsolete translations removed
|
diff --git a/plugins/casefilter/translations/libcasefilter_fr.ts b/plugins/casefilter/translations/libcasefilter_fr.ts
index ec354b9..b657cfd 100644
--- a/plugins/casefilter/translations/libcasefilter_fr.ts
+++ b/plugins/casefilter/translations/libcasefilter_fr.ts
@@ -1,104 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>CaseFilter</name>
<message>
<location filename="../case_filter.cpp" line="60"/>
<source>lower case</source>
<comment>case counts!</comment>
<translation>minuscule</translation>
</message>
<message>
<location filename="../case_filter.cpp" line="61"/>
<source>UPPER CASE</source>
<comment>case counts!</comment>
<translation>MAJUSCULE</translation>
</message>
<message>
<location filename="../case_filter.cpp" line="62"/>
<source>First letter in upcase</source>
<comment>case counts!</comment>
<translation>Première lettre en majuscule</translation>
</message>
<message>
<location filename="../case_filter.cpp" line="63"/>
<source>Words First Letter In Upcase</source>
<comment>case counts!</comment>
<translation>Première Lettre Des Mots En Majuscule</translation>
</message>
</context>
<context>
<name>CaseFilterFactory</name>
- <message>
- <source>Case filter</source>
- <translation type="obsolete">FIltre de casse</translation>
- </message>
<message>
<location filename="../case_filter_factory.cpp" line="12"/>
<source>Case</source>
<translation>Casse</translation>
</message>
<message>
<location filename="../case_filter_factory.cpp" line="13"/>
<source>Case manipulations in strings</source>
<translation>Manipulation de la casse dans les chaînes</translation>
</message>
</context>
<context>
<name>ConfigWidget</name>
<message>
<location filename="../config_widget.ui" line="20"/>
<source>Set strings in:</source>
<translation>Convertit les chaînes en :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="27"/>
<source>lower case</source>
<translation>minuscule</translation>
</message>
<message>
<location filename="../config_widget.ui" line="34"/>
<source>UPPER CASE</source>
<translation>MAJUSCULE</translation>
</message>
<message>
<location filename="../config_widget.ui" line="41"/>
<source>First letter in upper case</source>
<translation>Première lettre en majuscule</translation>
</message>
<message>
<location filename="../config_widget.ui" line="48"/>
<source>FIrst Words Letter In Upper Case</source>
<translation>Première Lettre Des Mots En Majuscule</translation>
</message>
<message>
<location filename="../config_widget.ui" line="55"/>
<source>Don't lower other chars</source>
<translation>Pas de conversion en minuscule des autres caractères</translation>
</message>
</context>
-<context>
- <name>QObject</name>
- <message>
- <source>lower case</source>
- <comment>case counts!</comment>
- <translation type="obsolete">minuscule</translation>
- </message>
- <message>
- <source>UPPER CASE</source>
- <comment>case counts!</comment>
- <translation type="obsolete">MAJUSCULE</translation>
- </message>
- <message>
- <source>First letter in upcase</source>
- <comment>case counts!</comment>
- <translation type="obsolete">Première lettre en majuscule</translation>
- </message>
- <message>
- <source>Words First Letter In Upcase</source>
- <comment>case counts!</comment>
- <translation type="obsolete">Première Lettre Des Mots En Majuscule</translation>
- </message>
-</context>
</TS>
diff --git a/plugins/commandaction/translations/libcommandaction_fr.ts b/plugins/commandaction/translations/libcommandaction_fr.ts
index bd1ec17..8c3142d 100644
--- a/plugins/commandaction/translations/libcommandaction_fr.ts
+++ b/plugins/commandaction/translations/libcommandaction_fr.ts
@@ -1,44 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>CommandActionFactory</name>
- <message>
- <source>Command action</source>
- <translation type="obsolete">Action commande</translation>
- </message>
<message>
<location filename="../command_action_factory.cpp" line="12"/>
<source>Command</source>
<translation>Commande</translation>
</message>
<message>
<location filename="../command_action_factory.cpp" line="13"/>
<source>Launch a system command for each treated file</source>
<translation>Lance une commande système sur chaque fichier traité</translation>
</message>
</context>
<context>
<name>ConfigWidget</name>
<message>
<location filename="../config_widget.ui" line="26"/>
<source>Execute:</source>
<translation>Exécute :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="36"/>
<source>Don't wait for the program execution end</source>
<translation>Ne pas attendre la fin de l'exécution du programme</translation>
</message>
<message>
<location filename="../config_widget.ui" line="43"/>
<source>Add</source>
<translation>Ajouter</translation>
</message>
<message>
<location filename="../config_widget.ui" line="50"/>
<source>Remove</source>
<translation>Supprimer</translation>
</message>
</context>
</TS>
diff --git a/plugins/cutterfilter/translations/libcutterfilter_fr.ts b/plugins/cutterfilter/translations/libcutterfilter_fr.ts
index 8ac9b86..dc34046 100644
--- a/plugins/cutterfilter/translations/libcutterfilter_fr.ts
+++ b/plugins/cutterfilter/translations/libcutterfilter_fr.ts
@@ -1,67 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>ConfigWidget</name>
<message>
<location filename="../config_widget.ui" line="22"/>
<source>Start marker:</source>
<translation>Marqueur de début :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="41"/>
<location filename="../config_widget.ui" line="86"/>
<source>Nth char</source>
<translation>ième caractère</translation>
</message>
<message>
<location filename="../config_widget.ui" line="52"/>
<location filename="../config_widget.ui" line="97"/>
<source>From the left</source>
<translation>En partant de la gauche</translation>
</message>
<message>
<location filename="../config_widget.ui" line="57"/>
<location filename="../config_widget.ui" line="102"/>
<source>From the right</source>
<translation>En partant de la droite</translation>
</message>
<message>
<location filename="../config_widget.ui" line="67"/>
<source>End marker:</source>
<translation>Marquer de fin :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="112"/>
<source>Operation:</source>
<translation>Opération :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="134"/>
<source>keep part</source>
<translation>Garder la partie</translation>
</message>
<message>
<location filename="../config_widget.ui" line="141"/>
<source>remove part</source>
<translation>Supprimer la partie</translation>
</message>
</context>
<context>
<name>CutterFilterFactory</name>
- <message>
- <source>Cutter filter</source>
- <translation type="obsolete">Filtre de coupure</translation>
- </message>
<message>
<location filename="../cutter_filter_factory.cpp" line="12"/>
<source>Cutter</source>
<translation>Coupure</translation>
</message>
<message>
<location filename="../cutter_filter_factory.cpp" line="13"/>
<source>Cut some parts of files</source>
<translation>Couper des parties des noms de fichiers</translation>
</message>
</context>
</TS>
diff --git a/plugins/numberingfilter/translations/libnumberingfilter_fr.ts b/plugins/numberingfilter/translations/libnumberingfilter_fr.ts
index bd12945..321445e 100644
--- a/plugins/numberingfilter/translations/libnumberingfilter_fr.ts
+++ b/plugins/numberingfilter/translations/libnumberingfilter_fr.ts
@@ -1,282 +1,278 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>ConfigWidget</name>
<message>
<location filename="../config_widget.ui" line="22"/>
<source>From:</source>
<translation>Ã partir de :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="43"/>
<source>With a step of:</source>
<translation>avec un pas de :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="61"/>
<source>Separator string:</source>
<translation>Séparateur :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="71"/>
<source>Type:</source>
<translation>Type :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="84"/>
<source>Numeric</source>
<translation>Numérique</translation>
</message>
<message>
<location filename="../config_widget.ui" line="89"/>
<source>Roman (Upper case)</source>
<translation>Romain (Majuscule)</translation>
</message>
<message>
<location filename="../config_widget.ui" line="94"/>
<source>Roman (Lower case)</source>
<translation>Romain (minuscule)</translation>
</message>
<message>
<location filename="../config_widget.ui" line="99"/>
<source>Alphabetic (Upper case)</source>
<translation>Alphabétique (Majuscule)</translation>
</message>
<message>
<location filename="../config_widget.ui" line="104"/>
<source>Alphabetic (Lower case)</source>
<translation>Alphabétique (Minuscule)</translation>
</message>
<message>
<location filename="../config_widget.ui" line="114"/>
<source>Base:</source>
<translation>Base :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="128"/>
<source>2 (Binary)</source>
<translation>2 (Binaire)</translation>
</message>
<message>
<location filename="../config_widget.ui" line="133"/>
<source>3</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="138"/>
<source>4</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="143"/>
<source>5</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="148"/>
<source>6</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="153"/>
<source>7</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="158"/>
<source>8 (Octal)</source>
<translation>8 (Octal)</translation>
</message>
<message>
<location filename="../config_widget.ui" line="163"/>
<source>9</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="168"/>
<source>10 (Decimal)</source>
<translation>10 (Décimal)</translation>
</message>
<message>
<location filename="../config_widget.ui" line="173"/>
<source>11</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="178"/>
<source>12</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="183"/>
<source>13</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="188"/>
<source>14</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="193"/>
<source>15</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="198"/>
<source>16 (Hexadecimal)</source>
<translation>16 (Hexadécimal)</translation>
</message>
<message>
<location filename="../config_widget.ui" line="203"/>
<source>17</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="208"/>
<source>18</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="213"/>
<source>19</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="218"/>
<source>20</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="223"/>
<source>21</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="228"/>
<source>22</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="233"/>
<source>23</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="238"/>
<source>24</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="243"/>
<source>25</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="248"/>
<source>26</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="253"/>
<source>27</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="258"/>
<source>28</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="263"/>
<source>29</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="268"/>
<source>30</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="273"/>
<source>31</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="278"/>
<source>32</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="283"/>
<source>33</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="288"/>
<source>34</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="293"/>
<source>35</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="298"/>
<source>36</source>
<translation></translation>
</message>
<message>
<location filename="../config_widget.ui" line="310"/>
<source>Padding:</source>
<translation>Remplissage :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="320"/>
<source>Position index:</source>
<translation>Position :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="339"/>
<source>Prefix</source>
<translation>Préfixe</translation>
</message>
<message>
<location filename="../config_widget.ui" line="346"/>
<source>Suffix</source>
<translation>Suffixe</translation>
</message>
<message>
<location filename="../config_widget.ui" line="353"/>
<source>Custom position:</source>
<translation>Position manuelle :</translation>
</message>
</context>
<context>
<name>NumberingFilter</name>
<message>
<location filename="../numbering_filter.cpp" line="52"/>
<source>Start: %1, Step: %2</source>
<translation>Début: %1, Pas: %2</translation>
</message>
</context>
<context>
<name>NumberingFilterFactory</name>
- <message>
- <source>Numbering filter</source>
- <translation type="obsolete">Filtre de numérotation</translation>
- </message>
<message>
<location filename="../numbering_filter_factory.cpp" line="12"/>
<source>Numbering</source>
<translation>Numérotation</translation>
</message>
<message>
<location filename="../numbering_filter_factory.cpp" line="13"/>
<source>Add a numbering to files</source>
<translation>Ajouter une numérotation aux fichiers</translation>
</message>
</context>
</TS>
diff --git a/plugins/replacefilter/translations/libreplacefilter_fr.ts b/plugins/replacefilter/translations/libreplacefilter_fr.ts
index 2fd6c56..a8285c9 100644
--- a/plugins/replacefilter/translations/libreplacefilter_fr.ts
+++ b/plugins/replacefilter/translations/libreplacefilter_fr.ts
@@ -1,59 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>ConfigWidget</name>
<message>
<location filename="../config_widget.ui" line="22"/>
<source>Replace:</source>
<translation>Remplacer :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="36"/>
<source>by:</source>
<translation>par :</translation>
</message>
<message>
<location filename="../config_widget.ui" line="62"/>
<source>Fixed string</source>
<translation>Chaîne fixe</translation>
</message>
<message>
<location filename="../config_widget.ui" line="69"/>
<source>Regular expressions</source>
<translation>Expression régulière</translation>
</message>
<message>
<location filename="../config_widget.ui" line="76"/>
<source>Wildcard</source>
<translation>Wildcard</translation>
</message>
<message>
<location filename="../config_widget.ui" line="86"/>
<source>Case sensitive</source>
<translation>Sensible à la casse</translation>
</message>
<message>
<location filename="../config_widget.ui" line="93"/>
<source>Pattern syntax:</source>
<translation>Syntaxe du motif :</translation>
</message>
</context>
<context>
<name>ReplaceFilterFactory</name>
- <message>
- <source>Replace filter</source>
- <translation type="obsolete">Filtre de remplacement</translation>
- </message>
<message>
<location filename="../replace_filter_factory.cpp" line="12"/>
<source>Replacement</source>
<translation>Remplacement</translation>
</message>
<message>
<location filename="../replace_filter_factory.cpp" line="13"/>
<source>Replace pieces in strings</source>
<translation>Remplace des morceaux dans les chaînes</translation>
</message>
</context>
</TS>
|
Guid75/renamah
|
971997adb4e1d4e146b171f5b174027b200642f1
|
layout problem FIXED
|
diff --git a/renamah/widget_simple.ui b/renamah/widget_simple.ui
index da82f5e..e14b519 100644
--- a/renamah/widget_simple.ui
+++ b/renamah/widget_simple.ui
@@ -1,398 +1,398 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WidgetSimple</class>
<widget class="QWidget" name="WidgetSimple">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>676</width>
<height>571</height>
</rect>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QGridLayout" name="gridLayout_6">
<item row="0" column="0">
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QWidget" name="widgetFiles" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<layout class="QGridLayout" name="gridLayout_5">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0" colspan="2">
+ <item row="0" column="0" colspan="3">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButtonProcess">
<property name="text">
<string>Process</string>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/process.png</normaloff>:/images/process.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="comboBoxOperation">
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContents</enum>
</property>
<item>
<property name="text">
<string>Rename files</string>
</property>
</item>
<item>
<property name="text">
<string>Copy renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Move renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Create symbolic links in</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEditDestination">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="toolButtonDestination">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0" colspan="2">
<widget class="QFrame" name="frameOperation">
<property name="frameShape">
<enum>QFrame::HLine</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item row="2" column="0" rowspan="7">
<widget class="QTreeView" name="treeViewFiles">
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragEnabled">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::InternalMove</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="animated">
<bool>true</bool>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
</widget>
</item>
<item row="2" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonAddFiles">
<property name="toolTip">
<string>Add some files...</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
</widget>
</item>
<item row="3" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonRemoveFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
</widget>
</item>
<item row="7" column="1" colspan="2">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>258</height>
</size>
</property>
</spacer>
</item>
<item row="8" column="1" colspan="2">
<widget class="QLabel" name="labelFileCount">
<property name="frameShape">
<enum>QFrame::Panel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<property name="text">
<string notr="true">13 files</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="4" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonSort">
<property name="text">
<string>Sort by</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QPushButton" name="pushButtonUpFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Up selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
</widget>
</item>
<item row="5" column="2">
<widget class="QPushButton" name="pushButtonDownFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Down selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QTabWidget" name="tabWidgetOperations">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabExtensionPolicy">
<attribute name="title">
<string>Extension policy</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QScrollArea" name="scrollArea">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>652</width>
<height>57</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetExtensionPolicy" name="widgetExtensionPolicy" native="true"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabFilters">
<attribute name="title">
<string>Filters</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_4">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetFilters" name="widgetFilters" native="true"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabEnders">
<attribute name="title">
<string>Finalizers</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_18">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetActions" name="widgetFinalizers" native="true"/>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>
<action name="actionSortByName">
<property name="text">
<string>by name</string>
</property>
<property name="toolTip">
<string>Sort files by name</string>
</property>
</action>
<action name="actionSortByModificationDate">
<property name="text">
<string>by modification date</string>
</property>
</action>
<action name="actionRemoveSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
<property name="text">
<string>&Remove</string>
</property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
</action>
<action name="actionAddFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
<property name="text">
<string>&Add</string>
</property>
<property name="toolTip">
<string>Add files</string>
</property>
</action>
<action name="actionUpSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
<property name="text">
<string>&Up</string>
</property>
<property name="toolTip">
<string>Up selected files</string>
</property>
</action>
<action name="actionDownSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
<property name="text">
<string>&Down</string>
</property>
<property name="toolTip">
<string>Down selected files</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>WidgetExtensionPolicy</class>
<extends>QWidget</extends>
<header>widget_extension_policy.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetActions</class>
<extends>QWidget</extends>
<header>widget_actions.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetFilters</class>
<extends>QWidget</extends>
<header>widget_filters.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources>
<include location="renamah.qrc"/>
</resources>
<connections/>
</ui>
|
Guid75/renamah
|
1baccd420b979503ad9301d17a2119d7c0e6c613
|
new translation macro
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index f566aa8..25d0257 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,33 +1,48 @@
PROJECT(RENAMAH)
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)
FIND_PACKAGE(Qt4 REQUIRED)
include_directories(
${RENAMAH_BINARY_DIR}/libcore
)
option (UPDATE_TRANSLATIONS "Update source translation translations/*.ts files (WARNING: make clean will delete the source .ts files! Danger!)"
"off")
option (NO_OBSOLETE_TRANSLATIONS "Remove all obsolete translations in *.ts files. This options will work only when UPDATE_TRANSLATIONS i on"
"off")
+# Use: COMPUTE_QT_FILES(QM_FILES ${SOURCE_FILES} ${TRANSLATIONS_FILES})
+MACRO(COMPUTE_QM_FILES QM_FILES)
+ FILE (GLOB TRANSLATION_FILES translations/*.ts)
+
+ if (UPDATE_TRANSLATIONS)
+ if (NO_OBSOLETE_TRANSLATIONS)
+ QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES} OPTIONS -noobsolete)
+ else (NO_OBSOLETE_TRANSLATIONS)
+ QT4_CREATE_TRANSLATION(${QM_FILES} ${ARGN} ${TRANSLATION_FILES})
+ endif (NO_OBSOLETE_TRANSLATIONS)
+ else (UPDATE_TRANSLATIONS)
+ QT4_ADD_TRANSLATION(${QM_FILES} ${TRANSLATION_FILES})
+ endif (UPDATE_TRANSLATIONS)
+ENDMACRO(COMPUTE_QM_FILES)
+
ADD_SUBDIRECTORY(libcore)
ADD_SUBDIRECTORY(plugins)
ADD_SUBDIRECTORY(renamah)
# INSTALL(TARGETS renamah
# RUNTIME DESTINATION bin)
#INSTALL(DIRECTORY share/renamah
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
#INSTALL(DIRECTORY share/applications
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
#INSTALL(DIRECTORY share/pixmaps
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
diff --git a/plugins/casefilter/CMakeLists.txt b/plugins/casefilter/CMakeLists.txt
index e37e0bc..e7e914c 100644
--- a/plugins/casefilter/CMakeLists.txt
+++ b/plugins/casefilter/CMakeLists.txt
@@ -1,45 +1,39 @@
INCLUDE(${QT_USE_FILE})
SET(CASEFILTER_SOURCES
case_filter_factory.cpp
case_filter.cpp
config_widget.cpp
)
SET(CASEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CASEFILTER_FORMS_H ${CASEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CASEFILTER_MOCH
case_filter.h
case_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CASEFILTER_MOC ${CASEFILTER_MOCH})
# Translations rules
-FILE(GLOB TRANSLATIONS_FILES translations/*.ts)
-if (UPDATE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS} ${CASEFILTER_MOCH}
- ${TRANSLATIONS_FILES})
-else (UPDATE_TRANSLATIONS)
- QT4_ADD_TRANSLATION(QM_FILES ${TRANSLATIONS_FILES})
-endif (UPDATE_TRANSLATIONS)
+COMPUTE_QM_FILES(QM_FILES ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS} ${CASEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_casefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(casefilter SHARED ${CASEFILTER_SOURCES} ${CASEFILTER_FORMS_H} ${CASEFILTER_MOC})
ADD_DEPENDENCIES(casefilter translations_casefilter)
diff --git a/plugins/commandaction/CMakeLists.txt b/plugins/commandaction/CMakeLists.txt
index 7109078..addbc40 100644
--- a/plugins/commandaction/CMakeLists.txt
+++ b/plugins/commandaction/CMakeLists.txt
@@ -1,53 +1,47 @@
INCLUDE(${QT_USE_FILE})
SET(COMMANDACTION_SOURCES
command_action_factory.cpp
command_action.cpp
config_widget.cpp
process_handler.cpp
)
SET(COMMANDACTION_FORMS
config_widget.ui
)
QT4_WRAP_UI(COMMANDACTION_FORMS_H ${COMMANDACTION_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(COMMANDACTION_MOCH
command_action.h
command_action_factory.h
config_widget.h
process_handler.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(COMMANDACTION_MOC ${COMMANDACTION_MOCH})
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
IF(WIN32)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ENDIF(WIN32)
# Translations rules
-FILE(GLOB TRANSLATIONS_FILES translations/*.ts)
-if (UPDATE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS} ${COMMANDACTION_MOCH}
- ${TRANSLATIONS_FILES})
-else (UPDATE_TRANSLATIONS)
- QT4_ADD_TRANSLATION(QM_FILES ${TRANSLATIONS_FILES})
-endif (UPDATE_TRANSLATIONS)
+COMPUTE_QM_FILES(QM_FILES ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS} ${COMMANDACTION_MOCH})
ADD_CUSTOM_TARGET(translations_commandaction DEPENDS ${QM_FILES})
IF(WIN32)
ADD_LIBRARY(commandaction WIN32 ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
ELSE(WIN32)
ADD_LIBRARY(commandaction SHARED ${COMMANDACTION_SOURCES} ${COMMANDACTION_FORMS_H} ${COMMANDACTION_MOC})
ENDIF(WIN32)
ADD_DEPENDENCIES(commandaction translations_commandaction)
diff --git a/plugins/cutterfilter/CMakeLists.txt b/plugins/cutterfilter/CMakeLists.txt
index 2ea827c..90a32bd 100644
--- a/plugins/cutterfilter/CMakeLists.txt
+++ b/plugins/cutterfilter/CMakeLists.txt
@@ -1,46 +1,38 @@
INCLUDE(${QT_USE_FILE})
SET(CUTTERFILTER_SOURCES
cutter_filter_factory.cpp
cutter_filter.cpp
config_widget.cpp
)
SET(CUTTERFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(CUTTERFILTER_FORMS_H ${CUTTERFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(CUTTERFILTER_MOCH
cutter_filter.h
cutter_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(CUTTERFILTER_MOC ${CUTTERFILTER_MOCH})
# Translations rules
-FILE(GLOB TRANSLATIONS_FILES translations/*.ts)
-
-if (UPDATE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS} ${CUTTERFILTER_MOCH}
- ${TRANSLATIONS_FILES})
-else (UPDATE_TRANSLATIONS)
- QT4_ADD_TRANSLATION(QM_FILES ${TRANSLATIONS_FILES})
-endif (UPDATE_TRANSLATIONS)
-
+COMPUTE_QM_FILES(QM_FILES ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS} ${CUTTERFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_cutterfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(cutterfilter SHARED ${CUTTERFILTER_SOURCES} ${CUTTERFILTER_FORMS_H} ${CUTTERFILTER_MOC})
ADD_DEPENDENCIES(cutterfilter translations_cutterfilter)
diff --git a/plugins/datefilter/CMakeLists.txt b/plugins/datefilter/CMakeLists.txt
index cce1293..6211874 100644
--- a/plugins/datefilter/CMakeLists.txt
+++ b/plugins/datefilter/CMakeLists.txt
@@ -1,47 +1,40 @@
INCLUDE(${QT_USE_FILE})
SET(DATEFILTER_SOURCES
date_filter_factory.cpp
date_filter.cpp
config_widget.cpp
)
SET(DATEFILTER_FORMS
config_widget.ui
help_widget.ui
)
QT4_WRAP_UI(DATEFILTER_FORMS_H ${DATEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(DATEFILTER_MOCH
date_filter.h
date_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(DATEFILTER_MOC ${DATEFILTER_MOCH})
# Translations rules
-FILE(GLOB TRANSLATIONS_FILES translations/*.ts)
-
-if (UPDATE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS} ${DATEFILTER_MOCH}
- ${TRANSLATIONS_FILES})
-else (UPDATE_TRANSLATIONS)
- QT4_ADD_TRANSLATION(QM_FILES ${TRANSLATIONS_FILES})
-endif (UPDATE_TRANSLATIONS)
+COMPUTE_QM_FILES(QM_FILES ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS} ${DATEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_datefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(datefilter SHARED ${DATEFILTER_SOURCES} ${DATEFILTER_FORMS_H} ${DATEFILTER_MOC})
ADD_DEPENDENCIES(datefilter translations_datefilter)
diff --git a/plugins/numberingfilter/CMakeLists.txt b/plugins/numberingfilter/CMakeLists.txt
index 83080f4..d4fee17 100644
--- a/plugins/numberingfilter/CMakeLists.txt
+++ b/plugins/numberingfilter/CMakeLists.txt
@@ -1,44 +1,38 @@
INCLUDE(${QT_USE_FILE})
SET(NUMBERINGFILTER_SOURCES
numbering_filter_factory.cpp
numbering_filter.cpp
config_widget.cpp
)
SET(NUMBERINGFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(NUMBERINGFILTER_FORMS_H ${NUMBERINGFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(NUMBERINGFILTER_MOCH
numbering_filter.h
numbering_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(NUMBERINGFILTER_MOC ${NUMBERINGFILTER_MOCH})
# Translations rules
-FILE(GLOB TRANSLATIONS_FILES translations/*.ts)
-if (UPDATE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS} ${NUMBERINGFILTER_MOCH}
- ${TRANSLATIONS_FILES})
-else (UPDATE_TRANSLATIONS)
- QT4_ADD_TRANSLATION(QM_FILES ${TRANSLATIONS_FILES})
-endif (UPDATE_TRANSLATIONS)
+COMPUTE_QM_FILES(QM_FILES ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS} ${NUMBERINGFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_numberingfilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(numberingfilter SHARED ${NUMBERINGFILTER_SOURCES} ${NUMBERINGFILTER_FORMS_H} ${NUMBERINGFILTER_MOC})
ADD_DEPENDENCIES(numberingfilter translations_numberingfilter)
diff --git a/plugins/replacefilter/CMakeLists.txt b/plugins/replacefilter/CMakeLists.txt
index 9b545cb..a5f40ec 100644
--- a/plugins/replacefilter/CMakeLists.txt
+++ b/plugins/replacefilter/CMakeLists.txt
@@ -1,44 +1,38 @@
INCLUDE(${QT_USE_FILE})
SET(REPLACEFILTER_SOURCES
replace_filter_factory.cpp
replace_filter.cpp
config_widget.cpp
)
SET(REPLACEFILTER_FORMS
config_widget.ui
)
QT4_WRAP_UI(REPLACEFILTER_FORMS_H ${REPLACEFILTER_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
SET(REPLACEFILTER_MOCH
replace_filter.h
replace_filter_factory.h
config_widget.h
)
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(REPLACEFILTER_MOC ${REPLACEFILTER_MOCH})
# Translations rules
-FILE(GLOB TRANSLATIONS_FILES translations/*.ts)
-if (UPDATE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS} ${REPLACEFILTER_MOCH}
- ${TRANSLATIONS_FILES})
-else (UPDATE_TRANSLATIONS)
- QT4_ADD_TRANSLATION(QM_FILES ${TRANSLATIONS_FILES})
-endif (UPDATE_TRANSLATIONS)
+COMPUTE_QM_FILES(QM_FILES ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS} ${REPLACEFILTER_MOCH})
ADD_CUSTOM_TARGET(translations_replacefilter DEPENDS ${QM_FILES})
# Destination
SET(LIBRARY_OUTPUT_PATH ${RENAMAH_BINARY_DIR}/bin/plugins)
ADD_LIBRARY(replacefilter SHARED ${REPLACEFILTER_SOURCES} ${REPLACEFILTER_FORMS_H} ${REPLACEFILTER_MOC})
ADD_DEPENDENCIES(replacefilter translations_replacefilter)
diff --git a/renamah/CMakeLists.txt b/renamah/CMakeLists.txt
index 2a9aea5..f4d0f77 100644
--- a/renamah/CMakeLists.txt
+++ b/renamah/CMakeLists.txt
@@ -1,104 +1,92 @@
SET(QT_USE_QTXML TRUE)
# SET(QT_USE_QTNETWORK TRUE)
INCLUDE(${QT_USE_FILE})
SET(RENAMAH_SOURCES
main.cpp
main_window.cpp
form_twinning.cpp
simple_dir_model.cpp
twinning_widget.cpp
widget_simple.cpp
file_model.cpp
filter_model.cpp
filter_manager.cpp
plugin_manager.cpp
form_last_operations.cpp
task_manager.cpp
modifier_delegate.cpp
led_widget.cpp
processor.cpp
widget_modifiers.cpp
modifier_manager.cpp
modifier_model.cpp
finalizer_model.cpp
action_manager.cpp
widget_extension_policy.cpp
extension_policy.cpp
widget_filters.cpp
widget_actions.cpp
dialog_manual_rename.cpp
profile.cpp
)
SET(RENAMAH_FORMS
main_window.ui
form_twinning.ui
widget_simple.ui
form_last_operations.ui
widget_modifiers.ui
widget_extension_policy.ui
dialog_manual_rename.ui
)
QT4_WRAP_UI(RENAMAH_FORMS_H ${RENAMAH_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/staticlibs)
SET(RENAMAH_MOCH
main_window.h
form_twinning.h
simple_dir_model.h
twinning_widget.h
widget_simple.h
file_model.h
filter_model.h
form_last_operations.h
modifier_delegate.h
led_widget.h
processor.h
widget_modifiers.h
modifier_model.h
finalizer_model.h
widget_extension_policy.h
widget_filters.h
widget_actions.h
dialog_manual_rename.h
)
-FILE (GLOB TRANSLATIONS_FILES translations/*.ts)
-
-if (UPDATE_TRANSLATIONS)
- if (NO_OBSOLETE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH}
- ${TRANSLATIONS_FILES} OPTIONS -noobsolete)
- else (NO_OBSOLETE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH}
- ${TRANSLATIONS_FILES})
- endif (NO_OBSOLETE_TRANSLATIONS)
-else (UPDATE_TRANSLATIONS)
- QT4_ADD_TRANSLATION(QM_FILES ${TRANSLATIONS_FILES})
-endif (UPDATE_TRANSLATIONS)
-
+# Translations stuff
+COMPUTE_QM_FILES(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH})
ADD_CUSTOM_TARGET(translations_renamah DEPENDS ${QM_FILES})
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(RENAMAH_MOC ${RENAMAH_MOCH})
QT4_ADD_RESOURCES(RENAMAH_RES renamah.qrc)
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
ADD_EXECUTABLE(renamah ${RENAMAH_SOURCES} ${RENAMAH_FORMS_H} ${RENAMAH_MOC} ${RENAMAH_RES})
ADD_DEPENDENCIES(renamah translations_renamah)
TARGET_LINK_LIBRARIES(
renamah core ${QT_LIBRARIES}
)
|
Guid75/renamah
|
294763decdb7103b050962ce0c646e90f989e48c
|
Removed obsolete translations
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 38e6b4d..f566aa8 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,31 +1,33 @@
PROJECT(RENAMAH)
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0)
FIND_PACKAGE(Qt4 REQUIRED)
include_directories(
${RENAMAH_BINARY_DIR}/libcore
)
option (UPDATE_TRANSLATIONS "Update source translation translations/*.ts files (WARNING: make clean will delete the source .ts files! Danger!)"
"off")
+option (NO_OBSOLETE_TRANSLATIONS "Remove all obsolete translations in *.ts files. This options will work only when UPDATE_TRANSLATIONS i on"
+ "off")
ADD_SUBDIRECTORY(libcore)
ADD_SUBDIRECTORY(plugins)
ADD_SUBDIRECTORY(renamah)
# INSTALL(TARGETS renamah
# RUNTIME DESTINATION bin)
#INSTALL(DIRECTORY share/renamah
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
#INSTALL(DIRECTORY share/applications
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
#INSTALL(DIRECTORY share/pixmaps
# DESTINATION share
# PATTERN .svn
# EXCLUDE)
diff --git a/renamah/CMakeLists.txt b/renamah/CMakeLists.txt
index 106f183..2a9aea5 100644
--- a/renamah/CMakeLists.txt
+++ b/renamah/CMakeLists.txt
@@ -1,99 +1,104 @@
SET(QT_USE_QTXML TRUE)
# SET(QT_USE_QTNETWORK TRUE)
INCLUDE(${QT_USE_FILE})
SET(RENAMAH_SOURCES
main.cpp
main_window.cpp
form_twinning.cpp
simple_dir_model.cpp
twinning_widget.cpp
widget_simple.cpp
file_model.cpp
filter_model.cpp
filter_manager.cpp
plugin_manager.cpp
form_last_operations.cpp
task_manager.cpp
modifier_delegate.cpp
led_widget.cpp
processor.cpp
widget_modifiers.cpp
modifier_manager.cpp
modifier_model.cpp
finalizer_model.cpp
action_manager.cpp
widget_extension_policy.cpp
extension_policy.cpp
widget_filters.cpp
widget_actions.cpp
dialog_manual_rename.cpp
profile.cpp
)
SET(RENAMAH_FORMS
main_window.ui
form_twinning.ui
widget_simple.ui
form_last_operations.ui
widget_modifiers.ui
widget_extension_policy.ui
dialog_manual_rename.ui
)
QT4_WRAP_UI(RENAMAH_FORMS_H ${RENAMAH_FORMS})
# Don't forget to include output directory, otherwise
# the UI file won't be wrapped!
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
# LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/staticlibs)
SET(RENAMAH_MOCH
main_window.h
form_twinning.h
simple_dir_model.h
twinning_widget.h
widget_simple.h
file_model.h
filter_model.h
form_last_operations.h
modifier_delegate.h
led_widget.h
processor.h
widget_modifiers.h
modifier_model.h
finalizer_model.h
widget_extension_policy.h
widget_filters.h
widget_actions.h
dialog_manual_rename.h
)
FILE (GLOB TRANSLATIONS_FILES translations/*.ts)
if (UPDATE_TRANSLATIONS)
- QT4_CREATE_TRANSLATION(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH}
- ${TRANSLATIONS_FILES})
+ if (NO_OBSOLETE_TRANSLATIONS)
+ QT4_CREATE_TRANSLATION(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH}
+ ${TRANSLATIONS_FILES} OPTIONS -noobsolete)
+ else (NO_OBSOLETE_TRANSLATIONS)
+ QT4_CREATE_TRANSLATION(QM_FILES ${RENAMAH_SOURCES} ${RENAMAH_FORMS} ${RENAMAH_MOCH}
+ ${TRANSLATIONS_FILES})
+ endif (NO_OBSOLETE_TRANSLATIONS)
else (UPDATE_TRANSLATIONS)
QT4_ADD_TRANSLATION(QM_FILES ${TRANSLATIONS_FILES})
endif (UPDATE_TRANSLATIONS)
ADD_CUSTOM_TARGET(translations_renamah DEPENDS ${QM_FILES})
ADD_DEFINITIONS(${QT_DEFINITIONS} -DQT_NO_DEBUG)
QT4_WRAP_CPP(RENAMAH_MOC ${RENAMAH_MOCH})
QT4_ADD_RESOURCES(RENAMAH_RES renamah.qrc)
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
ADD_EXECUTABLE(renamah ${RENAMAH_SOURCES} ${RENAMAH_FORMS_H} ${RENAMAH_MOC} ${RENAMAH_RES})
ADD_DEPENDENCIES(renamah translations_renamah)
TARGET_LINK_LIBRARIES(
renamah core ${QT_LIBRARIES}
)
diff --git a/renamah/translations/renamah_en_US.ts b/renamah/translations/renamah_en_US.ts
index 70e9491..93f8b69 100644
--- a/renamah/translations/renamah_en_US.ts
+++ b/renamah/translations/renamah_en_US.ts
@@ -1,424 +1,442 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
<name>DialogManualRename</name>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Do you really want to set the original filename?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
<location filename="../file_model.cpp" line="92"/>
<source>Original</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../file_model.cpp" line="93"/>
<source>Renamed</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
<location filename="../form_twinning.cpp" line="190"/>
<source>Choose a directory for left files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.cpp" line="201"/>
<source>Choose a directory for right files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="25"/>
<source>Simple</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="38"/>
<source>Last operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="64"/>
<source>&File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="73"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="83"/>
<source>&Quit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="88"/>
<source>Language</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="93"/>
<source>&Load profile...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="98"/>
<source>&Save profile...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.cpp" line="124"/>
<source>Choose a profile to load</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.cpp" line="136"/>
<source>Choose a profile filename to save in</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
<location filename="../modifier_model.cpp" line="54"/>
<source>#</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="55"/>
<source>Mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="56"/>
<source>Action</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
<location filename="../processor.cpp" line="127"/>
<source>Rename</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="128"/>
<source>Copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="129"/>
<source>Move</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="130"/>
<source>Create link</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
<location filename="../widget_filters.cpp" line="38"/>
<source>Override the global extension policy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="39"/>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="40"/>
<source>Extension policy</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
<location filename="../widget_modifiers.cpp" line="48"/>
<source>Add a new %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Confirmation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Do you really want to remove this filter?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
- <location filename="../widget_simple.cpp" line="78"/>
- <source>Pick a file</source>
- <translation type="unfinished"></translation>
- </message>
- <message>
- <location filename="../widget_simple.cpp" line="89"/>
+ <location filename="../widget_simple.cpp" line="226"/>
<source>Confirmation</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="89"/>
+ <location filename="../widget_simple.cpp" line="226"/>
<source>Do you really want to remove this files?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="115"/>
+ <location filename="../widget_simple.cpp" line="91"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="115"/>
+ <location filename="../widget_simple.cpp" line="91"/>
<source>Do you really want to start the rename process?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="159"/>
+ <location filename="../widget_simple.cpp" line="135"/>
<source>Choose a destination directory</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
- <location filename="../widget_simple.cpp" line="169"/>
+ <location filename="../widget_simple.cpp" line="145"/>
<source>%n files</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
+ <message>
+ <location filename="../widget_simple.cpp" line="241"/>
+ <source>Pick some files</source>
+ <translation type="unfinished"></translation>
+ </message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="141"/>
<source>Add some files...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="144"/>
- <source>Add...</source>
- <translation type="unfinished"></translation>
- </message>
- <message>
- <location filename="../widget_simple.ui" line="151"/>
+ <location filename="../widget_simple.ui" line="158"/>
+ <location filename="../widget_simple.ui" line="334"/>
<source>Remove selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="154"/>
- <source>Remove</source>
- <translation type="unfinished"></translation>
- </message>
- <message>
- <location filename="../widget_simple.ui" line="190"/>
+ <location filename="../widget_simple.ui" line="201"/>
<source>Sort by</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="197"/>
+ <location filename="../widget_simple.ui" line="211"/>
+ <location filename="../widget_simple.ui" line="358"/>
<source>Up selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="211"/>
+ <location filename="../widget_simple.ui" line="228"/>
+ <location filename="../widget_simple.ui" line="370"/>
<source>Down selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="232"/>
+ <location filename="../widget_simple.ui" line="249"/>
<source>Extension policy</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="267"/>
+ <location filename="../widget_simple.ui" line="284"/>
<source>Filters</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="280"/>
+ <location filename="../widget_simple.ui" line="297"/>
<source>Finalizers</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="297"/>
+ <location filename="../widget_simple.ui" line="314"/>
<source>by name</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="300"/>
+ <location filename="../widget_simple.ui" line="317"/>
<source>Sort files by name</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="305"/>
+ <location filename="../widget_simple.ui" line="322"/>
<source>by modification date</source>
<translation type="unfinished"></translation>
</message>
+ <message>
+ <location filename="../widget_simple.ui" line="331"/>
+ <source>&Remove</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="343"/>
+ <source>&Add</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="346"/>
+ <source>Add files</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="355"/>
+ <source>&Up</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="367"/>
+ <source>&Down</source>
+ <translation type="unfinished"></translation>
+ </message>
</context>
</TS>
diff --git a/renamah/translations/renamah_fr.ts b/renamah/translations/renamah_fr.ts
index 3059299..1f590e7 100644
--- a/renamah/translations/renamah_fr.ts
+++ b/renamah/translations/renamah_fr.ts
@@ -1,446 +1,444 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>DialogManualRename</name>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Do you really want to set the original filename?</source>
<translatorcomment>bof</translatorcomment>
<translation>Ãtes-vous sûr de vouloir affecter le nom de fichier original ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation>Renommage manuel</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation>Retour au renommage automatique</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation>Valeur originale</translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
<location filename="../file_model.cpp" line="92"/>
<source>Original</source>
<translation>Original</translation>
</message>
<message>
<location filename="../file_model.cpp" line="93"/>
<source>Renamed</source>
<translation>Renommé</translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
<location filename="../form_twinning.cpp" line="190"/>
<source>Choose a directory for left files</source>
<translation>Choisissez un répertoire pour les fichiers de gauche</translation>
</message>
<message>
<location filename="../form_twinning.cpp" line="201"/>
<source>Choose a directory for right files</source>
<translation>Choisissez un répertoire pour les fichiers de droite</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
<translation>Extension :</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
<translation>*avi,*.mkv</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
<translation>Statut</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
<translation>lancer</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation></translation>
</message>
<message>
<location filename="../main_window.ui" line="25"/>
<source>Simple</source>
<translation>Simple</translation>
</message>
<message>
<location filename="../main_window.ui" line="38"/>
<source>Last operations</source>
<translation>Dernières opérations</translation>
</message>
<message>
<location filename="../main_window.ui" line="64"/>
<source>&File</source>
<translation>&Fichier</translation>
</message>
<message>
<location filename="../main_window.ui" line="73"/>
<source>Settings</source>
<translation>Paramètres</translation>
</message>
<message>
<location filename="../main_window.ui" line="83"/>
<source>&Quit</source>
<translation>&Quitter</translation>
</message>
<message>
<location filename="../main_window.ui" line="88"/>
<source>Language</source>
<translation>Langage</translation>
</message>
<message>
<location filename="../main_window.ui" line="93"/>
<source>&Load profile...</source>
<translation>&Charge un profile...</translation>
</message>
<message>
<location filename="../main_window.ui" line="98"/>
<source>&Save profile...</source>
<translation>&Sauver le profile...</translation>
</message>
- <message>
- <source>Save profile...</source>
- <translation type="obsolete">Sauve le profile...</translation>
- </message>
<message>
<location filename="../main_window.cpp" line="124"/>
<source>Choose a profile to load</source>
<translation>Choisissez un profile à charger</translation>
</message>
<message>
<location filename="../main_window.cpp" line="136"/>
<source>Choose a profile filename to save in</source>
<translation>Choisissez un nom de profile à sauver</translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
<location filename="../modifier_model.cpp" line="54"/>
<source>#</source>
<translation></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="55"/>
<source>Mode</source>
<translation>Mode</translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="56"/>
<source>Action</source>
<translation>Action</translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
<location filename="../processor.cpp" line="127"/>
<source>Rename</source>
<translation>Renommer</translation>
</message>
<message>
<location filename="../processor.cpp" line="128"/>
<source>Copy</source>
<translation>Copier</translation>
</message>
<message>
<location filename="../processor.cpp" line="129"/>
<source>Move</source>
<translation>Déplacer</translation>
</message>
<message>
<location filename="../processor.cpp" line="130"/>
<source>Create link</source>
<translation>Créer un lien</translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation>Souhaitez-vous vraiment revenir à la politique d'extension par défaut ?</translation>
</message>
- <message>
- <source>Do you really want to return to return to default extension policy settings?</source>
- <translation type="obsolete">Voulez-vous vraiment revenir à la politique d'extension par défaut ?</translation>
- </message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation>Choisissez quelle partie des fichiers vous voulez renommer :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation>Le nom de base (sans l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation>Le nom de fichier en entier (avec l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation>Seulement l'extension</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation>Paramètres par défaut</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation>L'extension du fichier commence juste après le :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation>Premier point en partant de la droite</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation>Premier point en partant de la gauche</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation>ième point en partant de la droite</translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
<location filename="../widget_filters.cpp" line="39"/>
<source>General</source>
<translation>Général</translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="40"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="38"/>
<source>Override the global extension policy</source>
<translation>Supplanter la politique d'extension globale</translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
<location filename="../widget_modifiers.cpp" line="48"/>
<source>Add a new %1</source>
<translation>Ajouter un nouveau %1</translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Confirmation</source>
<translation>Confirmation</translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Do you really want to remove this filter?</source>
<translation>Voulez-vous réellement supprimer ce filtre ?</translation>
</message>
- <message>
- <source>Title</source>
- <translation type="obsolete">Titre</translation>
- </message>
- <message>
- <source>Modifier description</source>
- <translation type="obsolete">Description du modificateur</translation>
- </message>
<message>
<location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation>Cliquez pour ajouter</translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
- <location filename="../widget_simple.cpp" line="78"/>
- <source>Pick a file</source>
- <translation>Choisissez un fichier</translation>
- </message>
- <message>
- <location filename="../widget_simple.cpp" line="89"/>
+ <location filename="../widget_simple.cpp" line="226"/>
<source>Confirmation</source>
<translation>Confirmation</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="89"/>
+ <location filename="../widget_simple.cpp" line="226"/>
<source>Do you really want to remove this files?</source>
<translation>Ãtes-vous certain de vouloir supprimer ces fichiers ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="115"/>
+ <location filename="../widget_simple.cpp" line="91"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="115"/>
+ <location filename="../widget_simple.cpp" line="91"/>
<source>Do you really want to start the rename process?</source>
<translation>Voulez-vous vraiment démarrer le processus de renommage ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="159"/>
+ <location filename="../widget_simple.cpp" line="135"/>
<source>Choose a destination directory</source>
<translation>Choisissez un répertoire de destination</translation>
</message>
<message numerus="yes">
- <location filename="../widget_simple.cpp" line="169"/>
+ <location filename="../widget_simple.cpp" line="145"/>
<source>%n files</source>
<translation>
<numerusform>%n fichier</numerusform>
<numerusform>%n fichiers</numerusform>
</translation>
</message>
+ <message>
+ <location filename="../widget_simple.cpp" line="241"/>
+ <source>Pick some files</source>
+ <translation>Choisissez des fichiers</translation>
+ </message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation>Lancer</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation>Renommage de fichier</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation>Copie renommée dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation>Déplacement renommé dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation>Création des liens dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
<translation></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="141"/>
<source>Add some files...</source>
<translation>Ajouter des fichiers...</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="144"/>
- <source>Add...</source>
- <translation>Ajouter...</translation>
+ <location filename="../widget_simple.ui" line="331"/>
+ <source>&Remove</source>
+ <translation>&Supprimer</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="343"/>
+ <source>&Add</source>
+ <translation>&Ajouter</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="151"/>
+ <location filename="../widget_simple.ui" line="346"/>
+ <source>Add files</source>
+ <translation>Ajouter des fichiers</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="355"/>
+ <source>&Up</source>
+ <translation>&Monter</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="367"/>
+ <source>&Down</source>
+ <translation>&Descendre</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="158"/>
+ <location filename="../widget_simple.ui" line="334"/>
<source>Remove selected files</source>
<translation>Supprimer les fichiers sélectionnés</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="297"/>
+ <location filename="../widget_simple.ui" line="314"/>
<source>by name</source>
<translation>par nom</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="300"/>
+ <location filename="../widget_simple.ui" line="317"/>
<source>Sort files by name</source>
<translation>Trier les fichier par nom</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="305"/>
+ <location filename="../widget_simple.ui" line="322"/>
<source>by modification date</source>
<translation>par date de modification</translation>
</message>
<message>
- <source>Add files...</source>
- <translation type="obsolete">Ajouter des fichiers...</translation>
- </message>
- <message>
- <location filename="../widget_simple.ui" line="154"/>
- <source>Remove</source>
- <translation>Supprimer</translation>
- </message>
- <message>
- <location filename="../widget_simple.ui" line="190"/>
+ <location filename="../widget_simple.ui" line="201"/>
<source>Sort by</source>
<translation>Trier par</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="197"/>
+ <location filename="../widget_simple.ui" line="211"/>
+ <location filename="../widget_simple.ui" line="358"/>
<source>Up selected files</source>
<translation>Monter les fichiers sélectionnés</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="211"/>
+ <location filename="../widget_simple.ui" line="228"/>
+ <location filename="../widget_simple.ui" line="370"/>
<source>Down selected files</source>
<translation>Descendre les fichiers sélectionnés</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="232"/>
+ <location filename="../widget_simple.ui" line="249"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="267"/>
+ <location filename="../widget_simple.ui" line="284"/>
<source>Filters</source>
<translation>Filtres</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="280"/>
+ <location filename="../widget_simple.ui" line="297"/>
<source>Finalizers</source>
<translation>Finaliseurs</translation>
</message>
</context>
</TS>
|
Guid75/renamah
|
1f81c76e24cc11fe2d3f8e371564839deac45402
|
Up & Down buttons are disabled when no files selection
|
diff --git a/renamah/widget_simple.cpp b/renamah/widget_simple.cpp
index 30b1ca5..58b30de 100644
--- a/renamah/widget_simple.cpp
+++ b/renamah/widget_simple.cpp
@@ -1,278 +1,280 @@
#include <QFileDialog>
#include <QMessageBox>
#include <QHeaderView>
#include <QKeyEvent>
#include <QMouseEvent>
#include <interfaces/filter_factory.h>
#include "file_model.h"
#include "filter_model.h"
#include "filter_manager.h"
#include "processor.h"
#include "finalizer_model.h"
#include "action_manager.h"
#include "dialog_manual_rename.h"
#include "widget_simple.h"
WidgetSimple::WidgetSimple(QWidget *parent)
: uiRetranslating(false), QWidget(parent) {
setupUi(this);
menuSort = new QMenu(this);
pushButtonSort->setMenu(menuSort);
menuSort->addAction(actionSortByName);
menuSort->addAction(actionSortByModificationDate);
// Filters
widgetFilters->init(&FilterManager::instance(), FilterModel::instance());
connect(&FilterModel::instance(), SIGNAL(modifiersChanged()),
&FileModel::instance(), SLOT(invalidate()));
refreshFileCount();
// Finalizers
widgetFinalizers->init(&ActionManager::instance(), FinalizerModel::instance());
connect(&FinalizerModel::instance(), SIGNAL(modifiersChanged()),
&FileModel::instance(), SLOT(invalidate()));
// Files
treeViewFiles->setModel(&FileModel::instance());
treeViewFiles->header()->resizeSection(0, width() / 2);
connect(&FileModel::instance(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
this, SLOT(filesInserted(const QModelIndex &, int, int)));
connect(&FileModel::instance(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
this, SLOT(filesRemoved(const QModelIndex &, int, int)));
connect(&FileModel::instance(), SIGNAL(modelReset()),
this, SLOT(filesModelReset()));
connect(&FileModel::instance(), SIGNAL(dropDone()),
this, SLOT(filesDropDone()));
connect(treeViewFiles->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(treeViewFilesSelectionChanged(const QItemSelection &, const QItemSelection &)));
treeViewFiles->installEventFilter(this);
treeViewFiles->viewport()->installEventFilter(this);
on_comboBoxOperation_currentIndexChanged(0);
tabWidgetOperations->setCurrentWidget(tabFilters);
widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
connect(widgetExtensionPolicy, SIGNAL(extensionPolicyChanged()),
this, SLOT(generalExtensionPolicyChanged()));
QList<int> sizes;
sizes << 0 << 260;
splitter->setSizes(sizes);
}
void WidgetSimple::initAfterPluginLoaded() {
widgetFilters->addModifier("date");
widgetFilters->addModifier("cutter");
widgetFilters->addModifier("numbering");
// widgetFinalizers->addModifier("command");
// TEMP : Fill with some files
foreach (const QFileInfo &fileInfo, QDir::home().entryInfoList(QDir::Files))
FileModel::instance().addFile(fileInfo.absoluteFilePath());
}
void WidgetSimple::on_pushButtonProcess_clicked() {
// Fill processor with tasks
Processor::instance().clearTasks();
for (int row = 0; row < FileModel::instance().rowCount(); ++row)
{
QString original = FileModel::instance().originalFileName(FileModel::instance().index(row, 0));
QString renamed = FilterModel::instance().apply(original, row);
if (renamed != original)
Processor::instance().addTask(original, FilterModel::instance().apply(original, row));
}
if (!Processor::instance().hasTasks() ||
QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to start the rename process?"),
QMessageBox::Yes | QMessageBox::Cancel) != QMessageBox::Yes)
return;
Processor::instance().go();
}
void WidgetSimple::on_comboBoxOperation_currentIndexChanged(int index) {
if (uiRetranslating)
return;
switch (index)
{
case 0:
lineEditDestination->setEnabled(false);
toolButtonDestination->setEnabled(false);
Processor::instance().setDestinationOperation(Processor::Rename);
break;
default:
lineEditDestination->setEnabled(true);
toolButtonDestination->setEnabled(true);
switch (index)
{
case 1:
Processor::instance().setDestinationOperation(Processor::Copy);
break;
case 2:
Processor::instance().setDestinationOperation(Processor::Move);
break;
case 3:
Processor::instance().setDestinationOperation(Processor::SymLink);
break;
default:;
}
if (lineEditDestination->text() == "")
on_toolButtonDestination_clicked();
}
}
void WidgetSimple::on_toolButtonDestination_clicked() {
QString dirName = "";
if (QDir(lineEditDestination->text()).exists())
dirName = lineEditDestination->text();
dirName = QFileDialog::getExistingDirectory(this, tr("Choose a destination directory"), dirName);
if (dirName == "")
return;
lineEditDestination->setText(dirName);
Processor::instance().setDestinationDir(dirName);
}
void WidgetSimple::refreshFileCount() {
labelFileCount->setText(tr("%n files", "", FileModel::instance().rowCount()));
}
void WidgetSimple::generalExtensionPolicyChanged() {
FilterModel::instance().setExtensionPolicy(widgetExtensionPolicy->extensionPolicy());
}
bool WidgetSimple::eventFilter(QObject *watched, QEvent *event) {
if (watched == treeViewFiles && event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Delete)
on_pushButtonRemoveFiles_clicked();
} else if (watched == treeViewFiles->viewport() && event->type() == QEvent::MouseButtonDblClick) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton)
modifyCurrentFileName();
}
return QWidget::eventFilter(watched, event);
}
void WidgetSimple::modifyCurrentFileName() {
QModelIndex index = treeViewFiles->currentIndex();
if (!index.isValid())
return;
QDir dir = QFileInfo(FileModel::instance().originalFileName(index)).absoluteDir();
DialogManualRename dialog(this);
dialog.init(QFileInfo(FileModel::instance().originalFileName(index)).fileName(),
QFileInfo(FileModel::instance().renamedFileName(index)).fileName());
if (dialog.exec() != QDialog::Accepted)
return;
if (dialog.automaticRename())
FileModel::instance().removeManualRenaming(index);
else
FileModel::instance().setManualRenaming(index, dir.absoluteFilePath(dialog.fileName()));
}
void WidgetSimple::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
// Operation combobox
uiRetranslating = true;
int oldOperationCurrentIndex = comboBoxOperation->currentIndex();
retranslateUi(this);
comboBoxOperation->setCurrentIndex(oldOperationCurrentIndex);
uiRetranslating = false;
refreshFileCount();
} else
QWidget::changeEvent(event);
}
void WidgetSimple::newProfile() {
widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
widgetFilters->newProfile();
widgetFinalizers->newProfile();
}
void WidgetSimple::filesDropDone() {
int i = 0;
foreach (int row, FileModel::instance().dropRows()) {
QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select | QItemSelectionModel::Rows;
treeViewFiles->selectionModel()->select(FileModel::instance().index(row, 0), i ? flags : QItemSelectionModel::Clear | flags);
i++;
}
}
void WidgetSimple::on_actionSortByName_triggered() {
FileModel::instance().sort(FileModel::SortByName);
}
void WidgetSimple::on_actionSortByModificationDate_triggered() {
FileModel::instance().sort(FileModel::SortByModificationDate);
}
void WidgetSimple::on_actionRemoveSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (!list.count())
return;
if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this files?"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
QMap<int, int> rowsAndHeights;
foreach (const QItemSelectionRange &range, treeViewFiles->selectionModel()->selection())
rowsAndHeights.insert(range.top(), range.height());
QList<int> rows = rowsAndHeights.keys();
for (int i = rows.count() - 1; i >= 0; --i)
FileModel::instance().removeRows(rows[i], rowsAndHeights[rows[i]], QModelIndex());
}
void WidgetSimple::on_actionAddFiles_triggered() {
QStringList files = QFileDialog::getOpenFileNames(this, tr("Pick some files"),
QDir::home().absolutePath());
foreach (const QString &file, files)
FileModel::instance().addFile(file);
}
void WidgetSimple::contextMenuEvent(QContextMenuEvent *event) {
QMenu popupMenu;
popupMenu.addAction(actionAddFiles);
if (treeViewFiles->selectionModel()->selectedRows().count()) {
popupMenu.addAction(actionRemoveSelectedFiles);
popupMenu.addSeparator();
popupMenu.addAction(actionUpSelectedFiles);
popupMenu.addAction(actionDownSelectedFiles);
}
popupMenu.exec(event->globalPos());
}
void WidgetSimple::treeViewFilesSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) {
pushButtonRemoveFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
+ pushButtonUpFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
+ pushButtonDownFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
}
void WidgetSimple::on_actionUpSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (list.count()) {
FileModel::instance().upRows(list);
filesDropDone();
}
}
void WidgetSimple::on_actionDownSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (list.count()) {
FileModel::instance().downRows(list);
filesDropDone();
}
}
diff --git a/renamah/widget_simple.ui b/renamah/widget_simple.ui
index 33ecce5..da82f5e 100644
--- a/renamah/widget_simple.ui
+++ b/renamah/widget_simple.ui
@@ -1,392 +1,398 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WidgetSimple</class>
<widget class="QWidget" name="WidgetSimple">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>676</width>
<height>571</height>
</rect>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QGridLayout" name="gridLayout_6">
<item row="0" column="0">
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QWidget" name="widgetFiles" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<layout class="QGridLayout" name="gridLayout_5">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="2">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButtonProcess">
<property name="text">
<string>Process</string>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/process.png</normaloff>:/images/process.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="comboBoxOperation">
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContents</enum>
</property>
<item>
<property name="text">
<string>Rename files</string>
</property>
</item>
<item>
<property name="text">
<string>Copy renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Move renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Create symbolic links in</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEditDestination">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="toolButtonDestination">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0" colspan="2">
<widget class="QFrame" name="frameOperation">
<property name="frameShape">
<enum>QFrame::HLine</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item row="2" column="0" rowspan="7">
<widget class="QTreeView" name="treeViewFiles">
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragEnabled">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::InternalMove</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="animated">
<bool>true</bool>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
</widget>
</item>
<item row="2" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonAddFiles">
<property name="toolTip">
<string>Add some files...</string>
</property>
<property name="text">
- <string>Add</string>
+ <string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
</widget>
</item>
<item row="3" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonRemoveFiles">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
<property name="text">
- <string>Remove</string>
+ <string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
</widget>
</item>
<item row="7" column="1" colspan="2">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>258</height>
</size>
</property>
</spacer>
</item>
<item row="8" column="1" colspan="2">
<widget class="QLabel" name="labelFileCount">
<property name="frameShape">
<enum>QFrame::Panel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<property name="text">
<string notr="true">13 files</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="4" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonSort">
<property name="text">
<string>Sort by</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QPushButton" name="pushButtonUpFiles">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
<property name="toolTip">
<string>Up selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
</widget>
</item>
<item row="5" column="2">
<widget class="QPushButton" name="pushButtonDownFiles">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
<property name="toolTip">
<string>Down selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QTabWidget" name="tabWidgetOperations">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabExtensionPolicy">
<attribute name="title">
<string>Extension policy</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QScrollArea" name="scrollArea">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>652</width>
<height>57</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetExtensionPolicy" name="widgetExtensionPolicy" native="true"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabFilters">
<attribute name="title">
<string>Filters</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_4">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetFilters" name="widgetFilters" native="true"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabEnders">
<attribute name="title">
<string>Finalizers</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_18">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetActions" name="widgetFinalizers" native="true"/>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>
<action name="actionSortByName">
<property name="text">
<string>by name</string>
</property>
<property name="toolTip">
<string>Sort files by name</string>
</property>
</action>
<action name="actionSortByModificationDate">
<property name="text">
<string>by modification date</string>
</property>
</action>
<action name="actionRemoveSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
</property>
<property name="text">
<string>&Remove</string>
</property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
</action>
<action name="actionAddFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
<property name="text">
<string>&Add</string>
</property>
<property name="toolTip">
<string>Add files</string>
</property>
</action>
<action name="actionUpSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
<property name="text">
<string>&Up</string>
</property>
<property name="toolTip">
<string>Up selected files</string>
</property>
</action>
<action name="actionDownSelectedFiles">
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
<property name="text">
<string>&Down</string>
</property>
<property name="toolTip">
<string>Down selected files</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>WidgetExtensionPolicy</class>
<extends>QWidget</extends>
<header>widget_extension_policy.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetActions</class>
<extends>QWidget</extends>
<header>widget_actions.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetFilters</class>
<extends>QWidget</extends>
<header>widget_filters.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources>
<include location="renamah.qrc"/>
</resources>
<connections/>
</ui>
|
Guid75/renamah
|
94901ef8b143f59736309489ce949c2712ecaa45
|
added .gitignore
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f9922c8
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+*.qm
+ui_*
+moc_*
+*.cxx
+Makefile
+CMakeFiles
+*~
+CMakeCache.txt
+cmake_install.cmake
+/bin
|
Guid75/renamah
|
f90bc1914ca610c2e2b9d1d76dcca2abf4424345
|
contextual menu in file tree and icons in buttons/actions
|
diff --git a/renamah/widget_simple.cpp b/renamah/widget_simple.cpp
index 1242002..30b1ca5 100644
--- a/renamah/widget_simple.cpp
+++ b/renamah/widget_simple.cpp
@@ -1,259 +1,278 @@
#include <QFileDialog>
#include <QMessageBox>
#include <QHeaderView>
#include <QKeyEvent>
#include <QMouseEvent>
#include <interfaces/filter_factory.h>
#include "file_model.h"
#include "filter_model.h"
#include "filter_manager.h"
#include "processor.h"
#include "finalizer_model.h"
#include "action_manager.h"
#include "dialog_manual_rename.h"
#include "widget_simple.h"
WidgetSimple::WidgetSimple(QWidget *parent)
: uiRetranslating(false), QWidget(parent) {
setupUi(this);
menuSort = new QMenu(this);
pushButtonSort->setMenu(menuSort);
menuSort->addAction(actionSortByName);
menuSort->addAction(actionSortByModificationDate);
// Filters
widgetFilters->init(&FilterManager::instance(), FilterModel::instance());
connect(&FilterModel::instance(), SIGNAL(modifiersChanged()),
&FileModel::instance(), SLOT(invalidate()));
refreshFileCount();
// Finalizers
widgetFinalizers->init(&ActionManager::instance(), FinalizerModel::instance());
connect(&FinalizerModel::instance(), SIGNAL(modifiersChanged()),
&FileModel::instance(), SLOT(invalidate()));
// Files
treeViewFiles->setModel(&FileModel::instance());
treeViewFiles->header()->resizeSection(0, width() / 2);
connect(&FileModel::instance(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
this, SLOT(filesInserted(const QModelIndex &, int, int)));
connect(&FileModel::instance(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)),
this, SLOT(filesRemoved(const QModelIndex &, int, int)));
connect(&FileModel::instance(), SIGNAL(modelReset()),
this, SLOT(filesModelReset()));
connect(&FileModel::instance(), SIGNAL(dropDone()),
this, SLOT(filesDropDone()));
+ connect(treeViewFiles->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
+ this, SLOT(treeViewFilesSelectionChanged(const QItemSelection &, const QItemSelection &)));
treeViewFiles->installEventFilter(this);
treeViewFiles->viewport()->installEventFilter(this);
on_comboBoxOperation_currentIndexChanged(0);
tabWidgetOperations->setCurrentWidget(tabFilters);
widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
connect(widgetExtensionPolicy, SIGNAL(extensionPolicyChanged()),
this, SLOT(generalExtensionPolicyChanged()));
QList<int> sizes;
sizes << 0 << 260;
splitter->setSizes(sizes);
}
void WidgetSimple::initAfterPluginLoaded() {
widgetFilters->addModifier("date");
widgetFilters->addModifier("cutter");
widgetFilters->addModifier("numbering");
// widgetFinalizers->addModifier("command");
// TEMP : Fill with some files
foreach (const QFileInfo &fileInfo, QDir::home().entryInfoList(QDir::Files))
FileModel::instance().addFile(fileInfo.absoluteFilePath());
}
-void WidgetSimple::on_pushButtonAddFiles_clicked() {
- QStringList files = QFileDialog::getOpenFileNames(this, tr("Pick a file"),
- QDir::home().absolutePath());
- foreach (const QString &file, files)
- FileModel::instance().addFile(file);
-}
-
-void WidgetSimple::on_pushButtonRemoveFiles_clicked() {
- QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
- if (!list.count())
- return;
-
- if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this files?"),
- QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
- return;
-
- QMap<int, int> rowsAndHeights;
-
- foreach (const QItemSelectionRange &range, treeViewFiles->selectionModel()->selection())
- rowsAndHeights.insert(range.top(), range.height());
-
- QList<int> rows = rowsAndHeights.keys();
- for (int i = rows.count() - 1; i >= 0; --i)
- FileModel::instance().removeRows(rows[i], rowsAndHeights[rows[i]], QModelIndex());
-}
-
void WidgetSimple::on_pushButtonProcess_clicked() {
// Fill processor with tasks
Processor::instance().clearTasks();
for (int row = 0; row < FileModel::instance().rowCount(); ++row)
{
QString original = FileModel::instance().originalFileName(FileModel::instance().index(row, 0));
QString renamed = FilterModel::instance().apply(original, row);
if (renamed != original)
Processor::instance().addTask(original, FilterModel::instance().apply(original, row));
}
if (!Processor::instance().hasTasks() ||
QMessageBox::question(this, tr("Are you sure?"), tr("Do you really want to start the rename process?"),
QMessageBox::Yes | QMessageBox::Cancel) != QMessageBox::Yes)
return;
Processor::instance().go();
}
void WidgetSimple::on_comboBoxOperation_currentIndexChanged(int index) {
if (uiRetranslating)
return;
switch (index)
{
case 0:
lineEditDestination->setEnabled(false);
toolButtonDestination->setEnabled(false);
Processor::instance().setDestinationOperation(Processor::Rename);
break;
default:
lineEditDestination->setEnabled(true);
toolButtonDestination->setEnabled(true);
switch (index)
{
case 1:
Processor::instance().setDestinationOperation(Processor::Copy);
break;
case 2:
Processor::instance().setDestinationOperation(Processor::Move);
break;
case 3:
Processor::instance().setDestinationOperation(Processor::SymLink);
break;
default:;
}
if (lineEditDestination->text() == "")
on_toolButtonDestination_clicked();
}
}
void WidgetSimple::on_toolButtonDestination_clicked() {
QString dirName = "";
if (QDir(lineEditDestination->text()).exists())
dirName = lineEditDestination->text();
dirName = QFileDialog::getExistingDirectory(this, tr("Choose a destination directory"), dirName);
if (dirName == "")
return;
lineEditDestination->setText(dirName);
Processor::instance().setDestinationDir(dirName);
}
void WidgetSimple::refreshFileCount() {
labelFileCount->setText(tr("%n files", "", FileModel::instance().rowCount()));
}
void WidgetSimple::generalExtensionPolicyChanged() {
FilterModel::instance().setExtensionPolicy(widgetExtensionPolicy->extensionPolicy());
}
bool WidgetSimple::eventFilter(QObject *watched, QEvent *event) {
if (watched == treeViewFiles && event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Delete)
on_pushButtonRemoveFiles_clicked();
} else if (watched == treeViewFiles->viewport() && event->type() == QEvent::MouseButtonDblClick) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton)
modifyCurrentFileName();
}
return QWidget::eventFilter(watched, event);
}
void WidgetSimple::modifyCurrentFileName() {
QModelIndex index = treeViewFiles->currentIndex();
if (!index.isValid())
return;
QDir dir = QFileInfo(FileModel::instance().originalFileName(index)).absoluteDir();
DialogManualRename dialog(this);
dialog.init(QFileInfo(FileModel::instance().originalFileName(index)).fileName(),
QFileInfo(FileModel::instance().renamedFileName(index)).fileName());
if (dialog.exec() != QDialog::Accepted)
return;
if (dialog.automaticRename())
FileModel::instance().removeManualRenaming(index);
else
FileModel::instance().setManualRenaming(index, dir.absoluteFilePath(dialog.fileName()));
}
void WidgetSimple::changeEvent(QEvent *event) {
if (event->type() == QEvent::LanguageChange) {
// Operation combobox
uiRetranslating = true;
int oldOperationCurrentIndex = comboBoxOperation->currentIndex();
retranslateUi(this);
comboBoxOperation->setCurrentIndex(oldOperationCurrentIndex);
uiRetranslating = false;
refreshFileCount();
} else
QWidget::changeEvent(event);
}
void WidgetSimple::newProfile() {
widgetExtensionPolicy->setExtensionPolicy(FilterModel::instance().extensionPolicy());
widgetFilters->newProfile();
widgetFinalizers->newProfile();
}
void WidgetSimple::filesDropDone() {
int i = 0;
foreach (int row, FileModel::instance().dropRows()) {
QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select | QItemSelectionModel::Rows;
treeViewFiles->selectionModel()->select(FileModel::instance().index(row, 0), i ? flags : QItemSelectionModel::Clear | flags);
i++;
}
}
-void WidgetSimple::on_pushButtonUpFiles_clicked() {
+void WidgetSimple::on_actionSortByName_triggered() {
+ FileModel::instance().sort(FileModel::SortByName);
+}
+
+void WidgetSimple::on_actionSortByModificationDate_triggered() {
+ FileModel::instance().sort(FileModel::SortByModificationDate);
+}
+
+void WidgetSimple::on_actionRemoveSelectedFiles_triggered() {
+ QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
+ if (!list.count())
+ return;
+
+ if (QMessageBox::question(this, tr("Confirmation"), tr("Do you really want to remove this files?"),
+ QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
+ return;
+
+ QMap<int, int> rowsAndHeights;
+
+ foreach (const QItemSelectionRange &range, treeViewFiles->selectionModel()->selection())
+ rowsAndHeights.insert(range.top(), range.height());
+
+ QList<int> rows = rowsAndHeights.keys();
+ for (int i = rows.count() - 1; i >= 0; --i)
+ FileModel::instance().removeRows(rows[i], rowsAndHeights[rows[i]], QModelIndex());
+}
+
+void WidgetSimple::on_actionAddFiles_triggered() {
+ QStringList files = QFileDialog::getOpenFileNames(this, tr("Pick some files"),
+ QDir::home().absolutePath());
+ foreach (const QString &file, files)
+ FileModel::instance().addFile(file);
+}
+
+void WidgetSimple::contextMenuEvent(QContextMenuEvent *event) {
+ QMenu popupMenu;
+ popupMenu.addAction(actionAddFiles);
+ if (treeViewFiles->selectionModel()->selectedRows().count()) {
+ popupMenu.addAction(actionRemoveSelectedFiles);
+ popupMenu.addSeparator();
+ popupMenu.addAction(actionUpSelectedFiles);
+ popupMenu.addAction(actionDownSelectedFiles);
+ }
+
+ popupMenu.exec(event->globalPos());
+}
+
+void WidgetSimple::treeViewFilesSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) {
+ pushButtonRemoveFiles->setEnabled(treeViewFiles->selectionModel()->selectedRows().count());
+}
+
+void WidgetSimple::on_actionUpSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (list.count()) {
FileModel::instance().upRows(list);
filesDropDone();
}
}
-void WidgetSimple::on_pushButtonDownFiles_clicked() {
+void WidgetSimple::on_actionDownSelectedFiles_triggered() {
QModelIndexList list = treeViewFiles->selectionModel()->selectedRows();
if (list.count()) {
FileModel::instance().downRows(list);
filesDropDone();
}
}
-
-void WidgetSimple::on_actionSortByName_triggered() {
- FileModel::instance().sort(FileModel::SortByName);
-}
-
-void WidgetSimple::on_actionSortByModificationDate_triggered() {
- FileModel::instance().sort(FileModel::SortByModificationDate);
-}
diff --git a/renamah/widget_simple.h b/renamah/widget_simple.h
index 57cb743..edd0f87 100644
--- a/renamah/widget_simple.h
+++ b/renamah/widget_simple.h
@@ -1,51 +1,57 @@
#ifndef WIDGET_SIMPLE_H
#define WIDGET_SIMPLE_H
#include <QMenu>
#include <interfaces/filter.h>
#include <interfaces/action.h>
#include <interfaces/modifier_config_widget.h>
#include "ui_widget_simple.h"
class WidgetSimple : public QWidget, private Ui::WidgetSimple
{
Q_OBJECT
public:
WidgetSimple(QWidget *parent = 0);
void initAfterPluginLoaded();
/*! Called after each profile loaded */
void newProfile();
protected:
bool eventFilter(QObject *watched, QEvent *event);
void changeEvent(QEvent *event);
+ void contextMenuEvent(QContextMenuEvent *event);
private:
int uiRetranslating;
QMenu *menuSort;
void refreshFileCount();
void modifyCurrentFileName();
private slots:
- void on_pushButtonAddFiles_clicked();
- void on_pushButtonRemoveFiles_clicked();
- void on_pushButtonUpFiles_clicked();
- void on_pushButtonDownFiles_clicked();
+ void on_pushButtonAddFiles_clicked() { actionAddFiles->trigger(); }
+ void on_pushButtonRemoveFiles_clicked() { actionRemoveSelectedFiles->trigger(); }
+ void on_pushButtonUpFiles_clicked() { actionUpSelectedFiles->trigger(); }
+ void on_pushButtonDownFiles_clicked() { actionDownSelectedFiles->trigger(); }
void on_pushButtonProcess_clicked();
void on_comboBoxOperation_currentIndexChanged(int index);
void on_toolButtonDestination_clicked();
void filesInserted(const QModelIndex &, int, int) { refreshFileCount(); }
void filesRemoved(const QModelIndex &, int, int) { refreshFileCount(); }
void filesModelReset() { refreshFileCount(); }
void filesDropDone();
void generalExtensionPolicyChanged();
void on_actionSortByName_triggered();
void on_actionSortByModificationDate_triggered();
+ void on_actionRemoveSelectedFiles_triggered();
+ void on_actionAddFiles_triggered();
+ void on_actionUpSelectedFiles_triggered();
+ void on_actionDownSelectedFiles_triggered();
+ void treeViewFilesSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
};
#endif
diff --git a/renamah/widget_simple.ui b/renamah/widget_simple.ui
index 5d0bffa..33ecce5 100644
--- a/renamah/widget_simple.ui
+++ b/renamah/widget_simple.ui
@@ -1,333 +1,392 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WidgetSimple</class>
<widget class="QWidget" name="WidgetSimple">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>676</width>
<height>571</height>
</rect>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QGridLayout" name="gridLayout_6">
<item row="0" column="0">
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="childrenCollapsible">
<bool>false</bool>
</property>
<widget class="QWidget" name="widgetFiles" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<layout class="QGridLayout" name="gridLayout_5">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="2">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButtonProcess">
<property name="text">
<string>Process</string>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/process.png</normaloff>:/images/process.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="comboBoxOperation">
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContents</enum>
</property>
<item>
<property name="text">
<string>Rename files</string>
</property>
</item>
<item>
<property name="text">
<string>Copy renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Move renamed files in</string>
</property>
</item>
<item>
<property name="text">
<string>Create symbolic links in</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEditDestination">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="toolButtonDestination">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0" colspan="2">
<widget class="QFrame" name="frameOperation">
<property name="frameShape">
<enum>QFrame::HLine</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item row="2" column="0" rowspan="7">
<widget class="QTreeView" name="treeViewFiles">
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragEnabled">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::InternalMove</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="animated">
<bool>true</bool>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
</widget>
</item>
<item row="2" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonAddFiles">
<property name="toolTip">
<string>Add some files...</string>
</property>
<property name="text">
- <string>Add...</string>
+ <string>Add</string>
+ </property>
+ <property name="icon">
+ <iconset resource="renamah.qrc">
+ <normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
</property>
</widget>
</item>
<item row="3" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonRemoveFiles">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
<property name="toolTip">
<string>Remove selected files</string>
</property>
<property name="text">
<string>Remove</string>
</property>
+ <property name="icon">
+ <iconset resource="renamah.qrc">
+ <normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
+ </property>
</widget>
</item>
<item row="7" column="1" colspan="2">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>258</height>
</size>
</property>
</spacer>
</item>
<item row="8" column="1" colspan="2">
<widget class="QLabel" name="labelFileCount">
<property name="frameShape">
<enum>QFrame::Panel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<property name="text">
<string notr="true">13 files</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="4" column="1" colspan="2">
<widget class="QPushButton" name="pushButtonSort">
<property name="text">
<string>Sort by</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QPushButton" name="pushButtonUpFiles">
<property name="toolTip">
<string>Up selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
</property>
</widget>
</item>
<item row="5" column="2">
<widget class="QPushButton" name="pushButtonDownFiles">
<property name="toolTip">
<string>Down selected files</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="renamah.qrc">
<normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QTabWidget" name="tabWidgetOperations">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabExtensionPolicy">
<attribute name="title">
<string>Extension policy</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QScrollArea" name="scrollArea">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>652</width>
<height>57</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetExtensionPolicy" name="widgetExtensionPolicy" native="true"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabFilters">
<attribute name="title">
<string>Filters</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_4">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetFilters" name="widgetFilters" native="true"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabEnders">
<attribute name="title">
<string>Finalizers</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_18">
<property name="margin">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="WidgetActions" name="widgetFinalizers" native="true"/>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>
<action name="actionSortByName">
<property name="text">
<string>by name</string>
</property>
<property name="toolTip">
<string>Sort files by name</string>
</property>
</action>
<action name="actionSortByModificationDate">
<property name="text">
<string>by modification date</string>
</property>
</action>
+ <action name="actionRemoveSelectedFiles">
+ <property name="icon">
+ <iconset resource="renamah.qrc">
+ <normaloff>:/images/remove.png</normaloff>:/images/remove.png</iconset>
+ </property>
+ <property name="text">
+ <string>&Remove</string>
+ </property>
+ <property name="toolTip">
+ <string>Remove selected files</string>
+ </property>
+ </action>
+ <action name="actionAddFiles">
+ <property name="icon">
+ <iconset resource="renamah.qrc">
+ <normaloff>:/images/add.png</normaloff>:/images/add.png</iconset>
+ </property>
+ <property name="text">
+ <string>&Add</string>
+ </property>
+ <property name="toolTip">
+ <string>Add files</string>
+ </property>
+ </action>
+ <action name="actionUpSelectedFiles">
+ <property name="icon">
+ <iconset resource="renamah.qrc">
+ <normaloff>:/images/up.png</normaloff>:/images/up.png</iconset>
+ </property>
+ <property name="text">
+ <string>&Up</string>
+ </property>
+ <property name="toolTip">
+ <string>Up selected files</string>
+ </property>
+ </action>
+ <action name="actionDownSelectedFiles">
+ <property name="icon">
+ <iconset resource="renamah.qrc">
+ <normaloff>:/images/down.png</normaloff>:/images/down.png</iconset>
+ </property>
+ <property name="text">
+ <string>&Down</string>
+ </property>
+ <property name="toolTip">
+ <string>Down selected files</string>
+ </property>
+ </action>
</widget>
<customwidgets>
<customwidget>
<class>WidgetExtensionPolicy</class>
<extends>QWidget</extends>
<header>widget_extension_policy.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetActions</class>
<extends>QWidget</extends>
<header>widget_actions.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WidgetFilters</class>
<extends>QWidget</extends>
<header>widget_filters.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources>
<include location="renamah.qrc"/>
</resources>
<connections/>
</ui>
|
Guid75/renamah
|
c2fdca0403e180af2aceca59299e69b1dc6093a1
|
New translations
|
diff --git a/renamah/translations/renamah_en_US.ts b/renamah/translations/renamah_en_US.ts
index 3d4a44f..70e9491 100644
--- a/renamah/translations/renamah_en_US.ts
+++ b/renamah/translations/renamah_en_US.ts
@@ -1,384 +1,424 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
<name>DialogManualRename</name>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Do you really want to set the original filename?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
- <location filename="../file_model.cpp" line="90"/>
+ <location filename="../file_model.cpp" line="92"/>
<source>Original</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../file_model.cpp" line="91"/>
+ <location filename="../file_model.cpp" line="93"/>
<source>Renamed</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
<location filename="../form_twinning.cpp" line="190"/>
<source>Choose a directory for left files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.cpp" line="201"/>
<source>Choose a directory for right files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="25"/>
<source>Simple</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="38"/>
<source>Last operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="64"/>
<source>&File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="73"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="83"/>
<source>&Quit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="88"/>
<source>Language</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="93"/>
<source>&Load profile...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.ui" line="98"/>
<source>&Save profile...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.cpp" line="124"/>
<source>Choose a profile to load</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../main_window.cpp" line="136"/>
<source>Choose a profile filename to save in</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
<location filename="../modifier_model.cpp" line="54"/>
<source>#</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="55"/>
<source>Mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="56"/>
<source>Action</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
<location filename="../processor.cpp" line="127"/>
<source>Rename</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="128"/>
<source>Copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="129"/>
<source>Move</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../processor.cpp" line="130"/>
<source>Create link</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
<location filename="../widget_filters.cpp" line="38"/>
<source>Override the global extension policy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="39"/>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="40"/>
<source>Extension policy</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
<location filename="../widget_modifiers.cpp" line="48"/>
<source>Add a new %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Confirmation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Do you really want to remove this filter?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_modifiers.ui" line="328"/>
+ <location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
- <location filename="../widget_simple.cpp" line="71"/>
+ <location filename="../widget_simple.cpp" line="78"/>
<source>Pick a file</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="82"/>
+ <location filename="../widget_simple.cpp" line="89"/>
<source>Confirmation</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="82"/>
+ <location filename="../widget_simple.cpp" line="89"/>
<source>Do you really want to remove this files?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="108"/>
+ <location filename="../widget_simple.cpp" line="115"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="108"/>
+ <location filename="../widget_simple.cpp" line="115"/>
<source>Do you really want to start the rename process?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="152"/>
+ <location filename="../widget_simple.cpp" line="159"/>
<source>Choose a destination directory</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
- <location filename="../widget_simple.cpp" line="162"/>
+ <location filename="../widget_simple.cpp" line="169"/>
<source>%n files</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="126"/>
+ <location filename="../widget_simple.ui" line="141"/>
+ <source>Add some files...</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="144"/>
<source>Add...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="133"/>
+ <location filename="../widget_simple.ui" line="151"/>
+ <source>Remove selected files</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="154"/>
<source>Remove</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="176"/>
- <source>Extension policy</source>
+ <location filename="../widget_simple.ui" line="190"/>
+ <source>Sort by</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="197"/>
+ <source>Up selected files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widget_simple.ui" line="211"/>
+ <source>Down selected files</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="232"/>
+ <source>Extension policy</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="267"/>
<source>Filters</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="224"/>
+ <location filename="../widget_simple.ui" line="280"/>
<source>Finalizers</source>
<translation type="unfinished"></translation>
</message>
+ <message>
+ <location filename="../widget_simple.ui" line="297"/>
+ <source>by name</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="300"/>
+ <source>Sort files by name</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="305"/>
+ <source>by modification date</source>
+ <translation type="unfinished"></translation>
+ </message>
</context>
</TS>
diff --git a/renamah/translations/renamah_fr.ts b/renamah/translations/renamah_fr.ts
index c6e36a2..3059299 100644
--- a/renamah/translations/renamah_fr.ts
+++ b/renamah/translations/renamah_fr.ts
@@ -1,406 +1,446 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
<name>DialogManualRename</name>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.cpp" line="27"/>
<source>Do you really want to set the original filename?</source>
<translatorcomment>bof</translatorcomment>
<translation>Ãtes-vous sûr de vouloir affecter le nom de fichier original ?</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="14"/>
<source>Manual renaming</source>
<translation>Renommage manuel</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="23"/>
<source>Back to automatic renaming</source>
<translation>Retour au renommage automatique</translation>
</message>
<message>
<location filename="../dialog_manual_rename.ui" line="66"/>
<source>Original value</source>
<translation>Valeur originale</translation>
</message>
</context>
<context>
<name>FileModel</name>
<message>
- <location filename="../file_model.cpp" line="90"/>
+ <location filename="../file_model.cpp" line="92"/>
<source>Original</source>
<translation>Original</translation>
</message>
<message>
- <location filename="../file_model.cpp" line="91"/>
+ <location filename="../file_model.cpp" line="93"/>
<source>Renamed</source>
<translation>Renommé</translation>
</message>
</context>
<context>
<name>FormTwinning</name>
<message>
<location filename="../form_twinning.cpp" line="190"/>
<source>Choose a directory for left files</source>
<translation>Choisissez un répertoire pour les fichiers de gauche</translation>
</message>
<message>
<location filename="../form_twinning.cpp" line="201"/>
<source>Choose a directory for right files</source>
- <translation type="unfinished"></translation>
+ <translation>Choisissez un répertoire pour les fichiers de droite</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="23"/>
<location filename="../form_twinning.ui" line="88"/>
<source>...</source>
- <translation type="unfinished"></translation>
+ <translation>...</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="95"/>
<location filename="../form_twinning.ui" line="114"/>
<source>Extension:</source>
- <translation type="unfinished"></translation>
+ <translation>Extension :</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="106"/>
<source>*.avi,*.mkv</source>
- <translation type="unfinished"></translation>
+ <translation>*avi,*.mkv</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="191"/>
<location filename="../form_twinning.ui" line="198"/>
<source>Status</source>
- <translation type="unfinished"></translation>
+ <translation>Statut</translation>
</message>
<message>
<location filename="../form_twinning.ui" line="205"/>
<source>process</source>
- <translation type="unfinished"></translation>
+ <translation>lancer</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../main_window.ui" line="14"/>
<source>Renamah</source>
<translation></translation>
</message>
<message>
<location filename="../main_window.ui" line="25"/>
<source>Simple</source>
<translation>Simple</translation>
</message>
<message>
<location filename="../main_window.ui" line="38"/>
<source>Last operations</source>
<translation>Dernières opérations</translation>
</message>
<message>
<location filename="../main_window.ui" line="64"/>
<source>&File</source>
<translation>&Fichier</translation>
</message>
<message>
<location filename="../main_window.ui" line="73"/>
<source>Settings</source>
<translation>Paramètres</translation>
</message>
<message>
<location filename="../main_window.ui" line="83"/>
<source>&Quit</source>
<translation>&Quitter</translation>
</message>
<message>
<location filename="../main_window.ui" line="88"/>
<source>Language</source>
<translation>Langage</translation>
</message>
<message>
<location filename="../main_window.ui" line="93"/>
<source>&Load profile...</source>
<translation>&Charge un profile...</translation>
</message>
<message>
<location filename="../main_window.ui" line="98"/>
<source>&Save profile...</source>
<translation>&Sauver le profile...</translation>
</message>
<message>
<source>Save profile...</source>
<translation type="obsolete">Sauve le profile...</translation>
</message>
<message>
<location filename="../main_window.cpp" line="124"/>
<source>Choose a profile to load</source>
<translation>Choisissez un profile à charger</translation>
</message>
<message>
<location filename="../main_window.cpp" line="136"/>
<source>Choose a profile filename to save in</source>
<translation>Choisissez un nom de profile à sauver</translation>
</message>
</context>
<context>
<name>ModifierModel</name>
<message>
<location filename="../modifier_model.cpp" line="54"/>
<source>#</source>
<translation></translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="55"/>
<source>Mode</source>
<translation>Mode</translation>
</message>
<message>
<location filename="../modifier_model.cpp" line="56"/>
<source>Action</source>
<translation>Action</translation>
</message>
</context>
<context>
<name>Processor</name>
<message>
<location filename="../processor.cpp" line="127"/>
<source>Rename</source>
<translation>Renommer</translation>
</message>
<message>
<location filename="../processor.cpp" line="128"/>
<source>Copy</source>
<translation>Copier</translation>
</message>
<message>
<location filename="../processor.cpp" line="129"/>
<source>Move</source>
<translation>Déplacer</translation>
</message>
<message>
<location filename="../processor.cpp" line="130"/>
<source>Create link</source>
<translation>Créer un lien</translation>
</message>
</context>
<context>
<name>WidgetExtensionPolicy</name>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
<location filename="../widget_extension_policy.cpp" line="123"/>
<source>Do you really want to return to default extension policy settings?</source>
<translation>Souhaitez-vous vraiment revenir à la politique d'extension par défaut ?</translation>
</message>
<message>
<source>Do you really want to return to return to default extension policy settings?</source>
<translation type="obsolete">Voulez-vous vraiment revenir à la politique d'extension par défaut ?</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="13"/>
<source>Form</source>
<translation></translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="22"/>
<source>Choose what part of files you want to rename:</source>
<translation>Choisissez quelle partie des fichiers vous voulez renommer :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="28"/>
<source>The basename (without extension)</source>
<translation>Le nom de base (sans l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="35"/>
<source>The entire filename (with extension)</source>
<translation>Le nom de fichier en entier (avec l'extension)</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="42"/>
<source>Only the extension</source>
<translation>Seulement l'extension</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="52"/>
<source>Reset to default settings</source>
<translation>Paramètres par défaut</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="85"/>
<source>The file extension starts just after the:</source>
<translation>L'extension du fichier commence juste après le :</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="91"/>
<source>First point from the right</source>
<translation>Premier point en partant de la droite</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="98"/>
<source>First point from the left</source>
<translation>Premier point en partant de la gauche</translation>
</message>
<message>
<location filename="../widget_extension_policy.ui" line="112"/>
<source>th point from the right</source>
<translation>ième point en partant de la droite</translation>
</message>
</context>
<context>
<name>WidgetFilters</name>
<message>
<location filename="../widget_filters.cpp" line="39"/>
<source>General</source>
<translation>Général</translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="40"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
<location filename="../widget_filters.cpp" line="38"/>
<source>Override the global extension policy</source>
<translation>Supplanter la politique d'extension globale</translation>
</message>
</context>
<context>
<name>WidgetModifiers</name>
<message>
<location filename="../widget_modifiers.cpp" line="48"/>
<source>Add a new %1</source>
<translation>Ajouter un nouveau %1</translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Confirmation</source>
<translation>Confirmation</translation>
</message>
<message>
<location filename="../widget_modifiers.cpp" line="65"/>
<source>Do you really want to remove this filter?</source>
<translation>Voulez-vous réellement supprimer ce filtre ?</translation>
</message>
<message>
<source>Title</source>
<translation type="obsolete">Titre</translation>
</message>
<message>
<source>Modifier description</source>
<translation type="obsolete">Description du modificateur</translation>
</message>
<message>
- <location filename="../widget_modifiers.ui" line="328"/>
+ <location filename="../widget_modifiers.ui" line="334"/>
<source>Click to add</source>
<translation>Cliquez pour ajouter</translation>
</message>
</context>
<context>
<name>WidgetSimple</name>
<message>
- <location filename="../widget_simple.cpp" line="71"/>
+ <location filename="../widget_simple.cpp" line="78"/>
<source>Pick a file</source>
<translation>Choisissez un fichier</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="82"/>
+ <location filename="../widget_simple.cpp" line="89"/>
<source>Confirmation</source>
<translation>Confirmation</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="82"/>
+ <location filename="../widget_simple.cpp" line="89"/>
<source>Do you really want to remove this files?</source>
<translation>Ãtes-vous certain de vouloir supprimer ces fichiers ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="108"/>
+ <location filename="../widget_simple.cpp" line="115"/>
<source>Are you sure?</source>
<translation>Ãtes-vous certain ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="108"/>
+ <location filename="../widget_simple.cpp" line="115"/>
<source>Do you really want to start the rename process?</source>
<translation>Voulez-vous vraiment démarrer le processus de renommage ?</translation>
</message>
<message>
- <location filename="../widget_simple.cpp" line="152"/>
+ <location filename="../widget_simple.cpp" line="159"/>
<source>Choose a destination directory</source>
<translation>Choisissez un répertoire de destination</translation>
</message>
<message numerus="yes">
- <location filename="../widget_simple.cpp" line="162"/>
+ <location filename="../widget_simple.cpp" line="169"/>
<source>%n files</source>
<translation>
<numerusform>%n fichier</numerusform>
<numerusform>%n fichiers</numerusform>
</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="43"/>
<source>Process</source>
<translation>Lancer</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="58"/>
<source>Rename files</source>
<translation>Renommage de fichier</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="63"/>
<source>Copy renamed files in</source>
<translation>Copie renommée dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="68"/>
<source>Move renamed files in</source>
<translation>Déplacement renommé dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="73"/>
<source>Create symbolic links in</source>
<translation>Création des liens dans</translation>
</message>
<message>
<location filename="../widget_simple.ui" line="88"/>
<source>...</source>
<translation></translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="126"/>
+ <location filename="../widget_simple.ui" line="141"/>
+ <source>Add some files...</source>
+ <translation>Ajouter des fichiers...</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="144"/>
<source>Add...</source>
<translation>Ajouter...</translation>
</message>
+ <message>
+ <location filename="../widget_simple.ui" line="151"/>
+ <source>Remove selected files</source>
+ <translation>Supprimer les fichiers sélectionnés</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="297"/>
+ <source>by name</source>
+ <translation>par nom</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="300"/>
+ <source>Sort files by name</source>
+ <translation>Trier les fichier par nom</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="305"/>
+ <source>by modification date</source>
+ <translation>par date de modification</translation>
+ </message>
<message>
<source>Add files...</source>
<translation type="obsolete">Ajouter des fichiers...</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="133"/>
+ <location filename="../widget_simple.ui" line="154"/>
<source>Remove</source>
<translation>Supprimer</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="176"/>
+ <location filename="../widget_simple.ui" line="190"/>
+ <source>Sort by</source>
+ <translation>Trier par</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="197"/>
+ <source>Up selected files</source>
+ <translation>Monter les fichiers sélectionnés</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="211"/>
+ <source>Down selected files</source>
+ <translation>Descendre les fichiers sélectionnés</translation>
+ </message>
+ <message>
+ <location filename="../widget_simple.ui" line="232"/>
<source>Extension policy</source>
<translation>Politique d'extension</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="211"/>
+ <location filename="../widget_simple.ui" line="267"/>
<source>Filters</source>
<translation>Filtres</translation>
</message>
<message>
- <location filename="../widget_simple.ui" line="224"/>
+ <location filename="../widget_simple.ui" line="280"/>
<source>Finalizers</source>
<translation>Finaliseurs</translation>
</message>
</context>
</TS>
|
Guid75/renamah
|
a93debb0cf4e5827b0ac37bb99f718848f2335af
|
project homesite changed
|
diff --git a/README b/README
index c4fca1c..ce56295 100644
--- a/README
+++ b/README
@@ -1,47 +1,47 @@
--------
WELCOME!
--------
Renamah is a(nother) batch renamer written in C++.
The effort is oriented toward:
* ergonomy
* the crossplatform aspect (Qt4)
* modularity (plugin system for filters)
Featuring:
* cascading filters: replace, numbering, cutter, case manipulations, etc
* cascading finalizers: launching of a system command for each files, etc
* undo system (TODO)
* internationalization (French and English for now)
--------------------
INSTALL INSTRUCTIONS
--------------------
In the renamah root directory, type:
cmake .
make
sudo make install
------------
DEPENDENCIES
------------
To be successfully compiled, Renamah depends on some libraries:
- libqt4-core
- libqt4-gui
------------
THE END WORD
------------
-You can find Renamah homepage at: http://code.google.com/p/renamah
+You can find Renamah homepage at: http://github.com/Guid75/renamah
Thank you for using it!
Guillaume Denry <guillaume.denry@gmail.com>
|
tav/oldblog
|
319f43b5d39e50f04802cd1a65429059a2f5907d
|
Adjust pecu allocations.
|
diff --git a/pecu-allocations-by-tav.txt b/pecu-allocations-by-tav.txt
index bed8c37..0c3ff41 100644
--- a/pecu-allocations-by-tav.txt
+++ b/pecu-allocations-by-tav.txt
@@ -1,559 +1,554 @@
---
created: 2009-03-15, 10:14
layout: post
license: Public Domain
---
=======================
Pecu Allocations by Tav
=======================
.. image:: http://cloud.github.com/downloads/tav/plexnet/gfx.aaken.png
:class: float-right
Hundreds of people have -- knowingly or not -- had a *direct* impact on my
work/vision. Their belief, inspiration, energy, encouragement, suggestions,
criticisms, support (both emotional and financial), tasty treats and hard work
has been phenomenal!
I'd like to reward them with some tav-branded `pecu allocations
<http://www.thruflo.com/2009/06/09/tav-describes-pecus.html>`_.
Since I'm not making any pecu payouts at the moment, they're not worth much yet
-- but I hope one day that those who've helped me will feel the gratitude =)
See below for the full list of `pecu
<http://www.thruflo.com/2009/06/09/tav-describes-pecus.html>`_ allocations.
.. more
The following individuals have put in a lot to make my vision a reality and I'd
like to reward them with **200,000** pecus each:
.. class:: double-column
* Alex Tomkins (+50,000)
+* Alice Fung (+200,000)
* Brian Deegan
* Cris Pearson
* Daniel Biddle
* Danny Bruder
* David Pinto
-* Inderpaul Johar
-* James Arthur (+200,000)
* Jeffry Archambeault (+50,000)
* John McCane-Whitney
-* Liliana Avrushin
* Luke Graybill
* Mamading Ceesay (+100,000)
* Martyn Hurt
* Matthieu Rey-Grange
* Mathew Ryden (+100,000)
* Nadine Gahr
* Nathan Staab
-* Narmatha Murugananda
* Navaratnam Para
* Nicholas Midgley
* Ãyvind Selbek (+200,000)
* Sofia Bustamante
* Sean B. Palmer (+100,000)
-* Seyi Ogunyemi
+* Seyi Ogunyemi (+50,000)
* Stefan Plantikow
+* Thamilarasi Siva
* Tim Jenks
* Tiziano Cirillo
* Tom Salfield (+50,000)
* Yan Minagawa
The following beautiful creatures have helped at various critical junctures or
laid key foundations. For this they get **20,000** pecus each:
.. class:: double-column
* Aaron Swartz
* Adam Langley (+20,000)
-* Ade Thomas
-* Adnan Hadzi
-* Alex Greiner
* Alex Pappajohn (+80,000)
-* Alice Fung
* Allen Short
* Andreas Dietrich
* Andrew Kenneth Milton
* Anne Biggs
-* Anne Helene Wirstad
* Anette Hvolbæk
* Bryce Wilcox-O'Hearn
* Charles Goodier
* Chris Wood
* Christina Rebel
* Claire Assis
* David Bovill
* Derek Richards
* Eric Hopper
-* Eric Wahlforss
* Erik Möller
* Erol Ziya
-* Ephraim Spiro
* Fenton Whelan
-* Fergus Doyle
* Gary Alexander
* Gloria Davies-Coates
* Guido van Rossum
-* Guilhem Buzenet
* Howard Rheingold
+* Inderpaul Johar
* Itamar Shtull-Trauring
* Jacob Everist
+* James Arthur
* Jan Ludewig
-* Jill Lundquist
* Jim Carrico
* Jo Walsh
-* Joe Short
* Joerg Baach
* John Hurliman
* Josef Davies-Coates (+20,000)
* Henri Cattan
-* Henry Hicks
* Ka Ho Chan
* Karin Kylander
* Karina Arthur
* Katie Miller
* Kisiyane Roberts
* Laura Tov
-* Lesley Donna Williams
-* Lucie Rey-Grange
+* Liliana Avrushin
* Maciej Fijalkowski (+20,000)
-* Mark Poole
-* Maria Glauser
* Maria Chatzichristodoulou
* Matthew Sellwood
-* Matthew Skinner
+* Maximilian Kampik
* Mayra Graybill
-* Mia Bittar
* Mohan Selladurai
+* Narmatha Murugananda
* Neythal (Sri Lanka)
-* Nick Ierodiaconou
* Nolan Darilek
-* Olga Zueva
* Paul Böhm
* Phillip J. Eby
* Pierre-Antoine Tetard
* Ricky Cousins
* Salim Virani
* Saritah (Sarah Louise Newman ?)
* Saul Albert
* Shalabh Chaturvedi
* Simeon Scott
* Simon Michael
* Simon Fox
* Simon Reynolds
-* Stephan Karpischek
* Steve Alexander
* Suhanya Babu
* Tavin Cole
-* Thamilarasi Siva
* Tim Berners-Lee
* Tom Owen-Smith
-* Vanda Petanjek
* Xiao Xuan Guo
These lovely supporters get **2,000** pecus each:
-.. Ana Sandra Ruiz Entrecanales
-
.. class:: double-column
* Adam Burns
* Adam Karpierz (Poland)
* Adam Perfect
* Adam Wern
+* Ade Thomas
* Adir Tov
+* Adnan Hadzi
* Agathe Pouget-Abadie
* Al Tepper
* Alan Wagenberg
-* Alastair Parvin
* Alex Bustamante
+* Alex Greiner
* Alexander Wait (USA)
* Andreas Kotes
* Andreas Schwarz
* Andrius Kulikauskas
* Andy Dawkins
* Andy McKay
* Andrew M. Kuchling
* Andrew McCormick
* Angela Beesley Starling
* Anna Gordon-Walker
* Anna Rothkopf
* Annalisa Fagan
* Anne Doyle
+* Anne Helene Wirstad
* Anselm Hook
* Ante Pavlov
* Arani Siva
* Ash Gerrish
* Ashley Siple
* Auro Tom Foxtrot
-* Azra Gül
* Beatrice Wessolowski
* Ben Pirt
* Ben Swartz
* Benjamin Geer
* Benny "Curus" Amorsen
* Bernard Lietaer
* Blake Ludwig
* Boian Rodriguez Nikiforov
* Bram Cohen
* Brandon Wiley
* Bree Morrison
* Brenton Bills
* Brian Coughlan
* Briony "Misadventure" (UK)
* Callum Beith
* Candie Duncan
* Carl Ballard Swanson
* Carl Friedrich Bolz
* Céline Seger
* Chai Mason
* Charley Quinton
* Chris Cook
* Chris Davis
* Chris Heaton
* Chris McDonough
* Chris Withers
* Christoffer Hvolbaek
* Christopher Satterthwaite
* Christopher Schmidt
* Clara Maguire
* Cory Doctorow
* Craig Hubley
* Cyndi Rhoades
* Damiano VukotiÄ
* Dan Brickley
* Daniel Harris
* Daniel Magnoff
* Dante-Gabryell Monson
* David Bausola
* David Cozens
* David Goodger
* David Mertz
* David Midgley
* David Mills
* David Saxby
* Darran Edmundson
* Darren Platt
* Debra Bourne (UK)
* Dharushana Muthulingam
* Dermot ? (UK)
* Dimitris Savvaidis
* Dominik Webb
* Donatella Bernstein
* Dorothee Olivereau
* Dmytri Kleiner
* Earle Martin
* Edward Saperia
* Eléonore De Prunelé
* Elisabet Sahtouris
* Elkin Gordon Atwell
* Elmar Geese
* Emma Wigley
* Emmanuel Baidoo
+* Ephraim Spiro
+* Eric Wahlforss
* Erik Stewart
* Fabian Kyrielis
-* Farhan Rehman
-* Femi Longe
* Felicity Wood
* Felix Iskwei
+* Femi Longe
+* Fergus Doyle
* Florence David
* Francesca Cerletti (UK)
* Francesca Romana Giordano
* Gabe Wachob
* Gabrielle Hamm
* Gareth Strangemore-Jones
* Gary Poster
* Gaurav Pophaly
* Gavin Starks
* Gemma Youlia Dillon
* Geoff Jones
* Geoffry Arias
* George Nicholaides
* Gerry Gleason
* Giles Mason
* Glyph Lefkowitz
* Gordon Mohr
* Grant Stapleton
* Greg Timms
* Gregor J. Rothfuss
+* Guilhem Buzenet
* Guy Kawasaki
* Hannah Harris
* Harriet Harris
* Heather Wilkinson
* Helen Aldritch
* Henry Bowen
+* Henry Hicks
* Holly Lloyd
* Holly Porter
* Ian Clarke
* Ian Hogarth
* Ida Norheim-Hagtun
* Ifung Lu
* Igor Tojcic
* Ilze Black
* Inge Rochette
* James Binns
* James Cox (UK)
* James Howison (Australia)
* James Hurrell
* James McKay (Switzerland)
* James Stevens
* James Sutherland
* James Wallace
* Jan-Klaas Kollhof
* Jane Moyses
* Javier Candeira
* Jeannie Cool
* Jeremie Miller
* Jessica Bridges-Palmer
+* Jill Lundquist
* Jim Ley
* Jimmy Wales
* Joanna O'Donnell
* Joe Geldart (UK)
+* Joe Short
* Joey DeVilla
* John Bywater
* John Cassidy
* John Lea
* John "Sayke" ?
* Joi Ito
* Jon Bootland
* Jonathan Robinson
* Joni Davis ?
* Joni Steiner
* Jose Esquer
* Joseph O'Kelly (UK)
* Joy Green
* Juan Pablo Rico
* Jubin Zawar
* Judith Martin
* Julia Forster
* Jurgen Braam
* Justin OâShaughnessy (UK)
* Ka-Ping Yee
* Kapil Thangavelu
* Karen Hessels
* Katerina Tselou
* Katja Strøm Cappelen
* Kath Short
* Katie Keegan
* Katie Prescott
* Katy Marks
* Kelly Teamey
* Ken Manheimer
* Kevin Hemenway
* Kevin Marks
* Kiran Jonnalagadda
* Kiyoto Kanda
* Lanchanie Dias Gunawardena
* Laura Scheffler
* Lauri Love
* Leon Rocha
* Lena Nalbach
+* Lesley Donna Williams
* Leslie Vuchot
* Lewis Hart
* Libby Miller
* Lion Kimbro
* Lisa Colaco
* Lord Kimo
* Lottie Child
* Lucas Gonzalez
* Luke Francl
* Luke Kenneth Casson Leighton
* Luke Nicholson
* Luke Robinson
* Lynton Currill Kim-Wai Pepper
* Magnolia Slimm
* Manuel Sauer
* Maor Bar-Ziv
* Marco Herry
+* Maria Glauser
* Mark Brown
* Mark Chaplin
* Mark Hodge
+* Mark Poole
* Mark S. Miller
* Markus Quarta
* Marguerite Smith
* Marshall Burns
* Martin Peck
* Mary Fee
* Matt Cooperrider
* Matthew Devney
+* Matthew Skinner
* Mattis Manzel
-* Maximilian Kampik
* Mayra Vivo Torres
* Meghan Benton
* Meera Shah
* Menka Parekh
+* Mia Bittar
* Michael Linton
* Michael Maranda
* Michael Sparks
* Michel Bauwens
* Mike Kazantsev
* Mike Linksvayer
* Mikey Weinkove
* Mitchell Jacobs
* Molly Webb
* Moraan Gilad
* Mostofa Zaman
* Navindu Katugampola
* Nathalie Follen
* Nick Hart-Williams
+* Nick Ierodiaconou
* Nick Szabo
* Nicolas David
* Niels Boeing (Germany)
* Nils Toedtmann
* Nisha Patel
* Nishant Shah
* Noa Harvey
* Noah Slater
+* Olga Zueva
* Olivia Tusinski
* Oliver Morrison
* Oliver Sylvester-Bradley
* Oz Mose
* Pamela McLean
* Paola Desiderio
* Paolo "xerox" Martini (UK)
* Pascale Scheurer
* Patrick Andrews
* Patrick Yiu
* Paul Everitt
* Paul Harrison
* Paul Mutton (UK)
* Paul Pesach
* Paul Robinett
* Peri Urban
* Pete Brownwell
* Petit-Pigeard Clotilde
* Phil G
* Phil Harris
* Piccia Neri
* Pietro Speroni di Fenizio
* \R. David Murray
* Rama Gheerawo
* Raph Levien
* Rasmacone Boothe
* Rasmus Tenbergen
* Rastko ?
* Ray Murray
* Raymond Hettinger
* Rayhan Omar
* Rebecca Harding
* Reem Martin
* Riccarda Zezza
* Rob Lord
* Robert De Souza
* Robert Kaye
* Robert Knowles
* Robin Upton
* Rodney Shakespeare
* Rohit Khare
* Roman Nosov
* Ron Briefel
* Ricardo Niederberger Cabral
* Richard Ford
* Richard Nelson
* Richard "coldfyre" Nicholas (USA)
* Roger Dingledine
* Romek Szczesniak
* Ross Evans (UK)
* Rufus Pollock
* Salim Fadhley (UK)
* Sam Brown
* Sam Geall
* Sam Joseph
* Sara Kiran
* Selas Mene
* Servane Mouazan
* Shahid Choudhry
* Shane Hughes
* Simon Bartlet
* Simon Persoff
* Simon Rawles
+* Siva Selladurai
* Sonia Ali
* Sophie ? (Austria)
* Sophie Le Barbier
* Stan Rey-Grange
* Stayce Kavanaugh
* Stefan Baker
* Steffi Dayalan
* Stella Boeva
* Stephan Dohrn
+* Stephan Karpischek
* Stephen Wilmot
* Steve Jenson
* Steve Peake
* Steven Starr
* Su Nandy
* Suresh Fernando
* Suw Charman
* Sunir Shah
* Sym Von LynX
* Tamsin Lejeune
* Tanis Taylor
* Tansy E Huws
* Tess Ashwin
* Tim Wacker (USA)
* Tom D. Harry (UK)
* Tom Heiser
* Tom Longson
* Tom Williams
* Tommy Hutchinson
* Tommy Teillaud
* Toni Prug
* Toni Sola
* Tony Cook
* Tyler Eaves
* Ushani Suresh
+* Vanda Petanjek
* Veeral ?
* William Wardlaw-Rogers
* Wayne Siron
* Wes Felter
* Wybo Wiersma
* Zoe Cremer
* Zoe Young
And, finally, whilst I'm not currently making any pecu allocations to them, I
feel deeply indebted to these visionaries, musicians, coders and writers:
.. class:: double-column
* \A. R. Rahman
* Alan Kay
* Asian Dub Foundation
* Au Revoir Simone
* Bruce Sterling
* Buckminster Fuller (passed away)
* Daft Punk
* David Lynch
* Douglas Engelbart
* Fernando Perez
* India Arie
* Jeff Buckley (passed away)
* Kim Stanley Robinson
* Lawrence Lessig
* M.I.A.
* Mahatma Gandhi (passed away)
* Manu Chao
* Marc Stiegler
* Mark Pilgrim
* Marlena Shaw
* Massive Attack
* Michael Franti
* Muhammad Yunus
* Neal Stephenson
* Nouvelle Vague
* P.M.
* Paul Graham
* Peter Norvig
* Portishead
* Ray Charles (passed away)
* Ray Ozzie
* Richard P. Gabriel
* Tanya Stephens
* Ted Nelson
* Tim Peters
* Vannevar Bush (passed away)
* Vint Cerf
Thank you all!
\ No newline at end of file
|
tav/oldblog
|
05ec6830c6a63a40d609aa9bd954a5d8d83a9341
|
Added Consolas to the css for Windows. Thx donatzsky on HN.
|
diff --git a/website/css/site.css b/website/css/site.css
index 0380d94..6ca88e2 100644
--- a/website/css/site.css
+++ b/website/css/site.css
@@ -1,744 +1,744 @@
/*
* aaken default stylesheet -- by tav
*
*/
a {
color: #0000dd;
text-decoration: underline;
}
a:hover, a:active {
text-decoration: none;
}
a.no-underline {
text-decoration: none;
}
a.no-underline:hover {
text-decoration: underline;
}
body {
background-color: #3e3935;
background-image: url("../gfx/bg.jpg");
font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
font-size: 18px;
margin: 0;
min-width: 1080px;
padding: 0;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-weight: normal !important;
clear: both;
font-size: 36px;
margin: 0;
}
h1 {
font-size: 30px;
margin: 18px 0 14px 0;
}
pre {
background-color: #fefef1;
border: 1px solid #f7a600;
border-left: 5px solid #f7a600;
color: #101010;
- font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
+ font: 14px Consolas, "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
overflow: hidden;
padding: 12px 15px 13px 12px;
margin: 20px 30px 0 20px;
-webkit-border-bottom-right-radius: 12px;
-moz-border-radius-bottomright: 12px;
border-bottom-right-radius: 12px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
}
pre:hover {
overflow: auto;
}
pre.ascii-art {
line-height: 1em;
}
pre code {
background-color: transparent;
border: 0;
padding: 0;
border: 1px solid #c00;
}
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
strong {
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 1.4em;
font-weight: normal;
}
sup {
display: none;
}
li ul {
margin-top: 10px;
}
/* sections */
.content {
clear: both;
line-height: 1.5em;
margin-bottom: 1em;
}
#intro {
background: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
float: right;
padding: 5px 10px 10px 10px;
width: 200px;
line-height: 1.5em;
}
#intro h1 {
font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
font-size: 18px;
line-height: 27px;
margin: 18px 0 24px 0;
}
#main {
margin: 0px auto;
text-align: left;
width: 944px;
}
#page {
background: #fff;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
float: left;
width: 640px;
padding-left: 30px;
padding-right: 35px;
padding-top: 15px;
padding-bottom: 10px;
margin-bottom: 14px;
margin-right: 10px;
}
#site-header {
margin: 12px 0 14px 0;
text-align: right;
}
#site-title {
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border: 1px solid #fff;
color: #000;
font-family: "zalamander-caps-1","zalamander-caps-2", "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 3em;
float: left;
padding: 9px 15px 0px 15px;
text-decoration: none;
}
#site-title:hover {
border: 1px solid #000;
}
.wf-inactive #site-title {
padding-top: 0px;
padding-bottom: 8px;
}
#site-links {
padding-top: 4px;
}
#site-links a {
margin-left: 8px;
padding: 4px 6px;
text-decoration: none;
color: #fff;
font-size: 20px;
}
#site-links a:hover {
color: #000;
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#translation_form {
display: inline;
margin-right: 20px;
}
.follow-link {
margin: 12px 0 8px 16px;
}
/* disqus */
#dsq-global-toolbar, #dsq-sort-by, #dsq-like-tooltip {
display: none;
}
#dsq-subscribe, #dsq-footer, .dsq-item-trackback, #dsq-account-dropdown {
display: none;
}
#dsq-content h3 {
margin: 25px 0 25px 0 !important;
}
.dsq-comment-header a {
color: #2d2827;
}
/* rst classes */
.docinfo {
margin-left: 5px;
margin-top: 20px;
}
.abstract {
margin-top: 20px;
}
code, .literal {
background-color: #fefbf6;
border: 1px solid #dbd0be;
padding: 2px 4px;
- font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
+ font: 14px Consolas, "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
}
.topic-title {
font-weight: bold;
text-align: center;
}
.note {
color: #aaa;
margin-left: 10px;
font-style: italic;
}
.attention {
background-color: #FFC3C3;
padding: 1.5em;
margin-top: 1em;
margin-bottom: 1em;
text-align: center;
}
.admonition-title {
display: none
}
.highlight {
text-align: center;
border: 1px solid #c00;
background-color: #fff;
background-color: #c00;
color: #fff;
padding: 5px;
}
/* rst error */
.system-messages {
display: none;
}
/* toc */
.contents {
padding-left: 3em;
margin: 10px;
display: none;
}
.contents.toc-only {
display: block;
padding-left: 0;
margin: 0;
}
.contents.toc-only .topic-title {
display: none;
}
/* links */
a.fn-backref {
text-decoration: none;
}
a.footnote-reference {
vertical-align: super;
text-decoration: none;
}
/* tables */
table.docutils {
margin: 20px 30px 0 20px;
border-spacing: 0px;
}
table.docutils thead tr th {
background: #635b54;
color: #fff;
padding: 7px 10px;
font-weight: normal;
}
table.docutils td {
padding: 7px;
border-bottom: 1px dashed #d6d2cf;
}
table.docutils td .literal {
white-space: nowrap;
}
table.docutils thead tr th:first-child {
text-align: right;
}
table.docutils tr td:first-child {
text-align: right;
}
table.footnote, table.citation {
border: 0px;
padding: 5px;
margin: 5px;
}
table.citation td, table.footnote td {
border: 0px;
}
table.docutils td p, table.footnote td p, table.citation td p {
margin-top: 0px;
padding-top: 0px;
}
table.footnote td.label, table.citation td.label {
width: 12em;
padding-right: 10px;
text-align: right;
}
table.citation td.label a, table.footnote td.label a {
font-style: italic;
text-decoration: none;
color: #333;
}
p.caption {
color: #666;
font-style: italic;
margin-top: 5px;
padding-left: 5px;
text-align: center;
}
td p.first {
margin-top: 0;
}
td p.last {
margin-bottom: 0;
}
th.field-name, th.docinfo-name {
text-align: right;
padding-right: 5px;
white-space: nowrap;
}
table.field-list {
border: 0px;
}
table.field-list td {
border: 0px;
vertical-align: top;
padding: 1px;
}
/* doctest */
.doctest-output {
color: #a5504d;
}
.doctest-input {
color: #0d5d04;
}
.doctest-output {
color: #a5504d;
color: #c32528;
color: #bf5036;
}
.doctest-input {
color: #5d90cd;
color: #6a6a6a;
color: #0d5d04;
color: #27894f;
color: #00a33f;
color: #15973b;
color: #7f9a49;
color: #005d61;
color: #1d6c70;
color: #326008;
}
/* images */
img {
border: none;
vertical-align: top;
margin: 0;
padding: 0;
}
img.absmiddle {
vertical-align: middle;
}
/* lines */
hr {
noshade: noshade;
clear: both;
}
hr.clear {
clear: both;
height: 0;
width: 0;
margin: 0;
padding: 0;
color: #c00;
background-color: transparent;
border: 0px solid;
}
/* lists */
li {
margin-bottom: 10px;
}
/* utility classes */
.center {
text-align: center;
margin-top: 5px;
margin-bottom: 5px;
}
.hide {
display: none;
}
.image-caption {
font-style: italic;
text-align: right;
}
.float-left, .figure {
float: left;
padding: 5px;
margin-right: 12px;
border: 1px solid #ded0e8;
}
.figure {
width: 400px;
text-align: center;
}
.float-left-aligned {
float: left;
margin: 5px 12px 5px -30px;
}
.float-left-aligned .image-caption {
padding-top: 5px;
}
.float-right, .float-right-aligned {
float: right;
margin-left: 12px;
margin-bottom: 5px;
}
.float-right-aligned {
margin-right: -35px;
}
.float-right-aligned .image-caption {
padding-right: 5px;
}
.full-width, .full-width-lined {
clear: both;
margin-left: -30px;
margin-right: -35px;
}
.full-width pre {
margin: 0;
border-left: 0px;
border-right: 0px;
padding: 30px 35px 31px 30px;
-webkit-border-bottom-right-radius: 0px;
-moz-border-radius-bottomright: 0px;
border-bottom-right-radius: 0px;
-webkit-box-shadow: 0px 0px 0px transparent;
}
.full-width-lined {
border-bottom: 1px solid #cacaca;
border-top: 1px solid #cacaca;
margin-bottom: 20px;
margin-top: 20px;
}
.boxed {
border: 1px solid #cacaca;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
margin-top: 10px;
}
/* special */
h1.title {
display: none;
}
#abstract .topic-title {
display: none;
}
#table-of-contents .topic-title {
display: none;
}
.sidebox, .sidebox-grey {
padding: 17px 30px 17px 20px;
max-width: 180px;
float: right;
margin: 8px -35px 5px 10px;
}
.sidebox {
background-color: #dee;
border-right: 10px solid #488;
}
.sidebox-grey {
background-color: #eee;
border-right: 10px solid #888;
}
.intro-box {
clear: both;
width: 630px;
margin: 21px -35px 0 -30px;
background: #d6d2cf;
border-left: 10px solid #635b54;
padding: 15px 45px 16px 20px;
}
.intro-box a {
color: #635b54;
text-decoration: none;
background: url("../gfx/icon.link.gif") center right no-repeat;
padding-right: 17px;
margin-right: 3px;
}
.intro-box a:hover {
text-decoration: underline;
}
.double-column {
column-count: 2;
column-gap: 1.5em;
}
p.first {
display: inline;
}
/* document specific rules */
div#rationale a.external {
color: #888;
}
#ignore-this {
display: none;
}
.post-title {
clear: both;
margin-top: 1em;
margin-bottom: 2em;
border-top: 1px dashed #444;
padding-top: 1.4em;
line-height: 36px;
}
.post-link a {
color: #000;
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 36px;
font-weight: normal;
line-height: 36px;
text-decoration: none;
}
.post-footer {
margin-bottom: 9px;
}
.dulled {
color: #999;
font-style: italic;
}
.section-info {
padding-bottom: 1em;
border-bottom: 2px solid #544554;
margin-bottom: 1.5em;
margin-top: 1.2em;
}
.home-section-info {
margin-top: 1em;
text-align: right;
}
.right {
text-align: right;
}
.buffer {
margin-top: 6em;
}
.rss-entry { margin-bottom: 3em; }
.rss-entry .main, .feedburnerFeedBlock .main { font-size: 1.2em; padding: 25px; display: block; }
.feedburnerFeedBlock li {
list-style-type: none;
margin-bottom: 3em;
}
.feedburnerFeedBlock .headline {
display: none;
}
.section-header {
border-top: 3px solid #544554;
border-bottom: 3px solid #544554;
font-size: 2em;
text-align: center;
padding: 20px;
margin-bottom: 2em;
margin-top: 2em;
}
.index-link-info {
font-size: 0.8em;
color: #666;
}
.index-link-info a {
color: #666;
text-decoration: none;
}
.draft-article {
color: #ccc;
}
.if-time-permits {
border: 1px solid #ff6633;
padding: 4px;
color: #999;
}
.if-time-permits:before {
content: "IF TIME PERMITS";
background-color: #ff6633;
color: #fff;
padding: 5px;
margin-right: 3px;
margin-top: 3px;
}
a.button {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
}
a.button span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
}
a.button:active {
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.button:active span {
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
a.buttondown {
|
tav/oldblog
|
885c9c9e53c5ef7b03f4e8aee9f954e3f9297995
|
Removed name from the about-tav article (on request).
|
diff --git a/about-tav.txt b/about-tav.txt
index 29eb567..a9cbb7c 100644
--- a/about-tav.txt
+++ b/about-tav.txt
@@ -1,1015 +1,1015 @@
---
created: 2009-03-17, 04:03
layout: post
license: Public Domain
type: Feature
---
=========
About Tav
=========
A Brief History of Tav
~~~~~~~~~~~~~~~~~~~~~~
:Abstract:
I'm Tav, a 29 year old from London. I enjoy working on large-scale social,
economic and technological systems and have been pursuing the Espian vision
since starting my first company 11 years ago.
This is a draft, pseudo auto-biography written in a simple Q&A style. Enjoy!
.. contents:: Table of Contents
:depth: 2
:backlinks: none
Are you happy to answer personal questions?
===========================================
.. class:: sidebox
"Transparency is fundamental to trust"
Yes. I have nothing to hide and believe that transparency is fundamental to
trust. Because it lets others understand where you are coming from and your
motives are made clear.
The personal stuff is what matters. It's what drives people. What affects their
thoughts. Their actions. One might give reasoning for actions, but it is all
driven by something very personal.
For example, there was a time when I took a closed approach. Why? Not because I
believed in it. But because I was pissed off. Pissed off at an ex-collaborator
with whom I had disagreements of strategy. I didn't want him to benefit from my
work if he didn't believe in it.
There was another time when I couldn't focus on my work for months. I was heart
broken. When people mention heartache they fail to mention that it's not just a
metaphor, your heart really aches!
Feeling connected. Falling in love. Being loved back. Not being loved back.
Being warm and safe. The story of the heart defines us. And to be useful to
society it is paramount that we first understand ourselves. Then by sharing, we
let others do so too.
Who are you?
============
Entrepreneur. Musician. Engineer. Designer. Economist. Scientist. Architect.
Inventor. Activist. Producer. Hacker. Poet. Spiritual leader. Anthropologist.
Writer. I am none of these. Yet I find myself playing with a curious mix of it
all. Symbiotic engineering.
What's your name?
=================
Tav.
No, really, what's your name?
=============================
It's just Tav. No surname. Like Madonna if you will. If you mean what's the name
on my birth certificate, then it's Vageesan Sivapathasundaram. As you can
probably imagine, many school exams were finished by the time I managed to fill
in my name.
When my father kicked me out of the house he demanded that I never use his name.
What he meant was that I shouldn't use his name to ask for help from other
people.
.. class:: sidebox
"Being homeless at 17 gives you a certain outlook"
But being made homeless at 17 gives you a certain outlook. Having to sleep in a
wet park doesn't endear you to the guy responsible. So I decided to take his
wish rather literally and just abandoned my surname. Gave myself the name 'Tav'
-- a shortened form of an internet handle I'd been using, ta'veren:
"A person around whom the Wheel of Time weaves all surrounding life-threads,
perhaps all life-threads, to form a Web of Destiny" [Jordan-1990]_.
I quite liked it because the meaning was rather similar to my birth name,
Vageesan, which also means: creator, lord of knowledge, lord of speech, &c.
And as I would later find out from an excited Kabbalist at a party sometime, Tav
is also a letter of the Hebrew alphabet. It supposedly stands for truth
[Ginsburgh]_ and represents the covenant between God and his people. Or maybe it
just means a box.
Who is Tav Ino/Espian?
======================
`Saritah <http://www.saritah.com/>`_, an old housemate of mine, used to call me
"Tavino". So when sign-up forms insist on a surname, I give them "Ino". It's not
a part of my name. Just there to sate the surname requirements of silly
websites.
Likewise with "Tav Espian".
Do you suffer from schizophrenia?
=================================
Nope. At least no more than average. For example, when I was about 8, I used to
have 3 imaginary friends who controlled the various forces of life. Sadly I
haven't seen them since hitting puberty.
I did once conduct a related experiment though -- spent a few months living
multiple lives in parallel. I had keys to a number of different houses.
Introduced different aspects of myself under different names. Isolated my
behaviours into distinct characters.
.. class:: sidebox
"A gentle soul with a love for humanity"
This experiment -- whilst it nearly pushed me over into insanity -- helped me
realise my true self. Because in all the personalities I took, a certain
commonality was inescapable. A gentle soul with a love for humanity.
"If a man comes to the door of poetry untouched by the madness of the Muses,
believing that technique alone will make him a good poet, he and his sane
compositions never reach perfection, but are utterly eclipsed by the
performances of the inspired madman" -- Socrates.
When is your birthday?
======================
18th March 1982.
Where were you born?
====================
In North Middlesex Hospital, Enfield, London, UK.
Where have you lived?
=====================
In London (UK) for most of my life:
* Enfield
* Greenwich
* Plumstead
* Tooting
* Bickley
* Bromley
* Beckenham
* Orpington
* Hackney
* Finsbury Park
* Sudbury Hill
* Angel
* Liverpool Street
* Brixton
With some temporary stay in:
* Richmond
* Notting Hill
* Swiss Cottage
In Sri Lanka for 3 years:
* Kilinochi
In Tamil Nadu (India) for 2 years:
* Thirunelveli
* Chennai
In Berlin (Germany) for a year:
* Wedding
* Prenzlauer Berg
Have you had a privileged upbringing?
=====================================
I've had a mixed upbringing. Growing up on a farm/jungle in Sri Lanka. Being a
city boy in London. The quality of life I had growing up was reflective of the
ups and downs in my father's life.
He would be unemployed at times and we would live in shitholes. He would also
make more than £100k a year sometimes and we would live decently. Ups and downs.
I consider myself rather privileged to have had private schooling at Dulwich
College. But this was only possible because of a scholarship and an assisted
place. I appreciate it moreso because I've been at state schools and realise how
shit they can be.
.. class:: sidebox
"Thankful for the various opportunities life has given me"
But I am even more thankful for the various opportunities life has given me. To
have grown up under the influences of two different cultures. To have been born
and brought up in London -- in some ways, the centre of the world. To have
experienced poverty and excess.
To have experienced death at an early age and thus been able to question the
meaning of life. To have a loving mother. To have a cruel father. To not being
incapacitated in some form. To have decent-enough looks. The Universe has been
good to me.
And even the suffering I've experienced has been beneficial -- a real education
in the School of Life.
Where did you go to school?
===========================
I started at Heronsgate primary school in Greenwich. Then home schooled by my
mother whilst living in India for 2 years before joining Broadwater primary
school in Tooting. I also briefly attended Graveney's 6th form for A-level Math
classes before joining Dulwich College in 1992.
I dropped out of Dulwich in early 2000 after Leeds University gave me an
unconditional offer to do a degree in Philosophy and Economics. Unfortunately,
whilst I accepted the offer, I never bothered to turn up. Sorry Leeds!
What academic qualifications do you have?
=========================================
Nothing really. Unless you count GCSEs and A-levels -- The Autodidactic School
of Polymathy doesn't give out certifications yet.
I did 2 of my 12 GCSEs early at the age of 9 -- in Mathematics and Tamil. Did
the others at the usual age of 16. Got an A grade in all of them.
Did 8 A-levels in: Maths, Ancient History (AS), General Studies, Further Maths,
French (AS), Physic, Chemistry and English. Got the grades AAABBNUX
respectively. The last three were because I didn't bother turning up to the
exams after I got the unconditional offer for university.
I also did my SATs for entrance to US universities and think I got a perfect
score -- maybe that was only in the Maths. My memory is sketchy on that one. Got
fazed out when I realised that I couldn't afford the yearly 30k+ that
MIT/Harvard wanted.
.. class:: sidebox
"Lost interest in academia by my mid-teens"
My childhood aspirations to do a PhD by the time I was 18 were gone as I lost
interest in academia by my mid-teens. Academic qualifications seemed to simply
be an exercise in memory rather than understanding.
An example would be my Ancient Hsistory exam. I hadn't attended classes, so my
teachers predicted a D grade. The day before the exam I read a book on the
topic. So when the results arrived and I'd gotten an A grade, the Classics
department was rather surprised. Nothing more than short-term memory in action.
And whilst I've never experienced university, people often tell me it's
different. This, however, doesn't correlate with my experiences as a teacher. I
used to privately tutor undergraudate computer science students in my early
twenties. And their university education seemed to be just as focused on memory
and not on understanding.
What languages do you know?
===========================
.. class:: sidebox
"Lucky to be bilingual"
Despite my fantasies of being a polyglot, I am only fluent in two: English and
Tamil. I am familiar with some very basic French and German. A certificate
somewhere states that I should know some Japanese but I don't (at least not
anymore).
The most fun I ever had learning a language so far has been Hindi. I was 14 and
on holiday in South India for 3 months and convinced a North Indian gentleman to
teach me for a mere £30.
The deal was that I could turn up at his house any time during the day and he
would teach me. It turned out that he was just newly wed, and observing the
flirting of adults was an interesting side-experience to the learning of Hindi
and Sanskrit.
Unfortunately, like with Sinhalese and Latin, I can remember very little and
will be surprised if I recognised even a few letters from the written script
(Devanagari).
At some point though, I'd like to learn these languages properly -- along with
Russian, Chinese (Mandarin), Arabic, Greek and Spanish. I consider myself very
lucky to be bilingual. If you have kids, teach them many languages before they
reach the age of 5. It really helps.
What inspired the Espian vision?
================================
The death of my grandmother [Palmer-2004]_. To understand this, you need to go
back to the start of my life. 25 days old. Beginning my jetset lifestyle. My
mother and I were on the way to Sri Lanka.
Her father was dying back home. Lung cancer. When he passed away two months
later, my grandmother was left all alone. So my mother decided to leave me there
with her and returned to England.
And that is how I spent my first years growing up. Thinking that my grandmother
was my mother. My mother eventually came back for me. And I met my parents for
the first time a few months before my fourth birthday.
A year and a bit later, I had a little sister and we were about to emigrate to
the USA. My father was going to Berkeley. But news came that my grandmother had
fallen ill whilst visiting friends and family in India. Bone cancer.
I was rather adamant that we go to India. At least for me to go. Eventually my
mother, sister and I went to India. My grandmother had her leg amputated. The
cancer had stopped spreading. I nursed her back to health.
But then on October 20th 1988, she had a heart attack. My mother had been out
shopping. I called for help from the neighbours. I prayed to the God of Death to
spare her. But to no avail. Blood dripped from her nose. Her body was ice cold.
As the eldest grandson, I had to alight her funeral pyre. I refused. I wanted to
freeze her and preserve her until death could be reversed. You have to do this
everyone said. So I did.
A few days later I snapped. I was 6. This was my first experience of death. I
had grown up under shell attacks in Sri Lanka and seen bloodied, mutilated war
victims, but had never seen death directly. I couldn't understand why we lived.
What is the point of life if all that you get at the end is death?
The family across the road were Christian. I asked them. I asked their priest.
The neighbours to the right were Muslim. I asked them. I asked their imam. I
asked the Jains. The Saivas. The Hindus. The Sikhs. The Buddhists.
I got similar answers. But none were satisfactory. Made me realise that there is
very little difference in the real teachings of the various faiths. But I still
didn't have an answer.
I wanted to go meditate in the mountains. Maybe I'll reach enlightenment like
Buddha. Wander the wilderness like Jesus. My parents talked me out of this. So I
kept on asking questions of any adult that would give me their time.
Eventually I came to the conclusion that life has no meaning. There is no
ultimate truth or purpose. God lies within. And the only worthy goal in life is
to be happy in the moment.
But then I looked around. We were living in a village in southern India. During
the time following my grandma's death, the narcissicism of childhood had been
replaced by an awareness of the world.
And everywhere I looked I saw needless suffering. I compared the life in India
to life in England. The differences in the material quality of life. The
wastefulness and excess where others barely survived. The differences in the
spiritual quality of life. How, despite not having much, the poor seemed
happier.
I was also able to see politicians in action. The ideals of democracy thrown
aside as people were bribed into voting for specific parties. I tried to
understand why people would destroy the chances of a collective better future
for a slightly better today.
Eventually I came to the realisation that one's basic needs need to be met.
One's family to not be starving. Otherwise people were willing to screw each
other over for short term gain.
And if I were to be happy in my life and not be screwed over by others then I
needed to ensure that others had their needs taken care of. And if everyone had
the potential to be happy, then I could be happy.
And thus I discovered my life purpose. By adopting the entire world as my
family. The Espian vision was born.
How do you get your ideas?
==========================
Most of my ideas are informed and inspired from experiences that life puts me
through. And, quite often, they reach clarity as I am mid-speech discussing such
situations. One example I'll elaborate here is Pedipeace.
It was inspired by events that took place during a March 2003 protest as War
started in Iraq. As I was heading out to join some friends from school, I
couldn't find my belt. There was a corded PC microphone on the table. I tried it
out as a belt. It worked, but it looked rather silly so I took it off.
I caught up with my friends at Westminter. One of them had just been to Morocco.
He had a present for me. A djellaba. I wore the robe over my t-shirt. A few
hours later I had been adorned further.
.. image:: http://cloud.github.com/downloads/tav/plexnet/gfx.henry-21st-birthday.jpg
:class: float-right-aligned
:width: 302
:height: 204
My scarf was being used as a bandana to hold together a wreath of daffodils
adorning my head. I was carrying a big stick -- the leftovers of an anti-war
placard. I had used it earlier to make some music on some traffic cones and beer
bottles.
The protest continued as usual. The BBC interviewed me for looking strange. All
in all, it had been a lovely afternoon walk with friends. Except for the
shouting of "No War" constantly, it demonstrated how lovely London would be if
it was pedestrianised.
...
What's the story of the Wobbly Bridge?
======================================
Time. 2am. Place. The wobbly (millennium) bridge.
After entertaining myself running around the trees, I pull myself up onto the
wobbly bridge and gently skip along. My heart beats slightly faster as I see the
river flow underneath me. The thrill of being so high. The thrill of falling.
Clumsily pull myself over the side, straddle a beam and sit. Watch the river
flow. I lean back. Feel the aura of the full moon. The wind blows. So soft. But
with a sharpness that makes me alert. Aware. Lyrics come to mind "London calling
to the underworld... I live by the river!"
I get up to climb back over. I almost slip. Heart beats. Back on the wobbly.
Start to skip along again. In front of me, a giant circle. A perfect circle. A
circle of objects. I look around -- no-one to be seen. A present from an
anonymous stranger.
I delight in the find and start exploring. A mobile phone. A paintbrush. A block
of wood. A pressure valve. A blue tin (labelled russian caviar). I look inside.
Some round stones. Another block of wood. Too many objects to be mentioned here.
The wind takes on a cold edge, but the present makes me very warm.
And in the middle of this perfect circle, at the exact middle of the bridge
(both lengthways and sideways), a grey and white toy bunny with a fat blue
alkaline battery. I ponder upon the present for a long time. Is there a clever
message?
For some reason, the words "beautiful girl lovely dress" sample across my mind's
ear. A cyclist zooms by. I call back at him. He stops. He turns. He approaches
cautiously. I ask him what he thinks. Maybe a clock he says. Doesn't have
anything interesting to say. I let him go.
I explore the present further. Time goes by. I feel inspired. Thoughts provoked.
Another walks by. I wave. We speak. I can sense the samani in this creature. We
will be good friends.
I bid the present goodbye, and decide to spend the remaining hours of the
morning exploring the mind of this new found friend. And fun hours they were.
What are your deepest values?
=============================
.. class:: sidebox
"Truth, justice, honour, loyalty and love"
Truth, justice, honour, loyalty and love. Sure, they might be based on the Code
of Thundera, but they are my deepest values. And whilst I occasionally slip up,
I constantly strive to abide by them. This constant struggle is what makes life
interesting.
And, although not a value, another major driving force of my life is best
described in `Fight Club <http://www.imdb.com/title/tt0137523/>`_: "This is your
life and it is ending one minute at a time". That is, life is short and one
should make the best of it. Carpe diem!
Have you ever lied?
===================
Yes, a handful of times. I'm also terrible at lying -- you can see it from a
mile off!
I do however have two habits which are far from my self-image as a Speaker of
Truth. One is that I occasionally pretend to be ignorant and ask others to
explain things to me. This can be useful to both get a feel for what the other
person actually understands as well as a way to stroke their egos.
I don't actually see an issue with this -- as far as I can see it is beneficial
social lubrication. However I did once hear about Tony Blair getting lambasted
for similar behaviour, so perhaps there is something sinister that I am missing?
-The other habit of mine is related to what my old business partner Ade Thomas
-from green.tv refers to as "concentric circles of bullshit". It could probably
-be best understood by looking at how `green.tv <http://www.green.tv/>`_ came
-into existence.
+The other habit of mine is related to what an old business partner of mine
+refers to as "concentric circles of bullshit". It could probably be best
+understood by looking at how `green.tv <http://www.green.tv/>`_ came into
+existence.
It started with the idea being pitched to UNEP, Greenpeace and a few others.
This was before YouTube had become mainstream and they didn't really see the
value of an online video channel dedicated to environmental issues. Or had even
heard of podcasts.
They weren't happy to provide any resources, but were okay enough for their
names to be used as partners. This was all it took for the concentric circles of
bullshit to go into action!
It became easier to go round to a number of other organisations and say, "Hey,
UNEP and Greenpeace are backing us, would you like to come on board?". A Paragon
of Truth would never have been happy with such half-truths but it proved
effective.
By the time of launch, the circle had come back to the original parties who were
now willing to provide a lot of support since so many others were on board!
One of the Directors of UNEP was even willing to claim to have been the
visionary behind the idea in the first place and was more than happy to parade
the accomplishment in front of other UN agencies.
Now it worked out really well for everyone involved in green.tv, but playing
with such half-truths can sometimes have painful consequences. However, such
hustling is unfortunately a necessary trait sometimes when building businesses.
If anyone can tell me how to achieve the same results without it, I'd be happy
to learn.
Have you ever stolen anything?
==============================
Sadly, yes. Five times.
The first time, I stole 50p from my mother's coat pocket. I was 9 and wanted to
buy some cola bottles (they used to be just 1p each back then!). I felt guilty
about this for weeks after and eventually confessed.
The second time, I helped some fellow homeless people pick up scraps of metal
from a construction site. The metal got sold at a dodgy garage somewhere and
paid for a warm night and a drink. Sorry construction company!
The third time, I had done some work for a guy. Did it exactly as he wanted. But
he claimed it wasn't and refused to pay up. So I convinced him to give me the
money as a loan and have sadly yet to repay it. Sorry John!
I shop-lifted some food from Tesco once when I was one of the billion odd living
on less than $2 a day. So I paid for some of the items and walked out with
several more in the bag.
The final time, I stole a passport sized photo of an ex-girlfriend after we
split up. This is my confession.
Have you ever been disloyal?
============================
Sadly, twice. Once for real and the other time in my head. Both, unsurprisingly,
involved women.
The first time, a friend asked if his ex could stay at my place -- they were
going through a separation. Things went great for a while. She was extremely
lovely and I enjoyed having her around the place.
But once she started making advances, my value system was challenged. Torn
between my loyalty to my friend and my attraction to her, I am sorry to say that
I ended up giving in and we ended up having a fling.
The second time, a friend and his girl of many years had broken up. It so
happened that she was also the sister of another friend of mine. And so we ended
up spending a fair bit of time together.
During this time I gradually fell for her. Thankfully I am pleased to say that I
never acted on my feelings for her, but I am still not proud of having had those
feelings in the first place.
Loyalty is very important to me and I am truly sorry for having let down my
friends on those two occasions.
Are you a bigot?
================
.. class:: sidebox
"Much to be gained in life when one keeps an open mind"
Whilst I have no compunctions about political incorrectness and will tease the
French and the Obese, I am not a bigot. It is hard to be so when you grow up in
a truly diverse city like London.
As a further testament, my various lovers have come from a variety of religious
and national backgrounds -- Bolivia, England, Germany, Greece, India, Lithuania,
New Zealand, Singapore, St. Lucia, Vietnam...
Ditto with my various flatmates/colleagues -- Australia, Austria, Brazil,
Canada, China, France, Gambia, Japan, Netherlands, Norway, Sweden, USA, &c.
In contrast my dear father is a homophobic racist. In fact, I would go as far to
say that, in general, immigrants tend to be more bigoted than "natives". Whilst
unjustifiable, this is in some ways understandable -- a reflection of their
insecurity and vulnerability.
It's when it gets passed down to their children that I have a problem with it.
For example, I was at my sister's 21st birthday. It was at a club down near
Soho. And I was rather shocked as I walked in.
Why? Because with the exception of about 5 people, everyone else there was
brown. Not that I'm complaining. Asian girls -- like their South American
counterparts -- tend to be rather pleasant on the eyes.
But when many of these people were speaking to each other in Gujarati, Tamil,
Hindi, &c., I began to wonder. And after speaking to a few of them, my doubts
were confirmed. Most of these people rarely mixed with people outside of these
groups.
Now, being part of an ethnic community is not a bad thing. I would say it's a
great thing. But doing so to the exclusion of mixing with other groups is
definitely harmful. Especially in the context of London where you have so much
opportunity and no excuse.
Why? Because mixing with the same type of people doesn't help to broaden your
mind. You need to be exposed to unfamiliar and sometimes uncomfortable
perspectives. That's essential to nurturing a healthy understanding of the world
around you.
Some people might misinterpret this as being racist to my "own kind". I've even
been called coconut twice -- brown on the outside, white on the inside. I'm
neither white nor brown. I'm a multi-coloured kaleidoscope. A human being. An
Espian.
I want to get past the useless social ghettos that repeatedly form. These serve
no purpose except to create needless boundaries between otherwise loving beings.
And, whilst rare, I've experienced bigotry from "natives" too.
The most surreal one was a pub in east London. I had popped in whilst waiting
for a girlfriend. It was eerily filled with just white people. Even posh venues
have a token coloured individual.
All eyes turned to me as I put my coat down and approached the bar. One of the
barmaids intersected me and escorted me to the door. They were closing. Right.
Now, again, I have nothing with people mixing with their "own". Just don't do it
exclusively! Say no to social ghettos.
Anyways, seeing the bigotry of others whilst growing up had been a good enough
lesson in the pointlessness of it. There is so much to be gained in life when
one keeps an open mind.
One advice I'd like to share is to not suspect bigotry of others. My father
would interpret any insult or rejection as racial discrimination. My gay friends
would express gay pride a bit too much to overcompensate for the oppression they
felt others had towards them.
Sure, racism and oppression exist. There is a bigot on every street. But don't
live in fear of it. Don't suspect it. Just be yourself. And if that is a true
being with good intentions, others will sense that and react positively. No
matter what.
As for the few that don't. So what? They are probably old and set in their ways.
They will die off soon enough. Oh, that reminds me of another thing. Political
fucking correctness.
I was on a train once. Befriended this guy sitting in the same carriage. We'd
been having an hour long conversation when I asked him how life was as a
cripple. He went berserk.
Now I hadn't meant to insult him in any way. That should have been clear from
the tone of my voice. And he was a cripple. At least by any dictionary
definition that I've seen. But, no. He was a disabled something or other.
What the fuck? It seems to me that some people deal with their shortcomings by
hiding it behind fancy politically correct phrases. No, I'm not blind. I'm just
visually impaired. What the fuck? Deal with reality. Shit happens. Just be
yourself.
Are you gay?
============
No. However I have had two experiences relating to the issue. They took place
just over a decade apart and what surprises me is how similar both scenarios
were.
The first took place when I was 16. We were staying over at a family friend's
house in India and sometime in the early hours of one morning I woke to find one
of their sons sucking my cock.
My initial thought was to respond with physical violence, but given the matter
of his teeth around my most delicate part, I instead controlled myself, withdrew
Mister Helmet from his grasp and explained my lack of interest.
He took the rejection fairly well and went away. To this day I have no idea why
he thought such behaviour would be okay. What baffles me even more is that a
similar incident took place 10 years later!
This time it was a friend that I'd made at a party a few weeks prior. I had
liked his energy and invited him to one of my house parties. He had ended up
crashing in my room towards the end of the party.
It was not uncommon to go back to my room after a party and find people passed
out. So I got into my bed and went to sleep. I gradually woke up a little while
later to find him giving me a blowjob.
I couldn't believe that this was happening again. And perhaps because I was
still drunk or perhaps because earlier that day I'd had a break up with two of
the girls that I'd loved, but by that point I really didn't care.
So, this time, I let the guy suck me off. At one point he even moved around
wanting me to reciprocate -- I pushed him away and he seemed to get the hint.
And once I'd ejaculated, he put his clothes back on and left.
Now, when I have recounted what had happened to others, some have suggested that
I might therefore have bi-tendencies. Whilst this might be true, I have never
fantasised about having sex with a guy or been turned on by it, so I fail to see
how.
In fact, on that particular night, it really didn't matter that it was a guy. It
could have just as well have been a `Fleshlight sex toy
<http://en.wikipedia.org/wiki/Fleshlight>`_ for all I cared. Pure physical
release and nothing more.
So there you go. I am certainly not homophobic but I have no desire for romantic
or sexual relationships with guys either.
Are you violent?
================
If you ask everyone who knows me, they will attest that I am one of the calmest
people you'll ever meet. But, like everyone, I've had my moments.
I don't appreciate violent environments, but I am also comfortable with dealing
with violent individuals. As a consequence I've ended up in various minor fights
over the years. However, in a few incidents I momentarily lost it and hit women.
One time I punched my little sister several times in the stomach. Unfortunately
we weren't kids then. I had been staying with my family for a few weeks and my
mother and sister were making each other quite miserable.
Unfortunately I intervened and it escalated to a point where I momentarily lost
it. And to make things worse, years later, I repeated my shameful loss of
control as an argument with a girlfriend heated up and I hit her.
I can say how she was the aggressor and how she almost destroyed years of my
work, but truth is, I should have maintained control. Alas, there is no rewind
button in life and even a momentary loss of control can't be excused.
At least to make up for my shame, I spent the night in Brixton police station
and got given a caution. She had called the police and despite her not wanting
to press any charges, it seems the police had to take the guy into custody.
Having called the police many times when my father was being excessively violent
towards my mother, I was actually very appreciative of the police action in this
case. However I wasn't too happy with the caution.
Now, a caution isn't a criminal conviction but I felt it to be unjust. She was
clearly the aggressor and whilst I was also in the wrong, I felt the
discrimination based on my sex to be thoroughly unfair.
And to make matters worse, it turns out that if I had simply refused to answer
the questions in the police interview, then I would have walked away with no
caution, but since I had been open and honest, I'd fucked myself.
Justice should be contextual and people should be encouraged to be open and
honest. In any case, like others before me [Gandhi-1927]_, I am not a violent
individual, but I have sadly had moments where I've lost control.
Are you a vegetarian?
=====================
I used to be. Fervently. For 8 years of my life. From August 1998 till
December 2006. I had two rational reasons for my choice:
1. By eating lower down the food chain, it is more efficient and a larger global
population could be sustained.
2. Life is beautiful. And our fellow creatures shouldn't live purely for our
sake.
But, whilst I believe in the above, I also love the taste of meat and think that
it is natural to be a meat-eater. So the real reason I gave up meat was because
of a girl. She was a vegetarian.
She was my first love and though she had never asked me to give up meat, I did
so willingly. And the fact that I never touched meat was a sign of my commitment
to her.
But when we broke up in December 2006, I couldn't decide whether I wanted to
stay being a vegetarian or go back to eating meat. So I flipped a coin and am
now a meat-eater again.
Have you taken drugs?
=====================
Yes. I believe that one should experience as much of what life offers. And not
suffering from an addictive personality (nicotine excepted), I have had the
luxury of trying out various drugs.
.. class:: sidebox
"Hallucinogens helped with my understanding of myself and life"
My favourites have been LSD (Acid), MDMA and magic mushrooms. MDMA truly can be
happiness in a packet. And never having had a bad trip, hallucinogens have truly
helped with my understanding of myself and life around me.
Actually that not having had a bad trip thing isn't quite true. I was at a rave
once tripping my balls off on acid when two girls decided to stalk me. The two
witches as I saw them. It was a pleasant trip after I managed to get rid of
them.
Drugs like cocaine generally have very little effect on me. They just give me a
cold the next day. Some of the designer drugs have been fun -- though their
effects seem to diminish on repeat usage.
And, as for marijuana, whilst I've had many pleasant experiences on it, it is
near the bottom of my drugs list -- along with Ketamine. The reason for this is
because dope makes you comfortable with not doing anything.
I spent a good six months of my life doing nothing but getting stoned every day.
A friend of mine was a total pothead and he would start rolling the next joint
by the time I was finishing smoking the last one. And I really don't enjoy not
being productive.
Have you ever paid for sex?
===========================
No. But I have had a few interesting experiences with prostitutes.
Soho. Crack den
...
Have you been hustled?
======================
Yes, four times.
The first time, I was trying to score some brown (powdered heroin) from a pair
of street dealers. I gave one of them some cash and he owed me a fiver back. He
claimed to not have any change and said he'd pop down to the local shop.
...
Do you have a criminal record?
==============================
No.
What do you have against the Vatican City?
==========================================
Let me be clear that I have nothing against the Vatican. It is the Vatican City
that I have problems with. Specifically, the Gendarmeria -- the police force.
To understand this, we need to go back to one summer night in 2005. I had gone
to Rome for a day meeting. The meeting had gone well and my flight back was
early the next morning. So instead of being cooped up in my hotel room, I
decided to spend the night checking out Rome.
...
How much debt do you have?
==========================
I have lived most of my life assuming a gift economy of sorts. So my actual
legal debt is a £14k loan to Halifax which never seems to go down. However, I
owe just under £200k to friends and family.
The bulk of that is to the investors of my first company. The company went
bankrupt around my 19th birthday and I decided that the honourable thing would
be to assume their lost investment as debt owed to them from me personally.
Whilst this is no doubt a stupid stance to take as legally I owe them nothing
and they knowingly took the risk, I felt that they invested because they
believed in me and therefore it was my responsibility.
However I haven't felt the same sense of duty when dealing with large
corporations and have walked away from an outstanding mobile phone bill with
Vodafone and overdrafts with HSBC and Natwest. Sorry, I was poor.
Besides what I feel I owe to the investors of my first company, I also feel
guilty for a minor debt of around â¬50 owed to an Indonesian restaurant. It came
about whilst I was a starving artist in Berlin.
I didn't have any money, so I made a deal with the local Turkish and Indonesian
restaurants -- they'd feed me daily and when I got some money, I'd settle my
debt. After a few months of this I eventually settled my debt and all was good.
I asked the Indonesian place if they'd continue the deal and they kindly agreed.
These people were lovely. The owner, Surya, and his wife took great care of me.
However, about a week or so later, tragedy struck.
An uncle of mine died and my mother paid for a flight so that I could get back
for the funeral. Around the same time I was moving from one part of Berlin to
another. And, amidst all the commotion, I completely forgot to pay them.
It wasn't intentional and I'd really like to see the debt paid.
What jobs have you had?
=======================
I have worked for myself (the Espian vision) most of my life. So have had little
chance to have a "normal job".
My first job was working for an uncle of mine in his post-office/corner-shop in
Walthamstow. It was also the longest job I've had (a whole month!). I slept on
the store floor and during occasional bouts of insomnia re-organised the shop
and somehow managed to double the revenue.
My second longest job was as a street cleaner for Islington council. This was
perhaps the best job I've had. I got to get up early in the morning. And work
was finished by noon meaning that I had the whole day left.
Unfortunately, after 2 weeks, my ganger called me in and laid me off. I had been
spending too much time cleaning each and every street. I was laid off for being
a perfectionist. Heh.
Other jobs include being an art salesman, facilitator, etc. The funniest was
being an extra for a Sky Sports rugby ad -- imagine that, skinny me being
portrayed as a rugby player -- friends called up in disbelief after seeing the
ad.
And, finally, there have been a dozen odd temp jobs which I occassionally tried
for a day or two before walking out at the incompetency of those who were meant
to be my managers.
What is the worst invention ever?
=================================
Alarm clocks.
The wooshing sound of deadlines as they fly past.
...
What have you done with your life?
==================================
A lot of different things. Mainly centered around the Espian vision.
...
What do you want to do with rest of your life?
==============================================
A lot. Some of the highlights include:
* Empowering people by creating a better social-economic infrastructure.
* Creating a decentralised social platform. Ampify.
* Crafting a multi-genre musical instrument that inspires people. Jintra.
* Building a city using social architecture and a global underground tube
network. Zygote & Xetre.
* Creating a movie of epic proportions. Gaia.
* Travelling to Mars. Mangala.
* Utilising advances in molecular biology to enable a higher quality of life for
all. Electrophyll & Geren.
* Nurturing the cultural and natural commons for the benefit of all. Espia.
* Having a daughter. Hiroko.
Most likely I'll die of something like lung cancer before most of this happens.
So I also want to make the most of every moment that I am alive. Bringing
pleasure to myself and as much of humanity as possible.
What has been your most self-empowering moment yet?
===================================================
It took place sometime during the summer of 2004.
...
What inspires you?
==================
.. image:: http://cloud.github.com/downloads/tav/plexnet/gfx.saritah.jpg
:width: 352
:height: 259
:align: center
:class: float-right
| Get up and get going
| You've got nothing to lose
| Let it out, let it through
| There's nothing that you can't do
|
| What you want, get up and get
| Your future hasn't happened yet
| It is up to you to manifest
|
| Participation -- fundamental to creation
| You will not reach your destiny
|
tav/oldblog
|
97d9b0d451cade48370bd682aa7c0dca4816f722
|
Added an article on why Bitcoin will fail.
|
diff --git a/why-bitcoin-will-fail-as-a-currency.txt b/why-bitcoin-will-fail-as-a-currency.txt
new file mode 100644
index 0000000..b6d8fb7
--- /dev/null
+++ b/why-bitcoin-will-fail-as-a-currency.txt
@@ -0,0 +1,208 @@
+---
+created: 2011-06-07, 13:54
+layout: post
+license: Public Domain
+---
+
+===================================
+Why Bitcoin Will Fail As A Currency
+===================================
+
+`Bitcoin mania <http://www.google.com/trends?q=bitcoin>`_ has now reached such
+worrying heights that some people are even putting `all of their savings into it
+<http://falkvinge.net/2011/05/29/why-im-putting-all-my-savings-into-bitcoin/>`_.
+Unfortunately, Bitcoin is fundamentally flawed and by the time you finish
+reading this article, I hope you will agree with me.
+
+For those of you not familiar with `Bitcoin <http://www.bitcoin.org/>`_, it is
+often described as a "peer-to-peer currency". This geeky video is sorta
+informative:
+
+.. raw:: html
+
+ <div class="center">
+ <iframe width="560" height="349" src="http://www.youtube.com/embed/XQPSwA2Itbs?start=2516" frameborder="0" allowfullscreen></iframe>
+ </div>
+
+There are a lot of good reasons to be excited about the `design behind Bitcoin
+<http://www.bitcoin.org/bitcoin.pdf>`_ -- it enables secure transactions in a
+transparent manner and doesn't require centralised authorities. It really is
+genius and I look forward to seeing it used in other domains.
+
+However, this does not make Bitcoin a suitable currency system.
+
+.. more
+
+**Why?**
+
+Because, by design, there will never be more than `21 million Bitcoins
+<https://en.bitcoin.it/wiki/FAQ#How_are_new_Bitcoins_created?>`_ in existence.
+And thanks to hoarding and attrition, we can be sure that it will eventually
+serve as nothing more than as a `collector's item
+<http://en.wikipedia.org/wiki/Collectable>`_.
+
+**Bitcoin Hoarding**
+
+First, let's take a look at why Bitcoin encourages hoarding. As I write this,
+the `current total <http://blockexplorer.com/q/totalbc>`_ of Bitcoins mined so
+far is just short of 6.5 million:
+
+.. syntax:: pycon
+
+ >>> bitcoin.currentTotal()
+ 6459900
+
+That is, nearly a third of all Bitcoins that could ever exist are already
+sitting on people's computers. Now let's assume for a moment that Bitcoin really
+is useful and in the next decade grows to an `economy the size of Mexico
+<http://en.wikipedia.org/wiki/Economy_of_Mexico>`_, i.e. a trillion dollars.
+
+In this context, if you had 50 Bitcoins they would be worth:
+
+.. syntax:: pycon
+
+ >>> (50. / 21000000) * 1000000000000
+ 2380952.3809523806
+
+That is, 50 Bitcoins would be worth over 2 million dollars!! Knowing this,
+unless you were super desperate, would you really spend those Bitcoins today?
+
+In the early days, when Bitcoin was just a fun experiment, it might have made
+sense to spend it. But given that people are `now willing <https://mtgox.com/>`_
+to `accept it as a currency <https://en.bitcoin.it/wiki/Trade>`_, you would be
+an idiot not to hoard it.
+
+And, unlike currencies `backed by gold
+<http://en.wikipedia.org/wiki/Gold_standard>`_ or oil, where there is always the
+chance of someone discovering new gold mines or `oil fields
+<http://www.ogj.com/index/article-display/8070349727/articles/oil-gas-journal/exploration-development-2/area-drilling/20100/june-2011/uganda_-tullow_wells.html>`_,
+you know for certain that no-one will ever be able to dilute your share of the
+total Bitcoin.
+
+Now, despite the hoarders, there will still be an initial spike in the demand
+for Bitcoins due to:
+
+* Non-hoarders experimenting with the system and unwittingly increasing the
+ value of the Bitcoins held by the hoarders.
+
+* Greedy hoarders trying to buy up as much Bitcoins as they can so as to
+ increase the size of their potential future wealth.
+
+* Scammers manipulating the market with trades so as to make a quick buck from
+ `greater fools <http://en.wikipedia.org/wiki/Greater_fool_theory>`_ before it
+ all comes crashing down.
+
+Unfortunately it won't last long. For starters, the non-hoarders (the actual
+spenders) will gradually discover that hoarding is the best strategy for
+maximising the value of their Bitcoins -- causing them to either abandon the
+system or start hoarding themselves.
+
+It would also become increasingly apparent that the majority are hoarding and
+that only a `fraction of Bitcoins are in actual circulation
+<https://forum.bitcoin.org/index.php?topic=9456.0>`_. At this point, it is
+effectively game over for Bitcoin as a currency. An economy really can't
+function if nobody spends any money!!
+
+Since there will be a slow trickle of new users and cautious hoarders gradually
+dumping some of their Bitcoins, I doubt the Bitcoin economy will come to a total
+standstill anytime soon. But there is no doubt that the majority of the activity
+will be driven by speculation.
+
+It should hopefully now be obvious that Bitcoin is simply a store of speculative
+value. In some ways, it's a lot like `publicly traded shares
+<http://en.wikipedia.org/wiki/Share_(finance)>`_. But it's worse, because at
+least with most shares you get a share of the underlying corporate assets and
+profits.
+
+Also, unlike shares, where you can generally expect recurring `speculative
+bubbles <http://en.wikipedia.org/wiki/Economic_bubble>`_, Bitcoin is not
+impacted in positive ways by underlying conditions, e.g. corporate acquisitions,
+new share issues, growing profits, etc. Thus the capacity for multiple Bitcoin
+bubbles is extremely low.
+
+If anything, potential changes in external factors pretty much all lead to a
+negative impact for Bitcoin speculators, e.g. financial regulation,
+technological breakthroughs, forked block chains, etc.
+
+**Bitcoin Attrition**
+
+The effect of hoarding is made worse by the inevitable attrition of the number
+of available Bitcoins. That is, as time goes by, there will be fewer Bitcoins
+available in proportion to the total number of Bitcoins.
+
+This happens for a variety of reasons:
+
+* Many users, especially early-adopters, having experimented with Bitcoin and
+ generated some coins, have then just forgotten about it.
+
+* You can't access your Bitcoins unless you have your private keys backed up
+ somewhere. Hundreds of people have failed to backup their wallets and have
+ lost these keys permanently.
+
+* Technical issues in how the client generated keys has led to users losing
+ Bitcoins even when they tried to backup properly, e.g. `these
+ <http://forum.bitcoin.org/index.php?topic=11104.0>`_ `two
+ <http://forum.bitcoin.org/index.php?topic=782.0>`_ have each lost what would
+ today be worth about $130k and $160k due to technical glitches. Ouch!
+
+If it were possible to determine it, I would be willing to bet that over a sixth
+of the Bitcoins mined thus far are already not accessible. In our hypothetical
+scenario above, that would translate to over 50 billion dollars worth that has
+simply been "lost".
+
+As time goes by, this figure is only guaranteed to increase. And since we can
+safely assume that hoarders will be a lot more careful than the experimenters,
+most of the attrition will likely come from the actual spenders in the economy.
+
+Thus, limiting the actual number of Bitcoins in active circulation even further!
+I could go on, but I hope the point is relatively clear. Hoarding and attrition
+make Bitcoin unsuitable as a currency. Now, let's look at some
+counter-arguments.
+
+**What about creating new block chains without the 21 million coin limit?**
+
+Yes, you could create new block chains, EuroCoin, ChinaCoin, etc. However, this
+would be not be fixing the problem with Bitcoin in any way. You would simply be
+introducing competing alternative systems which may or may not fix the
+fundamental issue.
+
+**What about extending the Bitcoin client to keep on issuing new Bitcoins?**
+
+I don't think you could keep on calling this Bitcoin. For starters, it violates
+what most people understand as Bitcoin -- that it is totally decentralised and
+cannot be controlled by any one party.
+
+By imposing such a fundamental change, you would be violating the core
+assumptions made by those who have invested in Bitcoins. I doubt most of the
+anti-gov folk who seem to have taken to Bitcoin would be interested in having
+such changes dictated to them.
+
+**What about using consensus to change the protocol?**
+
+This is super easy to say and almost impossible to achieve. How would you
+achieve this consensus? Would it be majority/mob rule? By lottery? What about
+those who disagree with the result? Who decides on the process?
+
+I fear that the opportunity to fix this has long since gone. If anything, future
+decentralised currency designers should take this as a lesson to specify, ahead
+of time, a process to use in order to make protocol changes.
+
+That way, beneficial changes can be made without violating any implicit
+assumptions that people might have made.
+
+**Conclusion**
+
+Bitcoin is not a viable currency. It is a store of speculative value -- much
+like investing in stamps, comic books and vintage shoes. The fixed limit of the
+number of Bitcoins is subject to attrition and encourages hoarding which will
+inevitably lead to mainly speculative activity.
+
+Whilst Bitcoin is a perfectly viable speculative instrument, it will be far too
+volatile to serve as a medium of exchange. I would like to call upon the Bitcoin
+community to stop referring to it as a digital currency. This is misleading and
+harmful.
+
+Finally, forgive me if I haven't been clear enough with any of the explanations
+and do let me know what you think.
+
+-- Thanks, tav
|
tav/oldblog
|
d975a6b4d6f14b6065c2b81d1cbf2663810c6490
|
Fixed some errors in the about tav article.
|
diff --git a/about-tav.txt b/about-tav.txt
index f04e7e0..29eb567 100644
--- a/about-tav.txt
+++ b/about-tav.txt
@@ -1,1450 +1,1451 @@
---
created: 2009-03-17, 04:03
layout: post
license: Public Domain
type: Feature
---
=========
About Tav
=========
A Brief History of Tav
~~~~~~~~~~~~~~~~~~~~~~
:Abstract:
- I'm Tav, a 28 year old from London. I enjoy working on large-scale social,
+ I'm Tav, a 29 year old from London. I enjoy working on large-scale social,
economic and technological systems and have been pursuing the Espian vision
since starting my first company 11 years ago.
This is a draft, pseudo auto-biography written in a simple Q&A style. Enjoy!
.. contents:: Table of Contents
:depth: 2
:backlinks: none
Are you happy to answer personal questions?
===========================================
.. class:: sidebox
"Transparency is fundamental to trust"
Yes. I have nothing to hide and believe that transparency is fundamental to
trust. Because it lets others understand where you are coming from and your
motives are made clear.
The personal stuff is what matters. It's what drives people. What affects their
thoughts. Their actions. One might give reasoning for actions, but it is all
driven by something very personal.
For example, there was a time when I took a closed approach. Why? Not because I
believed in it. But because I was pissed off. Pissed off at an ex-collaborator
with whom I had disagreements of strategy. I didn't want him to benefit from my
work if he didn't believe in it.
There was another time when I couldn't focus on my work for months. I was heart
broken. When people mention heartache they fail to mention that it's not just a
metaphor, your heart really aches!
Feeling connected. Falling in love. Being loved back. Not being loved back.
Being warm and safe. The story of the heart defines us. And to be useful to
society it is paramount that we first understand ourselves. Then by sharing, we
let others do so too.
Who are you?
============
Entrepreneur. Musician. Engineer. Designer. Economist. Scientist. Architect.
Inventor. Activist. Producer. Hacker. Poet. Spiritual leader. Anthropologist.
Writer. I am none of these. Yet I find myself playing with a curious mix of it
all. Symbiotic engineering.
What's your name?
=================
Tav.
No, really, what's your name?
=============================
It's just Tav. No surname. Like Madonna if you will. If you mean what's the name
on my birth certificate, then it's Vageesan Sivapathasundaram. As you can
probably imagine, many school exams were finished by the time I managed to fill
in my name.
When my father kicked me out of the house he demanded that I never use his name.
What he meant was that I shouldn't use his name to ask for help from other
people.
.. class:: sidebox
"Being homeless at 17 gives you a certain outlook"
But being made homeless at 17 gives you a certain outlook. Having to sleep in a
wet park doesn't endear you to the guy responsible. So I decided to take his
wish rather literally and just abandoned my surname. Gave myself the name 'Tav'
-- a shortened form of an internet handle I'd been using, ta'veren:
"A person around whom the Wheel of Time weaves all surrounding life-threads,
perhaps all life-threads, to form a Web of Destiny" [Jordan-1990]_.
I quite liked it because the meaning was rather similar to my birth name,
Vageesan, which also means: creator, lord of knowledge, lord of speech, &c.
And as I would later find out from an excited Kabbalist at a party sometime, Tav
is also a letter of the Hebrew alphabet. It supposedly stands for truth
[Ginsburgh]_ and represents the covenant between God and his people. Or maybe it
just means a box.
Who is Tav Ino/Espian?
======================
`Saritah <http://www.saritah.com/>`_, an old housemate of mine, used to call me
"Tavino". So when sign-up forms insist on a surname, I give them "Ino". It's not
a part of my name. Just there to sate the surname requirements of silly
websites.
Likewise with "Tav Espian".
Do you suffer from schizophrenia?
=================================
Nope. At least no more than average. For example, when I was about 8, I used to
have 3 imaginary friends who controlled the various forces of life. Sadly I
haven't seen them since hitting puberty.
I did once conduct a related experiment though -- spent a few months living
multiple lives in parallel. I had keys to a number of different houses.
Introduced different aspects of myself under different names. Isolated my
behaviours into distinct characters.
.. class:: sidebox
"A gentle soul with a love for humanity"
This experiment -- whilst it nearly pushed me over into insanity -- helped me
realise my true self. Because in all the personalities I took, a certain
commonality was inescapable. A gentle soul with a love for humanity.
"If a man comes to the door of poetry untouched by the madness of the Muses,
believing that technique alone will make him a good poet, he and his sane
compositions never reach perfection, but are utterly eclipsed by the
performances of the inspired madman" -- Socrates.
When is your birthday?
======================
18th March 1982.
Where were you born?
====================
In North Middlesex Hospital, Enfield, London, UK.
Where have you lived?
=====================
In London (UK) for most of my life:
* Enfield
* Greenwich
* Plumstead
* Tooting
* Bickley
* Bromley
* Beckenham
* Orpington
* Hackney
* Finsbury Park
* Sudbury Hill
* Angel
* Liverpool Street
* Brixton
With some temporary stay in:
* Richmond
* Notting Hill
* Swiss Cottage
In Sri Lanka for 3 years:
* Kilinochi
In Tamil Nadu (India) for 2 years:
* Thirunelveli
* Chennai
In Berlin (Germany) for a year:
* Wedding
* Prenzlauer Berg
Have you had a privileged upbringing?
=====================================
I've had a mixed upbringing. Growing up on a farm/jungle in Sri Lanka. Being a
city boy in London. The quality of life I had growing up was reflective of the
ups and downs in my father's life.
He would be unemployed at times and we would live in shitholes. He would also
make more than £100k a year sometimes and we would live decently. Ups and downs.
I consider myself rather privileged to have had private schooling at Dulwich
College. But this was only possible because of a scholarship and an assisted
place. I appreciate it moreso because I've been at state schools and realise how
shit they can be.
.. class:: sidebox
"Thankful for the various opportunities life has given me"
But I am even more thankful for the various opportunities life has given me. To
have grown up under the influences of two different cultures. To have been born
and brought up in London -- in some ways, the centre of the world. To have
experienced poverty and excess.
To have experienced death at an early age and thus been able to question the
meaning of life. To have a loving mother. To have a cruel father. To not being
incapacitated in some form. To have decent-enough looks. The Universe has been
good to me.
And even the suffering I've experienced has been beneficial -- a real education
in the School of Life.
Where did you go to school?
===========================
I started at Heronsgate primary school in Greenwich. Then home schooled by my
mother whilst living in India for 2 years before joining Broadwater primary
school in Tooting. I also briefly attended Graveney's 6th form for A-level Math
classes before joining Dulwich College in 1992.
I dropped out of Dulwich in early 2000 after Leeds University gave me an
unconditional offer to do a degree in Philosophy and Economics. Unfortunately,
whilst I accepted the offer, I never bothered to turn up. Sorry Leeds!
What academic qualifications do you have?
=========================================
Nothing really. Unless you count GCSEs and A-levels -- The Autodidactic School
of Polymathy doesn't give out certifications yet.
I did 2 of my 12 GCSEs early at the age of 9 -- in Mathematics and Tamil. Did
the others at the usual age of 16. Got an A grade in all of them.
Did 8 A-levels in: Maths, Ancient History (AS), General Studies, Further Maths,
French (AS), Physic, Chemistry and English. Got the grades AAABBNUX
respectively. The last three were because I didn't bother turning up to the
exams after I got the unconditional offer for university.
I also did my SATs for entrance to US universities and think I got a perfect
score -- maybe that was only in the Maths. My memory is sketchy on that one. Got
fazed out when I realised that I couldn't afford the yearly 30k+ that
MIT/Harvard wanted.
.. class:: sidebox
"Lost interest in academia by my mid-teens"
My childhood aspirations to do a PhD by the time I was 18 were gone as I lost
interest in academia by my mid-teens. Academic qualifications seemed to simply
be an exercise in memory rather than understanding.
An example would be my Ancient Hsistory exam. I hadn't attended classes, so my
teachers predicted a D grade. The day before the exam I read a book on the
topic. So when the results arrived and I'd gotten an A grade, the Classics
department was rather surprised. Nothing more than short-term memory in action.
And whilst I've never experienced university, people often tell me it's
different. This, however, doesn't correlate with my experiences as a teacher. I
used to privately tutor undergraudate computer science students in my early
twenties. And their university education seemed to be just as focused on memory
and not on understanding.
What languages do you know?
===========================
.. class:: sidebox
"Lucky to be bilingual"
Despite my fantasies of being a polyglot, I am only fluent in two: English and
Tamil. I am familiar with some very basic French and German. A certificate
somewhere states that I should know some Japanese but I don't (at least not
anymore).
The most fun I ever had learning a language so far has been Hindi. I was 14 and
on holiday in South India for 3 months and convinced a North Indian gentleman to
teach me for a mere £30.
The deal was that I could turn up at his house any time during the day and he
would teach me. It turned out that he was just newly wed, and observing the
flirting of adults was an interesting side-experience to the learning of Hindi
and Sanskrit.
Unfortunately, like with Sinhalese and Latin, I can remember very little and
will be surprised if I recognised even a few letters from the written script
(Devanagari).
At some point though, I'd like to learn these languages properly -- along with
Russian, Chinese (Mandarin), Arabic, Greek and Spanish. I consider myself very
lucky to be bilingual. If you have kids, teach them many languages before they
reach the age of 5. It really helps.
What inspired the Espian vision?
================================
The death of my grandmother [Palmer-2004]_. To understand this, you need to go
back to the start of my life. 25 days old. Beginning my jetset lifestyle. My
mother and I were on the way to Sri Lanka.
Her father was dying back home. Lung cancer. When he passed away two months
later, my grandmother was left all alone. So my mother decided to leave me there
with her and returned to England.
And that is how I spent my first years growing up. Thinking that my grandmother
was my mother. My mother eventually came back for me. And I met my parents for
the first time a few months before my fourth birthday.
A year and a bit later, I had a little sister and we were about to emigrate to
the USA. My father was going to Berkeley. But news came that my grandmother had
fallen ill whilst visiting friends and family in India. Bone cancer.
I was rather adamant that we go to India. At least for me to go. Eventually my
mother, sister and I went to India. My grandmother had her leg amputated. The
cancer had stopped spreading. I nursed her back to health.
But then on October 20th 1988, she had a heart attack. My mother had been out
shopping. I called for help from the neighbours. I prayed to the God of Death to
spare her. But to no avail. Blood dripped from her nose. Her body was ice cold.
As the eldest grandson, I had to alight her funeral pyre. I refused. I wanted to
freeze her and preserve her until death could be reversed. You have to do this
everyone said. So I did.
A few days later I snapped. I was 6. This was my first experience of death. I
had grown up under shell attacks in Sri Lanka and seen bloodied, mutilated war
victims, but had never seen death directly. I couldn't understand why we lived.
What is the point of life if all that you get at the end is death?
The family across the road were Christian. I asked them. I asked their priest.
The neighbours to the right were Muslim. I asked them. I asked their imam. I
asked the Jains. The Saivas. The Hindus. The Sikhs. The Buddhists.
I got similar answers. But none were satisfactory. Made me realise that there is
very little difference in the real teachings of the various faiths. But I still
didn't have an answer.
I wanted to go meditate in the mountains. Maybe I'll reach enlightenment like
Buddha. Wander the wilderness like Jesus. My parents talked me out of this. So I
kept on asking questions of any adult that would give me their time.
Eventually I came to the conclusion that life has no meaning. There is no
ultimate truth or purpose. God lies within. And the only worthy goal in life is
to be happy in the moment.
But then I looked around. We were living in a village in southern India. During
the time following my grandma's death, the narcissicism of childhood had been
replaced by an awareness of the world.
And everywhere I looked I saw needless suffering. I compared the life in India
to life in England. The differences in the material quality of life. The
wastefulness and excess where others barely survived. The differences in the
spiritual quality of life. How, despite not having much, the poor seemed
happier.
I was also able to see politicians in action. The ideals of democracy thrown
aside as people were bribed into voting for specific parties. I tried to
understand why people would destroy the chances of a collective better future
for a slightly better today.
Eventually I came to the realisation that one's basic needs need to be met.
One's family to not be starving. Otherwise people were willing to screw each
other over for short term gain.
And if I were to be happy in my life and not be screwed over by others then I
needed to ensure that others had their needs taken care of. And if everyone had
the potential to be happy, then I could be happy.
And thus I discovered my life purpose. By adopting the entire world as my
family. The Espian vision was born.
How do you get your ideas?
==========================
Most of my ideas are informed and inspired from experiences that life puts me
through. And, quite often, they reach clarity as I am mid-speech discussing such
situations. One example I'll elaborate here is Pedipeace.
It was inspired by events that took place during a March 2003 protest as War
started in Iraq. As I was heading out to join some friends from school, I
couldn't find my belt. There was a corded PC microphone on the table. I tried it
out as a belt. It worked, but it looked rather silly so I took it off.
I caught up with my friends at Westminter. One of them had just been to Morocco.
He had a present for me. A djellaba. I wore the robe over my t-shirt. A few
hours later I had been adorned further.
.. image:: http://cloud.github.com/downloads/tav/plexnet/gfx.henry-21st-birthday.jpg
:class: float-right-aligned
:width: 302
:height: 204
My scarf was being used as a bandana to hold together a wreath of daffodils
adorning my head. I was carrying a big stick -- the leftovers of an anti-war
placard. I had used it earlier to make some music on some traffic cones and beer
bottles.
The protest continued as usual. The BBC interviewed me for looking strange. All
in all, it had been a lovely afternoon walk with friends. Except for the
shouting of "No War" constantly, it demonstrated how lovely London would be if
it was pedestrianised.
...
What's the story of the Wobbly Bridge?
======================================
Time. 2am. Place. The wobbly (millennium) bridge.
After entertaining myself running around the trees, I pull myself up onto the
wobbly bridge and gently skip along. My heart beats slightly faster as I see the
river flow underneath me. The thrill of being so high. The thrill of falling.
Clumsily pull myself over the side, straddle a beam and sit. Watch the river
flow. I lean back. Feel the aura of the full moon. The wind blows. So soft. But
with a sharpness that makes me alert. Aware. Lyrics come to mind "London calling
to the underworld... I live by the river!"
I get up to climb back over. I almost slip. Heart beats. Back on the wobbly.
Start to skip along again. In front of me, a giant circle. A perfect circle. A
circle of objects. I look around -- no-one to be seen. A present from an
anonymous stranger.
I delight in the find and start exploring. A mobile phone. A paintbrush. A block
of wood. A pressure valve. A blue tin (labelled russian caviar). I look inside.
Some round stones. Another block of wood. Too many objects to be mentioned here.
The wind takes on a cold edge, but the present makes me very warm.
And in the middle of this perfect circle, at the exact middle of the bridge
(both lengthways and sideways), a grey and white toy bunny with a fat blue
alkaline battery. I ponder upon the present for a long time. Is there a clever
message?
For some reason, the words "beautiful girl lovely dress" sample across my mind's
ear. A cyclist zooms by. I call back at him. He stops. He turns. He approaches
cautiously. I ask him what he thinks. Maybe a clock he says. Doesn't have
anything interesting to say. I let him go.
I explore the present further. Time goes by. I feel inspired. Thoughts provoked.
Another walks by. I wave. We speak. I can sense the samani in this creature. We
will be good friends.
I bid the present goodbye, and decide to spend the remaining hours of the
morning exploring the mind of this new found friend. And fun hours they were.
What are your deepest values?
=============================
.. class:: sidebox
"Truth, justice, honour, loyalty and love"
Truth, justice, honour, loyalty and love. Sure, they might be based on the Code
of Thundera, but they are my deepest values. And whilst I occasionally slip up,
I constantly strive to abide by them. This constant struggle is what makes life
interesting.
And, although not a value, another major driving force of my life is best
described in `Fight Club <http://www.imdb.com/title/tt0137523/>`_: "This is your
life and it is ending one minute at a time". That is, life is short and one
should make the best of it. Carpe diem!
Have you ever lied?
===================
Yes, a handful of times. I'm also terrible at lying -- you can see it from a
mile off!
I do however have two habits which are far from my self-image as a Speaker of
Truth. One is that I occasionally pretend to be ignorant and ask others to
explain things to me. This can be useful to both get a feel for what the other
person actually understands as well as a way to stroke their egos.
I don't actually see an issue with this -- as far as I can see it is beneficial
social lubrication. However I did once hear about Tony Blair getting lambasted
for similar behaviour, so perhaps there is something sinister that I am missing?
The other habit of mine is related to what my old business partner Ade Thomas
from green.tv refers to as "concentric circles of bullshit". It could probably
be best understood by looking at how `green.tv <http://www.green.tv/>`_ came
into existence.
It started with the idea being pitched to UNEP, Greenpeace and a few others.
This was before YouTube had become mainstream and they didn't really see the
value of an online video channel dedicated to environmental issues. Or had even
heard of podcasts.
They weren't happy to provide any resources, but were okay enough for their
names to be used as partners. This was all it took for the concentric circles of
bullshit to go into action!
It became easier to go round to a number of other organisations and say, "Hey,
UNEP and Greenpeace are backing us, would you like to come on board?". A Paragon
of Truth would never have been happy with such half-truths but it proved
effective.
By the time of launch, the circle had come back to the original parties who were
now willing to provide a lot of support since so many others were on board!
One of the Directors of UNEP was even willing to claim to have been the
visionary behind the idea in the first place and was more than happy to parade
the accomplishment in front of other UN agencies.
Now it worked out really well for everyone involved in green.tv, but playing
with such half-truths can sometimes have painful consequences. However, such
hustling is unfortunately a necessary trait sometimes when building businesses.
If anyone can tell me how to achieve the same results without it, I'd be happy
to learn.
Have you ever stolen anything?
==============================
Sadly, yes. Five times.
The first time, I stole 50p from my mother's coat pocket. I was 9 and wanted to
buy some cola bottles (they used to be just 1p each back then!). I felt guilty
about this for weeks after and eventually confessed.
The second time, I helped some fellow homeless people pick up scraps of metal
from a construction site. The metal got sold at a dodgy garage somewhere and
paid for a warm night and a drink. Sorry construction company!
The third time, I had done some work for a guy. Did it exactly as he wanted. But
he claimed it wasn't and refused to pay up. So I convinced him to give me the
money as a loan and have sadly yet to repay it. Sorry John!
I shop-lifted some food from Tesco once when I was one of the billion odd living
on less than $2 a day. So I paid for some of the items and walked out with
several more in the bag.
The final time, I stole a passport sized photo of an ex-girlfriend after we
split up. This is my confession.
Have you ever been disloyal?
============================
Sadly, twice. Once for real and the other time in my head. Both, unsurprisingly,
involved women.
The first time, a friend asked if his ex could stay at my place -- they were
going through a separation. Things went great for a while. She was extremely
lovely and I enjoyed having her around the place.
But once she started making advances, my value system was challenged. Torn
between my loyalty to my friend and my attraction to her, I am sorry to say that
I ended up giving in and we ended up having a fling.
The second time, a friend and his girl of many years had broken up. It so
happened that she was also the sister of another friend of mine. And so we ended
up spending a fair bit of time together.
During this time I gradually fell for her. Thankfully I am pleased to say that I
never acted on my feelings for her, but I am still not proud of having had those
feelings in the first place.
Loyalty is very important to me and I am truly sorry for having let down my
friends on those two occasions.
Are you a bigot?
================
.. class:: sidebox
"Much to be gained in life when one keeps an open mind"
Whilst I have no compunctions about political incorrectness and will tease the
French and the Obese, I am not a bigot. It is hard to be so when you grow up in
a truly diverse city like London.
As a further testament, my various lovers have come from a variety of religious
and national backgrounds -- Bolivia, England, Germany, Greece, India, Lithuania,
New Zealand, Singapore, St. Lucia, Vietnam...
Ditto with my various flatmates/colleagues -- Australia, Austria, Brazil,
Canada, China, France, Gambia, Japan, Netherlands, Norway, Sweden, USA, &c.
In contrast my dear father is a homophobic racist. In fact, I would go as far to
say that, in general, immigrants tend to be more bigoted than "natives". Whilst
unjustifiable, this is in some ways understandable -- a reflection of their
insecurity and vulnerability.
It's when it gets passed down to their children that I have a problem with it.
For example, I was at my sister's 21st birthday. It was at a club down near
Soho. And I was rather shocked as I walked in.
Why? Because with the exception of about 5 people, everyone else there was
brown. Not that I'm complaining. Asian girls -- like their South American
counterparts -- tend to be rather pleasant on the eyes.
But when many of these people were speaking to each other in Gujarati, Tamil,
Hindi, &c., I began to wonder. And after speaking to a few of them, my doubts
were confirmed. Most of these people rarely mixed with people outside of these
groups.
Now, being part of an ethnic community is not a bad thing. I would say it's a
great thing. But doing so to the exclusion of mixing with other groups is
definitely harmful. Especially in the context of London where you have so much
opportunity and no excuse.
Why? Because mixing with the same type of people doesn't help to broaden your
mind. You need to be exposed to unfamiliar and sometimes uncomfortable
perspectives. That's essential to nurturing a healthy understanding of the world
around you.
Some people might misinterpret this as being racist to my "own kind". I've even
been called coconut twice -- brown on the outside, white on the inside. I'm
neither white nor brown. I'm a multi-coloured kaleidoscope. A human being. An
Espian.
I want to get past the useless social ghettos that repeatedly form. These serve
no purpose except to create needless boundaries between otherwise loving beings.
And, whilst rare, I've experienced bigotry from "natives" too.
The most surreal one was a pub in east London. I had popped in whilst waiting
for a girlfriend. It was eerily filled with just white people. Even posh venues
have a token coloured individual.
All eyes turned to me as I put my coat down and approached the bar. One of the
barmaids intersected me and escorted me to the door. They were closing. Right.
Now, again, I have nothing with people mixing with their "own". Just don't do it
exclusively! Say no to social ghettos.
Anyways, seeing the bigotry of others whilst growing up had been a good enough
lesson in the pointlessness of it. There is so much to be gained in life when
one keeps an open mind.
One advice I'd like to share is to not suspect bigotry of others. My father
would interpret any insult or rejection as racial discrimination. My gay friends
would express gay pride a bit too much to overcompensate for the oppression they
felt others had towards them.
Sure, racism and oppression exist. There is a bigot on every street. But don't
live in fear of it. Don't suspect it. Just be yourself. And if that is a true
being with good intentions, others will sense that and react positively. No
matter what.
As for the few that don't. So what? They are probably old and set in their ways.
They will die off soon enough. Oh, that reminds me of another thing. Political
fucking correctness.
I was on a train once. Befriended this guy sitting in the same carriage. We'd
been having an hour long conversation when I asked him how life was as a
cripple. He went berserk.
Now I hadn't meant to insult him in any way. That should have been clear from
the tone of my voice. And he was a cripple. At least by any dictionary
definition that I've seen. But, no. He was a disabled something or other.
What the fuck? It seems to me that some people deal with their shortcomings by
hiding it behind fancy politically correct phrases. No, I'm not blind. I'm just
visually impaired. What the fuck? Deal with reality. Shit happens. Just be
yourself.
Are you gay?
============
No. However I have had two experiences relating to the issue. They took place
just over a decade apart and what surprises me is how similar both scenarios
were.
The first took place when I was 16. We were staying over at a family friend's
house in India and sometime in the early hours of one morning I woke to find one
of their sons sucking my cock.
My initial thought was to respond with physical violence, but given the matter
of his teeth around my most delicate part, I instead controlled myself, withdrew
Mister Helmet from his grasp and explained my lack of interest.
He took the rejection fairly well and went away. To this day I have no idea why
he thought such behaviour would be okay. What baffles me even more is that a
similar incident took place 10 years later!
This time it was a friend that I'd made at a party a few weeks prior. I had
liked his energy and invited him to one of my house parties. He had ended up
crashing in my room towards the end of the party.
It was not uncommon to go back to my room after a party and find people passed
out. So I got into my bed and went to sleep. I gradually woke up a little while
later to find him giving me a blowjob.
I couldn't believe that this was happening again. And perhaps because I was
still drunk or perhaps because earlier that day I'd had a break up with two of
the girls that I'd loved, but by that point I really didn't care.
So, this time, I let the guy suck me off. At one point he even moved around
wanting me to reciprocate -- I pushed him away and he seemed to get the hint.
And once I'd ejaculated, he put his clothes back on and left.
Now, when I have recounted what had happened to others, some have suggested that
I might therefore have bi-tendencies. Whilst this might be true, I have never
fantasised about having sex with a guy or been turned on by it, so I fail to see
how.
In fact, on that particular night, it really didn't matter that it was a guy. It
could have just as well have been a `Fleshlight sex toy
<http://en.wikipedia.org/wiki/Fleshlight>`_ for all I cared. Pure physical
release and nothing more.
So there you go. I am certainly not homophobic but I have no desire for romantic
or sexual relationships with guys either.
Are you violent?
================
If you ask everyone who knows me, they will attest that I am one of the calmest
people you'll ever meet. But, like everyone, I've had my moments.
I don't appreciate violent environments, but I am also comfortable with dealing
with violent individuals. As a consequence I've ended up in various minor fights
over the years. However, in a few incidents I momentarily lost it and hit women.
One time I punched my little sister several times in the stomach. Unfortunately
we weren't kids then. I had been staying with my family for a few weeks and my
mother and sister were making each other quite miserable.
Unfortunately I intervened and it escalated to a point where I momentarily lost
it. And to make things worse, years later, I repeated my shameful loss of
control as an argument with a girlfriend heated up and I hit her.
I can say how she was the aggressor and how she almost destroyed years of my
work, but truth is, I should have maintained control. Alas, there is no rewind
button in life and even a momentary loss of control can't be excused.
At least to make up for my shame, I spent the night in Brixton police station
and got given a caution. She had called the police and despite her not wanting
to press any charges, it seems the police had to take the guy into custody.
Having called the police many times when my father was being excessively violent
towards my mother, I was actually very appreciative of the police action in this
case. However I wasn't too happy with the caution.
Now, a caution isn't a criminal conviction but I felt it to be unjust. She was
clearly the aggressor and whilst I was also in the wrong, I felt the
discrimination based on my sex to be thoroughly unfair.
And to make matters worse, it turns out that if I had simply refused to answer
the questions in the police interview, then I would have walked away with no
caution, but since I had been open and honest, I'd fucked myself.
Justice should be contextual and people should be encouraged to be open and
honest. In any case, like others before me [Gandhi-1927]_, I am not a violent
individual, but I have sadly had moments where I've lost control.
Are you a vegetarian?
=====================
I used to be. Fervently. For 8 years of my life. From August 1998 till
December 2006. I had two rational reasons for my choice:
1. By eating lower down the food chain, it is more efficient and a larger global
population could be sustained.
2. Life is beautiful. And our fellow creatures shouldn't live purely for our
sake.
But, whilst I believe in the above, I also love the taste of meat and think that
it is natural to be a meat-eater. So the real reason I gave up meat was because
of a girl. She was a vegetarian.
She was my first love and though she had never asked me to give up meat, I did
so willingly. And the fact that I never touched meat was a sign of my commitment
to her.
But when we broke up in December 2006, I couldn't decide whether I wanted to
stay being a vegetarian or go back to eating meat. So I flipped a coin and am
now a meat-eater again.
Have you taken drugs?
=====================
Yes. I believe that one should experience as much of what life offers. And not
suffering from an addictive personality (nicotine excepted), I have had the
luxury of trying out various drugs.
.. class:: sidebox
"Hallucinogens helped with my understanding of myself and life"
My favourites have been LSD (Acid), MDMA and magic mushrooms. MDMA truly can be
happiness in a packet. And never having had a bad trip, hallucinogens have truly
helped with my understanding of myself and life around me.
Actually that not having had a bad trip thing isn't quite true. I was at a rave
once tripping my balls off on acid when two girls decided to stalk me. The two
witches as I saw them. It was a pleasant trip after I managed to get rid of
them.
Drugs like cocaine generally have very little effect on me. They just give me a
cold the next day. Some of the designer drugs have been fun -- though their
effects seem to diminish on repeat usage.
And, as for marijuana, whilst I've had many pleasant experiences on it, it is
near the bottom of my drugs list -- along with Ketamine. The reason for this is
because dope makes you comfortable with not doing anything.
I spent a good six months of my life doing nothing but getting stoned every day.
A friend of mine was a total pothead and he would start rolling the next joint
by the time I was finishing smoking the last one. And I really don't enjoy not
being productive.
Have you ever paid for sex?
===========================
No. But I have had a few interesting experiences with prostitutes.
Soho. Crack den
...
Have you been hustled?
======================
Yes, four times.
The first time, I was trying to score some brown (powdered heroin) from a pair
of street dealers. I gave one of them some cash and he owed me a fiver back. He
claimed to not have any change and said he'd pop down to the local shop.
...
Do you have a criminal record?
==============================
No.
What do you have against the Vatican City?
==========================================
Let me be clear that I have nothing against the Vatican. It is the Vatican City
that I have problems with. Specifically, the Gendarmeria -- the police force.
To understand this, we need to go back to one summer night in 2005. I had gone
to Rome for a day meeting. The meeting had gone well and my flight back was
early the next morning. So instead of being cooped up in my hotel room, I
decided to spend the night checking out Rome.
...
How much debt do you have?
==========================
I have lived most of my life assuming a gift economy of sorts. So my actual
legal debt is a £14k loan to Halifax which never seems to go down. However, I
owe just under £200k to friends and family.
The bulk of that is to the investors of my first company. The company went
bankrupt around my 19th birthday and I decided that the honourable thing would
be to assume their lost investment as debt owed to them from me personally.
Whilst this is no doubt a stupid stance to take as legally I owe them nothing
-and they knowingly took the risk, I feel that they invested because they
+and they knowingly took the risk, I felt that they invested because they
believed in me and therefore it was my responsibility.
However I haven't felt the same sense of duty when dealing with large
corporations and have walked away from an outstanding mobile phone bill with
Vodafone and overdrafts with HSBC and Natwest. Sorry, I was poor.
Besides what I feel I owe to the investors of my first company, I also feel
guilty for a minor debt of around â¬50 owed to an Indonesian restaurant. It came
about whilst I was a starving artist in Berlin.
I didn't have any money, so I made a deal with the local Turkish and Indonesian
-restaurants. They'd feed me daily and I'd eventually settle my debt. I settled
-the debt after a few months and all was good.
+restaurants -- they'd feed me daily and when I got some money, I'd settle my
+debt. After a few months of this I eventually settled my debt and all was good.
I asked the Indonesian place if they'd continue the deal and they kindly agreed.
These people were lovely. The owner, Surya, and his wife took great care of me.
However, about a week or so later, tragedy struck.
An uncle of mine died and my mother paid for a flight so that I could get back
for the funeral. Around the same time I was moving from one part of Berlin to
another. And, amidst all the commotion, I completely forgot to pay them.
It wasn't intentional and I'd really like to see the debt paid.
What jobs have you had?
=======================
I have worked for myself (the Espian vision) most of my life. So have had little
chance to have a "normal job".
My first job was working for an uncle of mine in his post-office/corner-shop in
Walthamstow. It was also the longest job I've had (a whole month!). I slept on
the store floor and during occasional bouts of insomnia re-organised the shop
and somehow managed to double the revenue.
My second longest job was as a street cleaner for Islington council. This was
perhaps the best job I've had. I got to get up early in the morning. And work
was finished by noon meaning that I had the whole day left.
Unfortunately, after 2 weeks, my ganger called me in and laid me off. I had been
spending too much time cleaning each and every street. I was laid off for being
a perfectionist. Heh.
Other jobs include being an art salesman, facilitator, etc. The funniest was
being an extra for a Sky Sports rugby ad -- imagine that, skinny me being
-portrayed as a rugby player -- friends called in disbelief after seeing the ad.
+portrayed as a rugby player -- friends called up in disbelief after seeing the
+ad.
And, finally, there have been a dozen odd temp jobs which I occassionally tried
for a day or two before walking out at the incompetency of those who were meant
to be my managers.
What is the worst invention ever?
=================================
Alarm clocks.
-The wooshing soound of deadlines as they woosh past.
+The wooshing sound of deadlines as they fly past.
...
What have you done with your life?
==================================
A lot of different things. Mainly centered around the Espian vision.
...
What do you want to do with rest of your life?
==============================================
A lot. Some of the highlights include:
* Empowering people by creating a better social-economic infrastructure.
* Creating a decentralised social platform. Ampify.
* Crafting a multi-genre musical instrument that inspires people. Jintra.
* Building a city using social architecture and a global underground tube
network. Zygote & Xetre.
* Creating a movie of epic proportions. Gaia.
* Travelling to Mars. Mangala.
* Utilising advances in molecular biology to enable a higher quality of life for
all. Electrophyll & Geren.
* Nurturing the cultural and natural commons for the benefit of all. Espia.
* Having a daughter. Hiroko.
Most likely I'll die of something like lung cancer before most of this happens.
So I also want to make the most of every moment that I am alive. Bringing
pleasure to myself and as much of humanity as possible.
What has been your most self-empowering moment yet?
===================================================
It took place sometime during the summer of 2004.
...
What inspires you?
==================
.. image:: http://cloud.github.com/downloads/tav/plexnet/gfx.saritah.jpg
:width: 352
:height: 259
:align: center
:class: float-right
| Get up and get going
| You've got nothing to lose
| Let it out, let it through
| There's nothing that you can't do
|
| What you want, get up and get
| Your future hasn't happened yet
| It is up to you to manifest
|
| Participation -- fundamental to creation
| You will not reach your destiny
| If you don't leave the station
| Let yourself be activated visionary
|
| Get up and get going
| You've got nothing to lose
| Let it out, let it through
| There's nothing that you can't do
|
| You are capable -- never forget that
| You are courageous -- got to respect that
| You've got your freedom -- need to protect that
|
| INSPIRATION, MOTIVATION, DEDICATION, REALISATION, YEAH!
|
| -- `Saritah <http://www.saritah.com/>`_
What has been the low point of your life?
=========================================
There have been many low points in my life. Not sure if I could select one as
having been the lowest. But one that springs to mind took place in 2003.
It started with me fucking up a freelance work. I'd been asked to develop the
new abctales.com -- a website for writers from all around the world. It was a
relatively straightforward task, but I decided to develop a lot of advanced
functionality. I had felt abctales could be a key player in the emerging "Web
2.0" space.
But, in so doing, I ended up taking a lot longer than I had originally planned.
I hadn't learnt the art of expectation management at this point. So, after a
month, pretty much everyone was pissed off. Not least, the abctales.com
community.
The guy who ran the thing and had believed in my abilities was tearing his hair
out. The friends who had recommended me to him were fucking pissed off. Someone
decided to steal the front tyre from the bike that I'd gotten from a skip. The
bike that I'd been using since I couldn't pay for public transport.
The "landlord" wasn't too pleased at rent not being paid. Enough was enough he
said. Please leave. And, oh, in the middle of all this, my relationship with a
girlfriend took a turn for the worse.
So I gave my landlord my fancy phone in exchange for rent owed. He gave me the
brick he owned. I packed up my belongings. As I did so, my laptop decided to
die. Besides the phone and a bunch of clothes, it was all I had left.
As I left the space I had called home for the previous year, I felt more lost
than when my father had kicked me out four years before. But I knew more people
by then. So I made two phone calls.
I fare dodged and got myself to Greenwich, where a wonderful guy called John
Lea fixed up my laptop and revived it. I am forever thankful for the kindness he
showed.
Then I made my way up to somewhere near West Hamsptead, where another friend,
Josef Davies-Coates, helped sort out a place for me to stay temporarily. I'd
have to paint the walls but would be indoors. I accepted.
Not the worst place I've stayed, but it wasn't the best either. The flat had
nothing besides floors and walls. No heating. One working power point and a tap
which dribbled cold water.
Beggars can't be choosers, so I set myself up and got to work. I bought myself a
box of cereal with the last pound I had left. I figured I could survive a bit
with just water and bits of cereal.
Then I managed to contract a fever somehow. So I spent my time huddled up on the
floor with a plastic bag stuffed with clothes as a pillow -- getting up to paint
the walls every so often.
Three days later the fever had gone and I was able to spend my time working
again. I forget how exactly I got myself out of this one, but I am thankful to
John and Josef. The kindness of strangers and friends is inspiring.
What has been your strangest experience so far?
===============================================
I've been lucky to have had a lot of crazy, fun experiences in life. They mostly
happened when I was least expecting them. And the strangest one took place one
early spring morning.
My housemates and I had been out all night dancing away at The Key. We returned
home at about 6 in the morning and not feeling sleepy, put on some music. One of
my flatmates picked up the bongo and started playing.
Despite having danced for the previous 8 hours, I still felt an overflow of
energy and kept on dancing. Not having had any drugs, my intake had been limited
to alcohol and cigarettes.
Then, all of a sudden, I felt one of the most powerful orgasms I'd ever felt. It
just took over me mid-dance. It was unlike anything I had ever experienced
before. And, being a non-ejaculatory orgasm, took me a moment to realise what
I'd just experienced.
I finally understood the Melveli (the Sufi Whirling Dervishes). I felt the
connection to the Universe pulsate through me. I offered myself in service to
the whole of creation.
What problem have you struggled the most with?
==============================================
Double binds. Destiny.
...
Why don't you read books?
=========================
Let me be clear. Whilst I rarely read books, I do read. A lot. The reason I
avoid books is for two simple reasons.
The first one is rather ego maniacal. I wanted to be able to claim my ideas as
my own. It was a rather poor reaction to discovering Zeno's paradoxes
[Aristotle]_ when I was a kid.
As a master of procrastination who spent a lot of his life thinking, I am
comfortable claiming my ideas as my own. But as I've grown older, I've come to
realise that nothing stands on its own.
Thus I came to realise that all my thoughts have in some way been inspired by
the works and actions of others around me. Truth is not owned. It can only be
discovered. I am merely a vessel for it to channel through.
The second reason is the one that still makes me avoid books. I noticed at a
young age that "educated" people spoke in a rather funny language. They would
use terms that only a select few would understand.
The terms gave them clarity and precision. But they became lost in it. Unable to
communicate with most others. A great loss in my view. Because they have much to
offer. So I have left it to others to read and simply question them to get an
understanding for myself.
Who are you most thankful for?
==============================
My mother -- Thamilarasi. She has sacrificed much of her life for me. She has
always been caring, attentive and loving.
Even when she joked to my father that should he see a woman running down the
street pulling out her hair in frustration, he should stop and look. For it
might be her -- tired of my never-ending questions. But, even then, she kept
answering my thousands of "Whys?".
She taught me the Arts. The Sciences. Mathematics. Music. History. Linguistics.
Everything she knew she taught me. She encouraged me to have an open mind.
She even got beaten up several times by my father for supporting me. He broke
her nose once because she'd paid £35 to put in my application for GCSE Maths.
Doesn't seem like much now, but we were poor then and she'd starved herself for
weeks to save up.
In some ways, my desire to change the world for the better was largely ingrained
by my mother. She used to have dreams when she was pregnant with me. Dreams of a
sage who would take her on travels across the Universe. Teach her mathematics.
Show her how life could be.
These dreams convinced my mother that I was the one prophesised by our
ancestors. The one who would save his people and make the world a better place.
Whilst I've grown to take it all with a pinch of salt, I cannot deny that it
affected me.
Thank you Amma.
Is it true that you met with the Tamil Tigers? Are you one?
===========================================================
Yes, I have met them. But, no, I am not affiliated with them.
To understand the context we need to go all the way back to the summer of 1998
-- when my 16-year old self was on holiday in India. There I had fallen in love
with this amazing girl, N-. She loved me back. Life was good.
But since I was in England and she was all the way over in India, I adopted a
life of polyamory [Easton-1997]_. My various girlfriends were (surprisingly)
accepting that my heart belonged to this girl in India. And, energised by this
love, I was able to throw myself into my work.
Then, during Christmas 2002, L- walked into my life. She was over on holiday
from Greece. By 2006, she was in love with me. Life was very good! Most of us go
through life never meeting someone who connects on all aspects -- spiritual,
physical, intellectual, emotional -- but here I'd managed to discover two!
But, by the end of 2006, things began to fall apart. Both N- and L- wanted me to
commit to just one of them. Things were also fraught with N- as she also wanted
me to give up various other things, e.g. cigarettes, mdma, &c. We'd been having
a lot of arguments.
So, rather brashly, on December 1st, I broke off the relationship with N-. As
fate would have it -- the very same evening -- L- broke off with me. I had gone
from a high to a low in one day. Never having experienced rejection before
didn't help.
Two weeks later, I turned up in Athens. It wasn't quite the surprise I'd
intended -- one of the side-effects of having public IRC logs which your lovers
are aware of.
Things started well. L- was still "madly in love" with me. But then we decided
to take a trip to Thessaloniki. Four days later, as we took the train back down
to Athens, the relationship was fully over. She now "hated" me.
It was Christmas Day 2006. I picked up my stuff from her house. Checked myself
into a hotel. And booked a flight to Berlin the next day. I did the only thing I
could do -- throw myself into my work.
But the Universe wasn't happy. I'd lost my energy. Even "Love's Cure" [Ovid]_
was of little help. I tried writing various cathartic letters [Tav-2007]_.
Nothing. The unusually high energy levels had been replaced by a boundless low.
I initiated the 2007 iteration of 24 weeks. Nothing. Work failed to offer the
distraction that I needed. When your work is driven by your love of humanity, it
needs to be anchored somehow.
So two weeks into 24 weeks, I abandoned my responsibilities and went to
Barcelona. Not sure how, but it helped. A week later I returned revitalised. My
energy wasn't back yet. But it wasn't in the negative either. I was able to
breathe. To function.
I got back in touch with N-. My energy levels started to ramp up. But, in late
2007, N- got engaged. She was 25. Most of her friends had gotten married by 21.
Her parents had gotten tired of her excuses.
N-'s mother had sacrificed a lot to bring up her children. N- wanted to make her
happy. So she had agreed to the marriage. I was devastated. So, on December
2007, I turned up in Coimbatoire, India.
It was intense. N- claimed that she was happy to get married. Her husband-to-be,
R-, loved her and she loved him. Then, one day, R- and some of his family (about
20 people) came to visit her family.
I felt like Jude when asked to give away his beloved Sue in marriage
[Hardy-1895]_. I managed to detach myself emotionally and be my usual self. R-'s
family even became rather fond of me. Being charismatic has its downsides. And
this was one.
That night, after everyone had left, N- broke down in tears. She didn't love R-.
She still loved me. She had just been angry over the whole L- situation. And
between that and making her mother happy, she had agreed to the marriage.
We talked with R-. Explained the situation to him. Asked him to call the wedding
off. He refused. He was madly in love with N-. She told him that she didn't love
him. He didn't care. She would come to love him after they got married he
claimed. I was baffled.
She tried to call the wedding off. R- retaliated by claiming to commit suicide
if she did any such thing. I talked with her parents and asked for her hand in
marriage. They refused.
I reasoned. I argued. I pleaded. They would hear none of it. They didn't care
that we loved each other. Culture stood in the way. If I married her then her
parents claimed they would commit suicide.
I asked N- to come with me. Only after her mother passed away she said -- till
then she would do what her mother wanted. Even if that meant spending her life
with someone she didn't love.
I couldn't understand it. The mother wanted her daughter to be happy and thus
was making a decision that would make her daughter's life miserable. And the
daughter was willing to have a miserable life in order to make her mother happy.
.. class:: sidebox
"Decided to disappear from this insane society and be a hermit"
So I decided to disappear from this insane society and be a hermit somewhere in
the Himalayas. Unfortunately N- was able to figure out my intentions and made
sure that I got on the flight back to London.
The flight, however, was a transit flight via Sri Lanka. So I just walked off
the plane in Colombo. My mind was on auto-pilot. I headed north. A series of
buses, military checkpoints and taxis later, I found myself walking through
no-man's land. On the way to the Tamil-tiger controlled region of Sri Lanka
(Tamil Ealam).
It had been an interesting journey in itself. Included a Buddhist monk I'd
befriended who enlightened me to the current state of the civil war between the
Sinhalese-dominated Sri Lankan government and the rebel Tamil Tigers (LTTE).
My British passport had let me off some of the heavy interrogation and body
searches that some of my fellow travellers had been constantly subject to. But
it had still been rather disconcerting having the private contents of my bag
publically emptied for scrutiny at various checkpoints.
I had spoken in English all the way -- paranoid of being mistaken for a Tamil
Tiger sympathiser. An old lady thanked me in Tamil for helping carry some of her
heavy bags of rice across no-man's land. I simply smiled back. We'd reached the
Tamil Ealam immigration control.
A guy came out to greet me as I puffed away on a cigarette. *What was I doing
there?* I wanted to visit my grandparents' house. *Where was I from?* London.
*Did I know any Tamil?* I put on my strongest English Tamil accent and said
"à®à¯à®à¯à®à®®à¯ à®à¯à®à¯à®à®®à¯" (a little bit).
A while later he led me to an official handling the paperwork who asked me a
question in Tamil. I stared back blankly. The other guy proceeded to explain
that I didn't know a word of Tamil. I didn't bother correcting him.
...
What is so good about Nutella?
==============================
.. class:: sidebox
"Brown skin, brown skin, you know I love your brown skin!" [Arie-2001]_
Nutella is simply orgasmic. Mixed with a diet of Fruit & Fibre, one could live
quite healthily. And if Mr. Ferrero has a sexy heir, I would have gladly married
her in exchange for a lifetime supply of Nutella...
How do you justify your large ecological footprint?
===================================================
I don't. I just hope that the quality and positive nature of my work outweighs
the damage caused by my excess footprint.
And as for using air travel, the dozens of Neem trees that I planted as a kid
hopefully help offset that.
What do you hope to achieve with this document?
===============================================
This is intended as a seed in the Valley of Hope. I would really appreciate
similar seeds from everyone reading this. And, together, our seeds will
hopefully flourish into beautiful Espia.
True power lies in the look in the eye of each and every one of us. And if we
can imagine our desired future, there is no power in the 'Verse that can stop
us. Together, we can create the worlds we want.
All thoughts, comments and criticisms are very welcome.
How does someone get in contact with you?
=========================================
Face to face is best! I'm based in London. If that doesn't work for you, then I
would love it if you could use the convey-and-notify approach [Celik-2007]_ and
drop me a link on:
* phone/sms: +44 (0) 7809 569 369
* email/jabber: tav@espians.com
* irc: `#esp on irc.freenode.net <irc://irc.freenode.net/esp>`_
* twitter: `@tav <http://twitter.com/tav>`_
* facebook: `Tav <http://www.facebook.com/asktav>`_
* skype: |skypestatus| `tavespian <skype:addname?name=tavespian>`_
.. |skypestatuss| replace:: Status
.. |skypestatus| image:: http://mystatus.skype.com/smallicon/tavespian
:class: absmiddle
References
==========
.. [Arie-2001]
`Acoustic Soul: Brown Skin
<http://www.amazon.com/Acoustic-Soul-India-Arie/dp/B00005A1PR>`_
India.Arie, Motown, March 2001.
.. [Aristotle]
`Physics (Physicae Auscultationes)
<http://classics.mit.edu/Aristotle/physics.html>`_
Aristotle, 350 BC.
.. [Celik-2007]
`Communication Protocols <http://tantek.pbwiki.com/CommunicationProtocols>`_
Tantek Ãelik, 2007.
.. [Easton-1997]
`The Ethical Slut
<http://www.amazon.com/Ethical-Slut-Infinite-Sexual-Possibilities/dp/1890159018>`_
Dossie Easton and Catherine A. Liszt, Greenery Press (CA), December 1997
.. [Gandhi-1927]
`The Story of My Experiments with Truth
<http://www.amazon.com/Gandhi-Autobiography-Story-Experiments-Truth/dp/0807059099>`_
Mohandas Karamchand (Mahatma) Gandhi, 1927.
.. [Ginsburgh]
`Tav: The Seal of Creation <http://www.inner.org/hebleter/tav.htm>`_
Gal Einai Institute (from the teachings of Rabbi Yitzchak Ginsburgh).
.. [Hardy-1895]
`Jude The Obscure <http://www.bibliomania.com/0/0/26/57/>`_
Thomas Hardy, 1895.
.. [Jordan-1990]
`The Eye of the World
<http://www.amazon.com/Eye-World-Wheel-Time-Book/dp/0812511816>`_
Robert Jordan, Tor Fantasy, November 1990.
.. [Ovid]
`Remedia Amoris (Love's Cure)
<http://www.sacred-texts.com/cla/ovid/lboo/lboo61.htm>`_
Publius Ovidius Naso (Ovid), 5 BC.
.. [Palmer-2004]
`WTF 1: On Espia, Tav, and the Plex <http://infomesh.net/200X/wtf1>`_
Sean B. Palmer, March 2004.
.. [Tav-2007]
`A Missive From a Heart to That Thing Sitting on the Shelf
<http://loves-cure.blogspot.com/2007/02/missive-from-heart-to-that-thing.html>`_
Tav, February 2007.
|
tav/oldblog
|
af56aaf6164ac8de8ebfbcc2d4851b3ca064bf2d
|
Added a follow count box to the index page.
|
diff --git a/_layouts/index.genshi b/_layouts/index.genshi
index 13eff3f..8ae3b66 100644
--- a/_layouts/index.genshi
+++ b/_layouts/index.genshi
@@ -1,74 +1,121 @@
---
layout: site
license: Public Domain
title: The Journey to Espia
---
<div xmlns:py="http://genshi.edgewall.org/">
<?python
from operator import lt
from posixpath import splitext
+ from time import time
+ from urllib import quote_plus, urlencode
STATIC = 'http://cloud.github.com/downloads/tav/plexnet'
MONTHS = [
'Zero Month',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
last_post_name = ['']
def set_name(post):
last_post_name[0] = post['__name__']
return last_post_name[0]
site_url = 'http://tav.espians.com'
items = [item for item in yatidb.values() if (item.get('type', None) == 'post') and (item.get('created', None))]
?>
<style type="text/css">
+ .metrics { font-size: 16px; }
.more { display: none; }
.more-link { display: block; }
</style>
+<div class="metrics">
+ <table cellspacing="0" cellpadding="5px">
+ <tr>
+ <td rowspan="2" width="38px" valign="top">
+ <a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="gfx/icon.twitter.png" width="32px" height="32px" /></a>
+ </td>
+ <td valign="top">
+ <a href="http://twitter.com/tav" title="Follow @tav on Twitter"><strong class="twitter-followers">800+ followers</strong></a>
+ </td>
+ <td rowspan="2" width="44px" valign="top" class="center">
+ <a href="https://github.com/tav" title="Follow tav on GitHub"><img src="gfx/icon.octocat.png" width="32px" height="32px" /></a>
+ </td>
+ <td valign="top">
+ <a href="https://github.com/tav" title="Follow tav on GitHub"><strong class="github-followers">50+ followers</strong></a>
+ </td>
+ <td rowspan="2" width="50px" valign="top" class="center">
+
+ <a href="http://feeds.feedburner.com/asktav" rel="alternate"
+ type="application/rss+xml" title="Subscribe to Tav's Blog"><img
+ src="gfx/icon.rss.png" width="32px" height="32px" /></a>
+ </td>
+ <td valign="top">
+ <a href="http://feeds.feedburner.com/asktav" rel="alternate"
+ type="application/rss+xml" title="Subscribe to Tav's Blog"><strong class="rss-readers">120+ readers</strong></a>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://twitter.com/tav" title="Follow @tav on Twitter">Follow tav</a>
+ </td>
+ <td>
+ <a href="https://github.com/tav" title="Follow tav on GitHub">Follow on Github</a>
+ </td>
+ <td>
+ <a href="http://feeds.feedburner.com/asktav" rel="alternate"
+ type="application/rss+xml" title="Subscribe to Tav's Blog">Subscribe via RSS</a>
+ </td>
+ </tr>
+ </table>
+</div>
+<hr class="clear" />
+<br />
+<script type="text/javascript" src="js/metrics.js?${int(time()/4)}" />
+
<div py:for="post in sorted(items, key=lambda x: x['created'], reverse=True)[:60]">
<?python
post_url = disqus_url = 'http://tav.espians.com/' + set_name(post)
if lt(post['created'][:7], "2009-07"):
disqus_url = 'http://www.asktav.com' + '/' + post['__name__']
?>
<div class="post-title">
<div class="post-link"><a href="${set_name(post)}">${Markup(post['title'])}</a></div>
<div class="additional-content-info">
<div class="float-right">
<a href="${post['__name__']}#disqus_thread" rel="disqus:${disqus_url}">Add a Comment</a>
<script>
tweetmeme_url = '${post_url}';
tweetmeme_source = 'tav';
tweetmeme_service = 'bit.ly';
tweetmeme_style = 'compact';
</script>
·
<div class="retweetbutton">
<script src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
</div>
</div>
<div class="article-info">
» by <span><a href="http://tav.espians.com">tav</a></span> on <span py:with="created=post['created']" class="post-date">${MONTHS[int(created[5:7])]} ${int(created[8:10])}, ${created[:4]} @ <a href="http://github.com/tav/blog/commits/master/${splitext(post['__name__'])[0]}.txt">${created[-5:]}</a></span> <a href="http://creativecommons.org/publicdomain/zero/1.0/" title="Public Domain"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Cc-pd.svg/64px-Cc-pd.svg.png" width="20px" height="20px" alt="Public Domain" class="absmiddle" /></a>
</div>
</div>
<div class="content">
<div py:content="Markup(post['__lead_output__'])" class="blog-post" />
</div>
<br /><hr class="clear" />
<div py:if="post['__lead__'] != post['__content__']"><a href="${set_name(post)}">Read moreâ¦</a></div>
<div class="post-footer">
</div>
</div>
<div class="center"><a href="archive.html#article-${last_post_name[0]}">Older Articles</a></div>
</div>
|
tav/oldblog
|
13d4340fdd28644daea3879e5377aed032229197
|
Evicted cache for css/js.
|
diff --git a/_layouts/site.genshi b/_layouts/site.genshi
index 933b790..c1ff5fb 100644
--- a/_layouts/site.genshi
+++ b/_layouts/site.genshi
@@ -1,202 +1,202 @@
---
license: Public Domain
---
<!DOCTYPE html>
<html xmlns:py="http://genshi.edgewall.org/">
<head>
<title>${Markup(site_title)}<py:if test="defined('title')"> » ${Markup(title)}</py:if></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
<meta name="tweetmeme-title" content="${Markup(title)}" />
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<meta name="author" content="tav" />
<meta name="description" content="${site_description}" />
<meta name="copyright" content="This work has been placed into the Public Domain." />
<meta name="document-rating" content="general" />
<link rel="icon" type="image/png" href="gfx/aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds.feedburner.com/asktav" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
- href="css/site.css" />
+ href="css/site.css?decafbad2" />
<style type="text/css" media="print">
#ignore-this { display: none; }
</style>
<style type="text/css">
.ascii-art .literal-block {
line-height: 1em !important;
}
.cmd-line {
background-color: #000;
color: #fff;
padding: 5px;
margin-left: 2em;
margin-right: 2em;
}
.cmd-ps1 {
color: #999;
}
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
#site-title { padding-top: 0px; }
</style>
<![endif]-->
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://use.typekit.com/por2lgv.js"></script>
<script>
GOOGLE_ANALYTICS_CODE = "UA-90176-8";
GOOGLE_ANALYTICS_HOST = "tav.epians.com";
DISQUS_FORUM = 'asktav';
PAGE_URI = '${'http://tav.espians.com/' + __name__}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
</script>
- <script src="js/init.js?decafbad"></script>
+ <script src="js/init.js?decafbad2"></script>
</head>
<body>
<?python
from urllib import quote_plus, urlencode
def unescape(s):
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("&", "&")
return s
if __name__ == 'index.html':
page_url = 'http://tav.espians.com/'
page_title = quote_plus(site_title + u' â '.encode('utf-8') + unescape(title))
else:
page_url = 'http://tav.espians.com/' + __name__
if defined('title'):
page_title = quote_plus(unescape(title))
else:
page_title = site_title
?>
<div id="share-box">
<div><strong>Share !</strong></div>
<div><a href="http://twitter.com/share?text=RT+%40tav+${page_title}&${urlencode({'url': page_url})}" title="Retweet" class="share-twitter"><img src="gfx/icon.twitter.png" width="32px" height="32px" /></a></div>
<div><a href="http://news.ycombinator.com/submitlink?${urlencode({'u': page_url})}&t=${page_title}" title="Upvote on Hacker News"><img src="gfx/icon.hackernews.png" width="32px" height="32px" /></a></div>
<div><a href="http://www.reddit.com/submit?${urlencode({'url': page_url})}&title=${page_title}" title="Reddit"><img src="gfx/icon.reddit.png" width="32px" height="32px" /></a></div>
<div><a href="http://www.facebook.com/sharer.php?t=${page_title}&${urlencode({'u': page_url})}" title="Share on Facebook" class="share-fb"><img src="gfx/icon.facebook.png" width="32px" height="32px" /></a></div>
</div>
<div id="main">
<div id="site-header">
<a href="/" id="site-title" title="${site_title}">
Tav's Blog →
</a>
<div id="site-links">
<form id="translation_form"><select id="lang_select" onchange="translate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form>
<a href="/" title="${site_description}">Home</a>
<a href="archive.html" title="Site Index">Archive</a>
<a href="about-tav.html" title="About Tav">About Tav</a>
</div>
<hr class="clear" />
</div>
<div class="article-nav"></div>
<div id="intro">
<div class="center">
<img src="gfx/profile-smoking.jpg" />
</div>
<h1>
I'm Tav, a 28yr old from London. I enjoy working on large-scale
social, economic and technological systems.
</h1>
<strong>Follow</strong>
<div class="follow-link">
<a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="gfx/icon.twitter.png" /></a> <a href="http://twitter.com/tav" title="Follow @tav on Twitter">tav</a>
</div>
<div class="follow-link">
<a href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog"><img
src="gfx/icon.rss.png" /></a> <a
href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog">tav's blog</a>
</div>
<div class="follow-link">
<a href="https://github.com/tav" title="Follow @tav on GitHub"><img src="gfx/icon.github.png" class="absmiddle" /></a> <a href="https://github.com/tav" title="Follow @tav on GitHub">tav</a>
</div>
<br/>
<strong>Contact</strong>
<div class="follow-link">
<a href="mailto:tav@espians.com" title="Email tav@espians.com"><img src="gfx/icon.gmail.png" /></a> <a href="mailto:tav@espians.com" title="Email tav@espians.com">tav@espians.com</a>
</div>
<div class="follow-link">
<a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook"><img src="gfx/icon.facebook.png" /></a> <a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook">asktav</a>
</div>
<div class="follow-link">
<a href="skype:addname?name=tavespian" title="Contact tavespian on Skype"><img src="gfx/icon.skype.png" /></a> <a href="skype:addname?name=tavespian" title="Contact tavespian on Skype">tavespian</a>
</div>
</div>
<div id="page">
<div>${Markup(content)}</div>
</div>
<hr class="clear" />
<div class="article-nav"></div>
</div>
</body>
</html>
|
tav/oldblog
|
a61b62e21c5cdc76da2a803d371e004e7feb383d
|
Worked around ClearType issues reported by endangeredmassa.
|
diff --git a/_layouts/site.genshi b/_layouts/site.genshi
index e734857..933b790 100644
--- a/_layouts/site.genshi
+++ b/_layouts/site.genshi
@@ -1,205 +1,202 @@
---
license: Public Domain
---
<!DOCTYPE html>
<html xmlns:py="http://genshi.edgewall.org/">
<head>
<title>${Markup(site_title)}<py:if test="defined('title')"> » ${Markup(title)}</py:if></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
<meta name="tweetmeme-title" content="${Markup(title)}" />
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<meta name="author" content="tav" />
<meta name="description" content="${site_description}" />
<meta name="copyright" content="This work has been placed into the Public Domain." />
<meta name="document-rating" content="general" />
<link rel="icon" type="image/png" href="gfx/aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds.feedburner.com/asktav" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="css/site.css" />
<style type="text/css" media="print">
#ignore-this { display: none; }
</style>
<style type="text/css">
.ascii-art .literal-block {
line-height: 1em !important;
}
.cmd-line {
background-color: #000;
color: #fff;
padding: 5px;
margin-left: 2em;
margin-right: 2em;
}
.cmd-ps1 {
color: #999;
}
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
#site-title { padding-top: 0px; }
</style>
<![endif]-->
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://use.typekit.com/por2lgv.js"></script>
<script>
GOOGLE_ANALYTICS_CODE = "UA-90176-8";
GOOGLE_ANALYTICS_HOST = "tav.epians.com";
DISQUS_FORUM = 'asktav';
PAGE_URI = '${'http://tav.espians.com/' + __name__}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
- try{
- Typekit.load();
- } catch(e) {};
</script>
<script src="js/init.js?decafbad"></script>
</head>
<body>
<?python
from urllib import quote_plus, urlencode
def unescape(s):
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("&", "&")
return s
if __name__ == 'index.html':
page_url = 'http://tav.espians.com/'
page_title = quote_plus(site_title + u' â '.encode('utf-8') + unescape(title))
else:
page_url = 'http://tav.espians.com/' + __name__
if defined('title'):
page_title = quote_plus(unescape(title))
else:
page_title = site_title
?>
<div id="share-box">
<div><strong>Share !</strong></div>
<div><a href="http://twitter.com/share?text=RT+%40tav+${page_title}&${urlencode({'url': page_url})}" title="Retweet" class="share-twitter"><img src="gfx/icon.twitter.png" width="32px" height="32px" /></a></div>
<div><a href="http://news.ycombinator.com/submitlink?${urlencode({'u': page_url})}&t=${page_title}" title="Upvote on Hacker News"><img src="gfx/icon.hackernews.png" width="32px" height="32px" /></a></div>
<div><a href="http://www.reddit.com/submit?${urlencode({'url': page_url})}&title=${page_title}" title="Reddit"><img src="gfx/icon.reddit.png" width="32px" height="32px" /></a></div>
<div><a href="http://www.facebook.com/sharer.php?t=${page_title}&${urlencode({'u': page_url})}" title="Share on Facebook" class="share-fb"><img src="gfx/icon.facebook.png" width="32px" height="32px" /></a></div>
</div>
<div id="main">
<div id="site-header">
<a href="/" id="site-title" title="${site_title}">
Tav's Blog →
</a>
<div id="site-links">
<form id="translation_form"><select id="lang_select" onchange="translate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form>
<a href="/" title="${site_description}">Home</a>
<a href="archive.html" title="Site Index">Archive</a>
<a href="about-tav.html" title="About Tav">About Tav</a>
</div>
<hr class="clear" />
</div>
<div class="article-nav"></div>
<div id="intro">
<div class="center">
<img src="gfx/profile-smoking.jpg" />
</div>
<h1>
I'm Tav, a 28yr old from London. I enjoy working on large-scale
social, economic and technological systems.
</h1>
<strong>Follow</strong>
<div class="follow-link">
<a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="gfx/icon.twitter.png" /></a> <a href="http://twitter.com/tav" title="Follow @tav on Twitter">tav</a>
</div>
<div class="follow-link">
<a href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog"><img
src="gfx/icon.rss.png" /></a> <a
href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog">tav's blog</a>
</div>
<div class="follow-link">
<a href="https://github.com/tav" title="Follow @tav on GitHub"><img src="gfx/icon.github.png" class="absmiddle" /></a> <a href="https://github.com/tav" title="Follow @tav on GitHub">tav</a>
</div>
<br/>
<strong>Contact</strong>
<div class="follow-link">
<a href="mailto:tav@espians.com" title="Email tav@espians.com"><img src="gfx/icon.gmail.png" /></a> <a href="mailto:tav@espians.com" title="Email tav@espians.com">tav@espians.com</a>
</div>
<div class="follow-link">
<a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook"><img src="gfx/icon.facebook.png" /></a> <a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook">asktav</a>
</div>
<div class="follow-link">
<a href="skype:addname?name=tavespian" title="Contact tavespian on Skype"><img src="gfx/icon.skype.png" /></a> <a href="skype:addname?name=tavespian" title="Contact tavespian on Skype">tavespian</a>
</div>
</div>
<div id="page">
<div>${Markup(content)}</div>
</div>
<hr class="clear" />
<div class="article-nav"></div>
</div>
</body>
</html>
diff --git a/website/css/site.css b/website/css/site.css
index 181bc90..0380d94 100644
--- a/website/css/site.css
+++ b/website/css/site.css
@@ -1,594 +1,593 @@
/*
* aaken default stylesheet -- by tav
*
*/
a {
color: #0000dd;
text-decoration: underline;
}
a:hover, a:active {
text-decoration: none;
}
a.no-underline {
text-decoration: none;
}
a.no-underline:hover {
text-decoration: underline;
}
body {
background-color: #3e3935;
background-image: url("../gfx/bg.jpg");
font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
font-size: 18px;
margin: 0;
min-width: 1080px;
padding: 0;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-weight: normal !important;
clear: both;
font-size: 36px;
margin: 0;
}
h1 {
font-size: 30px;
margin: 18px 0 14px 0;
}
pre {
background-color: #fefef1;
border: 1px solid #f7a600;
border-left: 5px solid #f7a600;
color: #101010;
font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
overflow: hidden;
padding: 12px 15px 13px 12px;
margin: 20px 30px 0 20px;
-webkit-border-bottom-right-radius: 12px;
-moz-border-radius-bottomright: 12px;
border-bottom-right-radius: 12px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
}
pre:hover {
overflow: auto;
}
pre.ascii-art {
line-height: 1em;
}
pre code {
background-color: transparent;
border: 0;
padding: 0;
border: 1px solid #c00;
}
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
strong {
- font-family: "museo-1", "museo-2", Verdana, Arial, sans-serif;
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 1.4em;
font-weight: normal;
}
sup {
display: none;
}
li ul {
margin-top: 10px;
}
/* sections */
.content {
clear: both;
line-height: 1.5em;
margin-bottom: 1em;
}
#intro {
background: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
float: right;
padding: 5px 10px 10px 10px;
width: 200px;
line-height: 1.5em;
}
#intro h1 {
font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
font-size: 18px;
line-height: 27px;
margin: 18px 0 24px 0;
}
#main {
margin: 0px auto;
text-align: left;
width: 944px;
}
#page {
background: #fff;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
float: left;
width: 640px;
padding-left: 30px;
padding-right: 35px;
padding-top: 15px;
padding-bottom: 10px;
margin-bottom: 14px;
margin-right: 10px;
}
#site-header {
margin: 12px 0 14px 0;
text-align: right;
}
#site-title {
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border: 1px solid #fff;
color: #000;
font-family: "zalamander-caps-1","zalamander-caps-2", "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 3em;
float: left;
padding: 9px 15px 0px 15px;
text-decoration: none;
}
#site-title:hover {
border: 1px solid #000;
}
.wf-inactive #site-title {
padding-top: 0px;
padding-bottom: 8px;
}
#site-links {
padding-top: 4px;
}
#site-links a {
margin-left: 8px;
padding: 4px 6px;
text-decoration: none;
color: #fff;
font-size: 20px;
}
#site-links a:hover {
color: #000;
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#translation_form {
display: inline;
margin-right: 20px;
}
.follow-link {
margin: 12px 0 8px 16px;
}
/* disqus */
#dsq-global-toolbar, #dsq-sort-by, #dsq-like-tooltip {
display: none;
}
#dsq-subscribe, #dsq-footer, .dsq-item-trackback, #dsq-account-dropdown {
display: none;
}
#dsq-content h3 {
margin: 25px 0 25px 0 !important;
}
.dsq-comment-header a {
color: #2d2827;
}
/* rst classes */
.docinfo {
margin-left: 5px;
margin-top: 20px;
}
.abstract {
margin-top: 20px;
}
code, .literal {
background-color: #fefbf6;
border: 1px solid #dbd0be;
padding: 2px 4px;
font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
}
.topic-title {
font-weight: bold;
text-align: center;
}
.note {
color: #aaa;
margin-left: 10px;
font-style: italic;
}
.attention {
background-color: #FFC3C3;
padding: 1.5em;
margin-top: 1em;
margin-bottom: 1em;
text-align: center;
}
.admonition-title {
display: none
}
.highlight {
text-align: center;
border: 1px solid #c00;
background-color: #fff;
background-color: #c00;
color: #fff;
padding: 5px;
}
/* rst error */
.system-messages {
display: none;
}
/* toc */
.contents {
padding-left: 3em;
margin: 10px;
display: none;
}
.contents.toc-only {
display: block;
padding-left: 0;
margin: 0;
}
.contents.toc-only .topic-title {
display: none;
}
/* links */
a.fn-backref {
text-decoration: none;
}
a.footnote-reference {
vertical-align: super;
text-decoration: none;
}
/* tables */
table.docutils {
margin: 20px 30px 0 20px;
border-spacing: 0px;
}
table.docutils thead tr th {
background: #635b54;
color: #fff;
padding: 7px 10px;
font-weight: normal;
}
table.docutils td {
padding: 7px;
border-bottom: 1px dashed #d6d2cf;
}
table.docutils td .literal {
white-space: nowrap;
}
table.docutils thead tr th:first-child {
text-align: right;
}
table.docutils tr td:first-child {
text-align: right;
}
table.footnote, table.citation {
border: 0px;
padding: 5px;
margin: 5px;
}
table.citation td, table.footnote td {
border: 0px;
}
table.docutils td p, table.footnote td p, table.citation td p {
margin-top: 0px;
padding-top: 0px;
}
table.footnote td.label, table.citation td.label {
width: 12em;
padding-right: 10px;
text-align: right;
}
table.citation td.label a, table.footnote td.label a {
font-style: italic;
text-decoration: none;
color: #333;
}
p.caption {
color: #666;
font-style: italic;
margin-top: 5px;
padding-left: 5px;
text-align: center;
}
td p.first {
margin-top: 0;
}
td p.last {
margin-bottom: 0;
}
th.field-name, th.docinfo-name {
text-align: right;
padding-right: 5px;
white-space: nowrap;
}
table.field-list {
border: 0px;
}
table.field-list td {
border: 0px;
vertical-align: top;
padding: 1px;
}
/* doctest */
.doctest-output {
color: #a5504d;
}
.doctest-input {
color: #0d5d04;
}
.doctest-output {
color: #a5504d;
color: #c32528;
color: #bf5036;
}
.doctest-input {
color: #5d90cd;
color: #6a6a6a;
color: #0d5d04;
color: #27894f;
color: #00a33f;
color: #15973b;
color: #7f9a49;
color: #005d61;
color: #1d6c70;
color: #326008;
}
/* images */
img {
border: none;
vertical-align: top;
margin: 0;
padding: 0;
}
img.absmiddle {
vertical-align: middle;
}
/* lines */
hr {
noshade: noshade;
clear: both;
}
hr.clear {
clear: both;
height: 0;
width: 0;
margin: 0;
padding: 0;
color: #c00;
background-color: transparent;
border: 0px solid;
}
/* lists */
li {
margin-bottom: 10px;
}
/* utility classes */
.center {
text-align: center;
margin-top: 5px;
margin-bottom: 5px;
}
.hide {
display: none;
}
.image-caption {
font-style: italic;
text-align: right;
}
.float-left, .figure {
float: left;
padding: 5px;
margin-right: 12px;
border: 1px solid #ded0e8;
}
.figure {
width: 400px;
text-align: center;
}
.float-left-aligned {
float: left;
margin: 5px 12px 5px -30px;
}
.float-left-aligned .image-caption {
padding-top: 5px;
}
.float-right, .float-right-aligned {
float: right;
margin-left: 12px;
margin-bottom: 5px;
}
.float-right-aligned {
margin-right: -35px;
}
.float-right-aligned .image-caption {
padding-right: 5px;
}
.full-width, .full-width-lined {
clear: both;
margin-left: -30px;
margin-right: -35px;
}
.full-width pre {
margin: 0;
border-left: 0px;
border-right: 0px;
padding: 30px 35px 31px 30px;
-webkit-border-bottom-right-radius: 0px;
-moz-border-radius-bottomright: 0px;
border-bottom-right-radius: 0px;
-webkit-box-shadow: 0px 0px 0px transparent;
}
.full-width-lined {
border-bottom: 1px solid #cacaca;
border-top: 1px solid #cacaca;
margin-bottom: 20px;
margin-top: 20px;
}
.boxed {
border: 1px solid #cacaca;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
margin-top: 10px;
}
/* special */
h1.title {
display: none;
}
#abstract .topic-title {
display: none;
}
#table-of-contents .topic-title {
display: none;
}
.sidebox, .sidebox-grey {
padding: 17px 30px 17px 20px;
max-width: 180px;
float: right;
margin: 8px -35px 5px 10px;
}
.sidebox {
background-color: #dee;
border-right: 10px solid #488;
}
.sidebox-grey {
background-color: #eee;
border-right: 10px solid #888;
}
.intro-box {
clear: both;
width: 630px;
margin: 21px -35px 0 -30px;
background: #d6d2cf;
border-left: 10px solid #635b54;
padding: 15px 45px 16px 20px;
}
.intro-box a {
color: #635b54;
text-decoration: none;
background: url("../gfx/icon.link.gif") center right no-repeat;
padding-right: 17px;
margin-right: 3px;
}
diff --git a/website/js/init.js b/website/js/init.js
index 3739dd9..67d57c7 100644
--- a/website/js/init.js
+++ b/website/js/init.js
@@ -1,131 +1,223 @@
// Released into the public domain by tav <tav@espians.com>
var startup = function () {
var shareBoxDisplayed = false;
var displayShareBox = function () {
$(document).unbind('scroll', displayShareBox);
setTimeout(function () {
if (shareBoxDisplayed) {
return;
}
shareBoxDisplayed = true;
$('#share-box').show();
}, 1400);
};
$(document).bind('scroll', displayShareBox);
setTimeout(displayShareBox, 5000);
var query = '';
$("a").each(function(idx, elm) {
if (elm.rel && elm.rel.indexOf('disqus:') >= 0) {
query += 'url' + idx + '=' + encodeURIComponent(elm.rel.split('disqus:')[1]) + '&';
}
});
$.getScript('http://disqus.com/forums/' + DISQUS_FORUM + '/get_num_replies.js?' + query);
$('.share-twitter').click(function () {
window.open(this.href, 'twitter', 'width=600,height=429,scrollbars=yes');
return false;
});
$('.share-fb').click(function () {
window.open(this.href, 'fb', 'width=600,height=400,scrollbars=yes');
return false;
});
if (!document.getElementById('table-of-contents'))
return;
document.getElementById('table-of-contents').style.display = 'none';
var abstractob = document.getElementById('abstract');
var toc_handler = document.createElement('span');
toc_handler.id = "toc-handler";
var toc_handler_a = document.createElement('a');
toc_handler_a.href = "#";
toc_handler_a.appendChild(document.createTextNode("Table of Contents"));
var toc_status = 0;
toc_handler_a.onclick = function () {
if (toc_status == 0) {
toc_status = 1;
document.getElementById('table-of-contents').style.display = 'block';
return false;
} else {
toc_status = 0;
document.getElementById('table-of-contents').style.display = 'none';
return false;
}
};
toc_handler.appendChild(document.createTextNode(" [ "));
toc_handler.appendChild(toc_handler_a);
toc_handler.appendChild(document.createTextNode(" ]"));
var p_elems = abstractob.getElementsByTagName("p");
p_elems[p_elems.length - 1].appendChild(toc_handler);
toc_handler.style.fontSize = '0.9em';
var hrefs = document.getElementById('table-of-contents').getElementsByTagName('a');
for (var i=0; i < hrefs.length; i++) {
if (hrefs[i].href.indexOf('#ignore-this') != -1)
hrefs[i].parentNode.style.display = 'none';
}
};
// -----------------------------------------------------------------------------
// Utility Functions
// -----------------------------------------------------------------------------
var setupGoogleAnalytics = function () {
var proto = document.location.protocol;
if (proto === 'file:')
return;
window._gaq = [
['_setAccount', GOOGLE_ANALYTICS_CODE],
['_trackPageview']
];
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
if (proto === 'https:') {
ga.src = 'https://ssl.google-analytics.com/ga.js';
} else {
ga.src = 'http://www.google-analytics.com/ga.js';
}
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(ga, script);
})();
};
var translate = function (elem) {
var url = 'http://translate.google.com/translate?u=';
if (elem.options[elem.selectedIndex].value !="") {
parent.location= url + encodeURIComponent(PAGE_URI) + elem.options[elem.selectedIndex].value;
}
};
// -----------------------------------------------------------------------------
// Load Metrics
// -----------------------------------------------------------------------------
var loadMetrics = function loadMetrics(data) {
$('.twitter-followers').text(data['twitter'] + " followers");
$('.github-followers').text(data['github'] + " followers");
$('.rss-readers').text(data['rss'] + " readers");
};
// -----------------------------------------------------------------------------
// Init
// -----------------------------------------------------------------------------
setupGoogleAnalytics();
$(startup);
+// -----------------------------------------------------------------------------
+// Font Smoothing Detection
+// -----------------------------------------------------------------------------
+
+// Adapted from
+// http://www.useragentman.com/blog/2009/11/29/how-to-detect-font-smoothing-using-javascript/
+
+function detectFontSmoothing() {
+
+ // IE can be surprisingly helpful sometimes.
+ if (screen && typeof(screen.fontSmoothingEnabled) !== "undefined")
+ return screen.fontSmoothingEnabled;
+
+ var canvas = document.createElement('canvas'),
+ ctx,
+ script;
+
+ // Assume that non-IE older browsers are not running on Windows.
+ if (!canvas.getContext)
+ return null;
+
+ try {
+
+ // Create a 35x35 Canvas block.
+ canvas.width = "35";
+ canvas.height = "35";
+
+ // We must put this node into the body, otherwise
+ // Safari Windows does not report correctly.
+ canvas.style.display = 'none';
+ script = document.getElementsByTagName('script')[0];
+ script.parentNode.insertBefore(canvas, script);
+
+ // Draw a black letter 'O', 32px Arial.
+ ctx = canvas.getContext('2d');
+ ctx.textBaseline = "top";
+ ctx.font = "12px Arial";
+ ctx.fillStyle = "black";
+ ctx.strokeStyle = "black";
+ ctx.fillText("O", 0, 0);
+
+ // Start at (8,1) and search the canvas from left to right,
+ // top to bottom to see if we can find a non-black pixel. If
+ // so we return true.
+ for (var j=8; j <= 32; j++) {
+ for (var i = 1; i <= 32; i++) {
+ var imageData = ctx.getImageData(i, j, 1, 1).data,
+ alpha = imageData[3];
+ if (alpha != 255 && alpha != 0)
+ return true;
+ }
+ }
+ } catch (ex) {
+ // Something went wrong (for example, Opera cannot use the
+ // canvas fillText() method. Return null (unknown).
+ return null;
+ }
+
+ return false;
+
+};
+
+// -----------------------------------------------------------------------------
+// Handle Fonts
+// -----------------------------------------------------------------------------
+
+function loadStylesheet(_rules) {
+ var css = document.createElement('style'),
+ rules = document.createTextNode(_rules),
+ script = document.getElementsByTagName('script')[0];
+ css.type = "text/css";
+ if (css.styleSheet) {
+ css.styleSheet.cssText = rules.nodeValue;
+ } else {
+ css.appendChild(rules);
+ }
+ script.parentNode.insertBefore(css, script);
+};
+
+if (!(detectFontSmoothing() === false)) {
+ try {
+ Typekit.load();
+ if ($.browser.msie) {
+ loadStylesheet('code, pre, .literal { font-size: 17px; line-height: 20px; }');
+ }
+ } catch(e) {}
+} else {
+ try {
+ loadStylesheet('code, pre, .literal { font-family: Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace; font-size: 14px; line-height: 16px; } body, #intro h1 { font-family: Verdana, Arial, sans-serif; font-size: 13px; line-height: 23px; } .content { line-height: 23px; } em { font-style: normal !important; font-weight: bold; } .article-info { font-size: 11px; } #site-title { font-size: 54px; line-height: 60px; padding-bottom: 8px; } intro { font-size: 15px; } #intro strong { font-size: 24px; } .content a, #intro a, .article-nav a, .additional-content-info a, #disqus-comments-section a { font-weight: bold; }}');
+ Typekit.load();
+ } catch(e) {}
+}
|
tav/oldblog
|
85da0fa7eb3b76dcf5508791a10eb12ff7b18d12
|
Added setup.py call to the Fabric instructions.
|
diff --git a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
index dca3dee..1efffe2 100644
--- a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
+++ b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
@@ -1025,549 +1025,553 @@ For most serious deployments, you tend to have distinct environments, e.g.
testing, staging, production, etc. And `existing
<http://blog.jeremi.info/entry/my-git-workflow-to-deploy-an-application-to-appengine>`_
`fabric <http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/>`__
`setups <https://github.com/bueda/ops>`_ tend to have similarly named commands
so you can run things like:
.. syntax:: console
$ fab production deploy
Now, not being a fan of repeatedly adding the same functionality to all my
fabfiles, I've added staged deployment support to Fabric. You can enable it by
specifying an ``env.stages`` list value, e.g.
.. syntax:: python
env.stages = ['staging', 'production']
The first item in the list is taken to be the *default* and overridable commands
of the following structure are automatically generated for each item:
.. syntax:: python
@task(display=None)
def production():
puts("env.stage = production", prefix='system')
env.stage = 'production'
config_file = env.config_file
if config_file:
if not isinstance(config_file, basestring):
config_file = '%s.yaml'
try:
env.config_file = config_file % stage
except TypeError:
env.config_file = config_file
That is, it will update ``env.stage`` and ``env.config_file`` with the
appropriate values and print out a message, e.g.
.. syntax:: console
$ fab production check deploy
[system] env.stage = production
...
And if your fab command line call didn't start with one of the stages, it will
automatically run the one for the default stage, e.g.
.. syntax:: console
$ fab check deploy
[system] env.stage = staging
...
For added convenience, the environments are also listed when you run ``fab``
without any arguments, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
Available environments:
staging
production
And, for further flexibility, you can override ``env.stages`` with the
``FAB_STAGES`` environment variable. This takes a comma-separated list of
environment stages and, again, the first is treated as the default, e.g.
.. syntax:: console
$ FAB_STAGES=development,production fab deploy
[system] env.stage = development
...
The staged deployment support is compatible with the `YAML Config`_ support. So
if you set ``env.config_file`` to ``True``, it will automatically look for a
``<stage>.yaml`` file, e.g. ``production.yaml``
.. syntax:: python
env.config_file = True
However if you set it to a string which can be formatted, it will be replaced
with the name of the staged environment, e.g.
.. syntax:: python
env.config_file = 'etc/ampify/%s.yaml'
That is, for ``fab development``, the above will use
``etc/ampify/development.yaml``. And, finally, if ``env.config_file`` is simply
a string with no formatting characters, it will be used as is, i.e. the same
config file irregardless of ``env.stage``.
Default Settings Manager
------------------------
The default ``env.get_settings()`` can be found in the ``fabric.contrib.tav``
module. If ``env.config_file`` support isn't enabled it mimics the traditional
``@hosts`` behaviour, i.e. all the contexts are treated as host strings, e.g.
.. syntax:: pycon
>>> env.get_settings(('admin@dev1.ampify.it', 'dev3.ampify.it:2222'))
[{'host': 'dev1.ampify.it',
'host_string': 'admin@dev1.ampify.it',
'port': '22',
'user': 'admin'},
{'host': 'dev3.ampify.it',
'host_string': 'dev3.ampify.it',
'port': '2222',
'user': 'tav'}]
However, if ``env.config_file`` is enabled, then a YAML config file like the
following is expected:
.. syntax:: yaml
default:
shell: /bin/bash -l -c
app-servers:
directory: /var/ampify
hosts:
- dev1.ampify.it:
debug: on
- dev2.ampify.it
- dev3.ampify.it:
directory: /opt/ampify
- dev4.ampify.it
build-servers:
cmd: make build
directory: /var/ampify/build
hosts:
- build@dev5.ampify.it
- dev6.ampify.it:
user: tav
- dev7.ampify.it
hostinfo:
dev*.ampify.it:
user: dev
debug: off
dev3.ampify.it:
shell: /bin/tcsh -c
dev7.ampify.it:
user: admin
In the root of the config, everything except the ``default`` and ``hostinfo``
properties are assumed to be contexts. And in each of the contexts, everything
except the ``hosts`` property is assumed to be an ``env`` value.
Three distinct types of contexts are supported:
* Host contexts -- any context containing the ``.`` character but no slashes,
e.g. ``dev1.ampify.it``.
.. syntax:: pycon
>>> env.get_settings(
... ('tav@dev1.ampify.it', 'dev7.ampify.it', 'dev3.ampify.it')
... )
[{'debug': False,
'host': 'dev1.ampify.it',
'host_string': 'tav@dev1.ampify.it',
'port': '22',
'shell': '/bin/bash -l -c',
'user': 'tav'},
{'debug': False,
'host': 'dev7.ampify.it',
'host_string': 'dev7.ampify.it',
'port': '22',
'shell': '/bin/bash -l -c',
'user': 'admin'},
{'debug': False,
'host': 'dev3.ampify.it',
'host_string': 'dev3.ampify.it',
'port': '22',
'shell': '/bin/tcsh -c',
'user': 'dev'}]
The settings are composed in layers: first, any ``default`` values; any
matching ``*patterns`` in ``hostinfo``; any explicit matches within
``hostinfo``; any specific information embedded within the context itself,
e.g. ``user@host:port``.
* Non-host contexts, e.g. ``app-servers``.
.. syntax:: pycon
>>> env.get_settings(('app-servers',))
[{'debug': True,
'directory': '/var/ampify',
'host': 'dev1.ampify.it',
'host_string': 'dev1.ampify.it',
'port': '22',
'shell': '/bin/bash -l -c',
'user': 'dev'},
{'debug': False,
'directory': '/var/ampify',
'host': 'dev2.ampify.it',
'host_string': 'dev2.ampify.it',
'port': '22',
'shell': '/bin/bash -l -c',
'user': 'dev'},
{'debug': False,
'directory': '/opt/ampify',
'host': 'dev3.ampify.it',
'host_string': 'dev3.ampify.it',
'port': '22',
'shell': '/bin/tcsh -c',
'user': 'dev'},
{'debug': False,
'directory': '/var/ampify',
'host': 'dev4.ampify.it',
'host_string': 'dev4.ampify.it',
'port': '22',
'shell': '/bin/bash -l -c',
'user': 'dev'}]
First, the hosts are looked up in the ``hosts`` property of the specific
context and then a similar lookup is done for each of the hosts as with host
contexts with two minor differences:
1. Any context-specific values, e.g. the properties for ``app-servers``, are
added as a layer after any ``default`` values.
2. Any host-specific values defined within the context override everything
else.
* Composite contexts -- made up of a non-host context followed by a slash and
comma-separated hosts, e.g. ``app-servers/dev1.ampify.it,dev3.ampify.it``.
.. syntax:: pycon
>>> env.get_settings(('app-servers/dev1.ampify.it,dev3.ampify.it',))
[{'debug': True,
'directory': '/var/ampify',
'host': 'dev1.ampify.it',
'host_string': 'dev1.ampify.it',
'port': '22',
'shell': '/bin/bash -l -c',
'user': 'dev'},
{'debug': False,
'directory': '/opt/ampify',
'host': 'dev3.ampify.it',
'host_string': 'dev3.ampify.it',
'port': '22',
'shell': '/bin/tcsh -c',
'user': 'dev'}]
These are looked up similarly to non-host contexts, except that instead of
looking for ``hosts`` within the config, the specified hosts are used. This is
particularly useful for overriding contexts to a subset of servers from the
command-line.
All in all, I've tried to provide a reasonably flexible default -- but you are
welcome to override it to suit your particular needs, e.g. you might want to
load the config dynamically over the network, etc.
Finally, it's worth noting that all responses are cached by the default
``env.get_settings()`` -- making it very cheap to switch contexts.
Hyphenated Commands
-------------------
This is a minor point, but I find hyphens, e.g. ``deploy-ampify``, to be more
aesthetically pleasing than underscores, i.e. ``deploy_ampify``. So Fabric now
displays and supports hyphenated variants of all commands, e.g. for the
following fabfile:
.. syntax:: python
from fabric.api import *
@task
def deploy_ampify():
"""deploy the current version of ampify"""
...
The command listing shows:
.. syntax:: console
$ fab
Available commands:
deploy-ampify deploy the current version of ampify
And you can run the command with:
.. syntax:: console
$ fab deploy-ampify
Command Line Env Flags
----------------------
You can now update the ``env`` object directly from the command line using the
new env flags syntax:
* ``+<key>`` sets the value of the key to ``True``.
* ``+<key>:<value>`` sets the key to the given string value.
So, for the following content in your fabfile:
.. syntax:: python
env.config_file = 'deploy.yaml'
env.debug = False
Running the following will set ``env.config_file`` to the new value:
.. syntax:: console
$ fab <commands> +config_file:alt.yaml
And the following will set ``env.debug`` to ``True``:
.. syntax:: console
$ fab <commands> +debug
The env flags are all set in the order given on the command line and before any
commands are run (including the config file handling if one is specified). And
you can, of course, specify as many env flags as you want.
Optimisations
-------------
It won't make much of a difference, but for my own sanity I've made a bunch of
minor optimisations to Fabric, e.g.
* Removed repeated look-up of attributes within loops.
* Removed repeated local imports within functions.
* Removed redundant double-wrapping of functions within the ``@hosts`` and
``@roles`` decorators.
Colors Support
--------------
You can enable the optional colors support by setting ``env.colors``, i.e.
.. syntax:: python
env.colors = True
Here's a screenshot of it in action:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqge6/fabric-shell"><img
src="http://img.skitch.com/20110211-nep3wmpi33qb2c4a13bf7fsgja.png"
alt="Fabric with Colors" /></a>
</div>
You can customise the colors by modifying the ``env.color_settings`` property.
By default it is set to:
.. syntax:: python
env.color_settings = {
'abort': yellow,
'error': yellow,
'finish': cyan,
'host_prefix': green,
'prefix': red,
'prompt': blue,
'task': red,
'warn': yellow
}
You can find the color functions in the ``fabric.colors`` module.
Logging Improvements
--------------------
The builtin ``puts()`` and ``fastprint()`` logging functions have also been
extended with the optional ``format`` parameter and ``env.format`` support
similar to the ``local()`` and ``run()`` builtins, so that instead of having to
do something like:
.. syntax:: python
@task
def db_migrate():
puts(
"[%s] [database] migrating schemas for %s" %
(env.host_string, env.db_name)
)
You can now just do:
.. syntax:: python
env.format = True
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database')
And it will output something like:
.. syntax:: console
$ fab db-migrate
[somehost.com] [database] migrating schemas for ampify
The second parameter which was previously a boolean-only value that was used to
control whether the host string was printed or not, can now also be a string
value -- in which case the string will be used as the prefix instead of the host
string.
You can still control if a host prefix is *also* printed by using the new
optional ``show_host`` parameter, e.g.
.. syntax:: python
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database', show_host=False)
Will output something like:
.. syntax:: console
$ fab db-migrate
[database] migrating schemas for ampify
And if you'd enabled ``env.colors``, the prefix will be also colored according
to your settings!
Autocompletion
--------------
`Bash completion <http://www.debian-administration.org/articles/316>`_ is one of
those features that really helps you to be more productive. Just include the
following in your ``~/.bashrc`` or equivalent file and you'll be able to use
Fabric's new command completion support:
.. syntax:: bash
_fab_completion() {
COMPREPLY=( $( \
COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \
COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
OPTPARSE_AUTO_COMPLETE=1 $1 ) )
}
complete -o default -F _fab_completion fab
It completes on all available commands and command line options, e.g.
.. syntax:: console
$ fab --dis<tab>
--disable-known-hosts --disable-hooks --display
Also, since Fabric has no way of knowing which `command line env flags`_ and
contexts you might be using, you can specify additional autocompletion items as
an ``env.autocomplete`` list value, e.g.
.. syntax:: python
env.autocomplete = ['+config_file:', '+debug', '@db-servers']
This will then make those values available for you to autocomplete, i.e.
.. syntax:: console
$ fab +<tab>
+config_file: +debug
Backwards Compatibility
-----------------------
All these changes should be fully backwards compatible. That is, unless you
happen to have specified any of the new ``env`` variables like ``env.stages``,
your existing fabfiles should run as they've always done. Do let me know if this
is not the case...
Usage
-----
If you'd like to take advantage of these various changes, the simplest thing to
do is to clone my `pylibs repository <https://github.com/tav/pylibs>`_ and put
it on your ``$PYTHONPATH``, i.e.
.. syntax:: console
$ git clone git://github.com/tav/pylibs.git
- $ export PYTHONPATH=$PYTHONPATH:`pwd`/pylibs
+ $ cd pylibs
+
+ $ python setup.py
+
+ $ export PYTHONPATH=$PYTHONPATH:`pwd`
Then create a ``fab`` script somewhere on your ``$PATH`` with the following
content:
.. syntax:: python
#! /usr/bin/env python
from fabric.main import main
main()
Make sure the script is executable, i.e.
.. syntax:: console
$ chmod +x fab
And as long as you have Python 2.6+, you should be good to go...
.. class:: intro-box
https://github.com/tav/pylibs/tree/master/fabric
Next Steps
----------
I have been talking to the Fabric maintainers about merging these changes
upstream. And so far they've been quite positive. But, as you can imagine, there
are a number of competing ideas about what is best for Fabric's future.
So if you like these features, then do leave a comment expressing your support.
It'd really help getting these features into the next version of Fabric.
-- Thanks, tav
\ No newline at end of file
|
tav/oldblog
|
a06f299c034d5194ce26df6478a888fa88d0c15d
|
Added follow metrics and share box.
|
diff --git a/_layouts/post.genshi b/_layouts/post.genshi
index 8c3b200..28d6844 100644
--- a/_layouts/post.genshi
+++ b/_layouts/post.genshi
@@ -1,80 +1,120 @@
---
layout: site
license: Public Domain
---
<div xmlns:py="http://genshi.edgewall.org/">
<?python
from time import time
from operator import lt
from posixpath import splitext
from urllib import quote_plus, urlencode
def unescape(s):
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("&", "&")
return s
page_url = disqus_url = 'http://tav.espians.com/' + __name__
if defined('created') and lt(created[:7], "2009-07"):
disqus_url = 'http://www.asktav.com/' + __name__
MONTHS = [
'Zero Month',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
?>
<div class="article-title">
<div class="post-link"><a href="${__name__}">${Markup(title)}</a></div>
<div class="additional-content-info">
<a href="#disqus_thread" rel="disqus:${disqus_url}">Add a Comment</a>
<script type="text/javascript">
tweetmeme_url = '${page_url}';
tweetmeme_source = 'tav';
tweetmeme_service = 'bit.ly';
tweetmeme_style = 'compact';
</script>
·
<div class="retweetbutton">
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
</div>
<div class="article-info">
» by <a href="http://tav.espians.com">tav</a><span py:if="defined('created')"> on <span class="post-date">${MONTHS[int(created[5:7])]} ${int(created[8:10])}, ${created[:4]} @ <a href="http://github.com/tav/blog/commits/master/${splitext(__name__)[0]}.txt">${created[-5:]}</a></span></span> <a href="http://creativecommons.org/publicdomain/zero/1.0/" title="Public Domain"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Cc-pd.svg/64px-Cc-pd.svg.png" width="20px" height="20px" alt="Public Domain" class="absmiddle" /></a>
</div>
</div>
<!--<div py:if="not defined('created')" class="attention">
This is an early draft. Many sections are incomplete. A lot more is being written.
</div>-->
<div class="content">
<div py:content="Markup(content)"></div>
</div>
<hr class="clear" />
<div class="share">
If you found this post useful, then please<br />
- <a href="http://www.facebook.com/sharer.php?t=${quote_plus(unescape(title))}&${urlencode({'u': page_url})}" title="Share on Facebook" class="fb-share">share on Facebook</a>
- <a href="http://twitter.com/share?text=RT+%40tav+${quote_plus(unescape(title))}&${urlencode({'url': page_url})}" title="Retweet" class="twitter-share">or Tweet</a>
+ <a href="http://www.facebook.com/sharer.php?t=${quote_plus(unescape(title))}&${urlencode({'u': page_url})}" title="Share on Facebook" class="fb-share share-fb">share on Facebook</a>
+ <a href="http://twitter.com/share?text=RT+%40tav+${quote_plus(unescape(title))}&${urlencode({'url': page_url})}" title="Retweet" class="twitter-share share-twitter">or Tweet</a>
+</div>
+<div class="metrics">
+ <table cellspacing="0" cellpadding="3px">
+ <tr>
+ <td rowspan="2" width="24px" valign="top">
+ <a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="gfx/icon.twitter.png" width="24px" height="24px" /></a>
+ </td>
+ <td valign="top">
+ <a href="http://twitter.com/tav" title="Follow @tav on Twitter"><strong class="twitter-followers">800+ followers</strong></a>
+ </td>
+ <td rowspan="2" width="24px" valign="top">
+ <a href="https://github.com/tav" title="Follow tav on GitHub"><img src="gfx/icon.octocat.png" width="24px" height="24px" /></a>
+ </td>
+ <td valign="top">
+ <a href="https://github.com/tav" title="Follow tav on GitHub"><strong class="github-followers">50+ followers</strong></a>
+ </td>
+ <td rowspan="2" width="24px" valign="top">
+ <a href="http://feeds.feedburner.com/asktav" rel="alternate"
+ type="application/rss+xml" title="Subscribe to Tav's Blog"><img
+ src="gfx/icon.rss.png" width="24px" height="24px" /></a>
+ </td>
+ <td valign="top">
+ <a href="http://feeds.feedburner.com/asktav" rel="alternate"
+ type="application/rss+xml" title="Subscribe to Tav's Blog"><strong class="rss-readers">120+ readers</strong></a>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://twitter.com/tav" title="Follow @tav on Twitter">Follow tav</a>
+ </td>
+ <td>
+ <a href="https://github.com/tav" title="Follow tav on GitHub">Follow on Github</a>
+ </td>
+ <td>
+ <a href="http://feeds.feedburner.com/asktav" rel="alternate"
+ type="application/rss+xml" title="Subscribe to Tav's Blog">Subscribe via RSS</a>
+ </td>
+ </tr>
+ </table>
</div>
<hr class="clear" />
<br />
<script type="text/javascript">
ARTICLE_NAME = '${__name__}';
</script>
<script type="text/javascript" src="index.js?${int(time()/4)}" />
<div id="disqus-comments-section">
<script type="text/javascript">
disqus_url = "${disqus_url}";
disqus_title = "${Markup(title)}";
</script>
<div id="disqus_thread"></div><script type="text/javascript"
src="http://disqus.com/forums/${site_nick}/embed.js"></script><noscript><a
href="http://${site_nick}.disqus.com/?${urlencode({'url': disqus_url})}">View the forum
thread.</a></noscript>
</div>
+<script type="text/javascript" src="js/metrics.js?${int(time()/4)}" />
</div>
diff --git a/_layouts/site.genshi b/_layouts/site.genshi
index a3aed8d..e734857 100644
--- a/_layouts/site.genshi
+++ b/_layouts/site.genshi
@@ -1,180 +1,205 @@
---
license: Public Domain
---
<!DOCTYPE html>
<html xmlns:py="http://genshi.edgewall.org/">
<head>
<title>${Markup(site_title)}<py:if test="defined('title')"> » ${Markup(title)}</py:if></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
<meta name="tweetmeme-title" content="${Markup(title)}" />
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<meta name="author" content="tav" />
<meta name="description" content="${site_description}" />
<meta name="copyright" content="This work has been placed into the Public Domain." />
<meta name="document-rating" content="general" />
<link rel="icon" type="image/png" href="gfx/aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds.feedburner.com/asktav" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="css/site.css" />
<style type="text/css" media="print">
#ignore-this { display: none; }
</style>
<style type="text/css">
.ascii-art .literal-block {
line-height: 1em !important;
}
.cmd-line {
background-color: #000;
color: #fff;
padding: 5px;
margin-left: 2em;
margin-right: 2em;
}
.cmd-ps1 {
color: #999;
}
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
#site-title { padding-top: 0px; }
</style>
<![endif]-->
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://use.typekit.com/por2lgv.js"></script>
<script>
GOOGLE_ANALYTICS_CODE = "UA-90176-8";
GOOGLE_ANALYTICS_HOST = "tav.epians.com";
DISQUS_FORUM = 'asktav';
PAGE_URI = '${'http://tav.espians.com/' + __name__}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
try{
Typekit.load();
} catch(e) {};
</script>
<script src="js/init.js?decafbad"></script>
</head>
<body>
+<?python
+ from urllib import quote_plus, urlencode
+ def unescape(s):
+ s = s.replace("<", "<")
+ s = s.replace(">", ">")
+ s = s.replace("&", "&")
+ return s
+
+ if __name__ == 'index.html':
+ page_url = 'http://tav.espians.com/'
+ page_title = quote_plus(site_title + u' â '.encode('utf-8') + unescape(title))
+ else:
+ page_url = 'http://tav.espians.com/' + __name__
+ if defined('title'):
+ page_title = quote_plus(unescape(title))
+ else:
+ page_title = site_title
+?>
+<div id="share-box">
+ <div><strong>Share !</strong></div>
+ <div><a href="http://twitter.com/share?text=RT+%40tav+${page_title}&${urlencode({'url': page_url})}" title="Retweet" class="share-twitter"><img src="gfx/icon.twitter.png" width="32px" height="32px" /></a></div>
+ <div><a href="http://news.ycombinator.com/submitlink?${urlencode({'u': page_url})}&t=${page_title}" title="Upvote on Hacker News"><img src="gfx/icon.hackernews.png" width="32px" height="32px" /></a></div>
+ <div><a href="http://www.reddit.com/submit?${urlencode({'url': page_url})}&title=${page_title}" title="Reddit"><img src="gfx/icon.reddit.png" width="32px" height="32px" /></a></div>
+ <div><a href="http://www.facebook.com/sharer.php?t=${page_title}&${urlencode({'u': page_url})}" title="Share on Facebook" class="share-fb"><img src="gfx/icon.facebook.png" width="32px" height="32px" /></a></div>
+</div>
<div id="main">
<div id="site-header">
<a href="/" id="site-title" title="${site_title}">
Tav's Blog →
</a>
<div id="site-links">
<form id="translation_form"><select id="lang_select" onchange="translate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form>
<a href="/" title="${site_description}">Home</a>
<a href="archive.html" title="Site Index">Archive</a>
<a href="about-tav.html" title="About Tav">About Tav</a>
</div>
<hr class="clear" />
</div>
<div class="article-nav"></div>
<div id="intro">
<div class="center">
<img src="gfx/profile-smoking.jpg" />
</div>
<h1>
I'm Tav, a 28yr old from London. I enjoy working on large-scale
social, economic and technological systems.
</h1>
<strong>Follow</strong>
<div class="follow-link">
<a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="gfx/icon.twitter.png" /></a> <a href="http://twitter.com/tav" title="Follow @tav on Twitter">tav</a>
</div>
<div class="follow-link">
<a href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog"><img
src="gfx/icon.rss.png" /></a> <a
href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog">tav's blog</a>
</div>
<div class="follow-link">
<a href="https://github.com/tav" title="Follow @tav on GitHub"><img src="gfx/icon.github.png" class="absmiddle" /></a> <a href="https://github.com/tav" title="Follow @tav on GitHub">tav</a>
</div>
<br/>
<strong>Contact</strong>
<div class="follow-link">
<a href="mailto:tav@espians.com" title="Email tav@espians.com"><img src="gfx/icon.gmail.png" /></a> <a href="mailto:tav@espians.com" title="Email tav@espians.com">tav@espians.com</a>
</div>
<div class="follow-link">
<a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook"><img src="gfx/icon.facebook.png" /></a> <a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook">asktav</a>
</div>
<div class="follow-link">
<a href="skype:addname?name=tavespian" title="Contact tavespian on Skype"><img src="gfx/icon.skype.png" /></a> <a href="skype:addname?name=tavespian" title="Contact tavespian on Skype">tavespian</a>
</div>
</div>
<div id="page">
<div>${Markup(content)}</div>
</div>
<hr class="clear" />
<div class="article-nav"></div>
</div>
</body>
</html>
diff --git a/getmetrics.py b/getmetrics.py
new file mode 100755
index 0000000..2644de0
--- /dev/null
+++ b/getmetrics.py
@@ -0,0 +1,55 @@
+#! /usr/bin/env python
+
+from simplejson import dumps as encode_json, loads as decode_json
+from time import sleep, time
+from traceback import print_exc
+from urllib import urlopen
+from xml.etree import ElementTree
+
+# ------------------------------------------------------------------------------
+# Constants
+# ------------------------------------------------------------------------------
+
+output = 'website/js/metrics.js'
+
+github = 'http://github.com/api/v2/json/user/show/tav'
+
+feedburner = "http://feedburner.google.com/api/awareness/1.0/GetFeedData?id=pel7nkvcgomc4kvih3ue7su4dg"
+
+twitter = "http://api.twitter.com/1/users/show/tav.json"
+
+# ------------------------------------------------------------------------------
+# Get Info
+# ------------------------------------------------------------------------------
+
+def main():
+ data = {}
+ info = ElementTree.fromstring(urlopen(feedburner).read())
+ data['rss'] = int(info.find('feed/entry').get('circulation'))
+ info = decode_json(urlopen(twitter).read())
+ data['twitter'] = info['followers_count']
+ info = decode_json(urlopen(github).read())
+ data['github'] = info['user']['followers_count']
+ for key, val in data.items():
+ if val > 1000:
+ val = '%s,%03d' % divmod(val, 1000)
+ else:
+ val = str(val)
+ data[key] = val
+ js = open(output, 'wb')
+ js.write('loadMetrics(')
+ js.write(encode_json(data))
+ js.write(');\n')
+ js.close()
+ print time(), data
+
+# ------------------------------------------------------------------------------
+# Run Loop
+# ------------------------------------------------------------------------------
+
+while 1:
+ try:
+ main()
+ except Exception:
+ print_exc()
+ sleep(60 * 15)
diff --git a/website/css/site.css b/website/css/site.css
index 5489f3d..181bc90 100644
--- a/website/css/site.css
+++ b/website/css/site.css
@@ -1,540 +1,541 @@
/*
* aaken default stylesheet -- by tav
*
*/
a {
color: #0000dd;
text-decoration: underline;
}
a:hover, a:active {
text-decoration: none;
}
a.no-underline {
text-decoration: none;
}
a.no-underline:hover {
text-decoration: underline;
}
body {
background-color: #3e3935;
background-image: url("../gfx/bg.jpg");
font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
font-size: 18px;
margin: 0;
+ min-width: 1080px;
padding: 0;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-weight: normal !important;
clear: both;
font-size: 36px;
margin: 0;
}
h1 {
font-size: 30px;
margin: 18px 0 14px 0;
}
pre {
background-color: #fefef1;
border: 1px solid #f7a600;
border-left: 5px solid #f7a600;
color: #101010;
font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
overflow: hidden;
padding: 12px 15px 13px 12px;
margin: 20px 30px 0 20px;
-webkit-border-bottom-right-radius: 12px;
-moz-border-radius-bottomright: 12px;
border-bottom-right-radius: 12px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
}
pre:hover {
overflow: auto;
}
pre.ascii-art {
line-height: 1em;
}
pre code {
background-color: transparent;
border: 0;
padding: 0;
border: 1px solid #c00;
}
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
strong {
font-family: "museo-1", "museo-2", Verdana, Arial, sans-serif;
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 1.4em;
font-weight: normal;
}
sup {
display: none;
}
li ul {
margin-top: 10px;
}
/* sections */
.content {
clear: both;
line-height: 1.5em;
margin-bottom: 1em;
}
#intro {
background: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
float: right;
padding: 5px 10px 10px 10px;
width: 200px;
line-height: 1.5em;
}
#intro h1 {
font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
font-size: 18px;
line-height: 27px;
margin: 18px 0 24px 0;
}
#main {
margin: 0px auto;
text-align: left;
width: 944px;
}
#page {
background: #fff;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
float: left;
width: 640px;
padding-left: 30px;
padding-right: 35px;
padding-top: 15px;
padding-bottom: 10px;
margin-bottom: 14px;
margin-right: 10px;
}
#site-header {
margin: 12px 0 14px 0;
text-align: right;
}
#site-title {
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border: 1px solid #fff;
color: #000;
font-family: "zalamander-caps-1","zalamander-caps-2", "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 3em;
float: left;
padding: 9px 15px 0px 15px;
text-decoration: none;
}
#site-title:hover {
border: 1px solid #000;
}
.wf-inactive #site-title {
padding-top: 0px;
padding-bottom: 8px;
}
#site-links {
padding-top: 4px;
}
#site-links a {
margin-left: 8px;
padding: 4px 6px;
text-decoration: none;
color: #fff;
font-size: 20px;
}
#site-links a:hover {
color: #000;
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#translation_form {
display: inline;
margin-right: 20px;
}
.follow-link {
margin: 12px 0 8px 16px;
}
/* disqus */
#dsq-global-toolbar, #dsq-sort-by, #dsq-like-tooltip {
display: none;
}
#dsq-subscribe, #dsq-footer, .dsq-item-trackback, #dsq-account-dropdown {
display: none;
}
#dsq-content h3 {
margin: 25px 0 25px 0 !important;
}
.dsq-comment-header a {
color: #2d2827;
}
/* rst classes */
.docinfo {
margin-left: 5px;
margin-top: 20px;
}
.abstract {
margin-top: 20px;
}
code, .literal {
background-color: #fefbf6;
border: 1px solid #dbd0be;
padding: 2px 4px;
font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
}
.topic-title {
font-weight: bold;
text-align: center;
}
.note {
color: #aaa;
margin-left: 10px;
font-style: italic;
}
.attention {
background-color: #FFC3C3;
padding: 1.5em;
margin-top: 1em;
margin-bottom: 1em;
text-align: center;
}
.admonition-title {
display: none
}
.highlight {
text-align: center;
border: 1px solid #c00;
background-color: #fff;
background-color: #c00;
color: #fff;
padding: 5px;
}
/* rst error */
.system-messages {
display: none;
}
/* toc */
.contents {
padding-left: 3em;
margin: 10px;
display: none;
}
.contents.toc-only {
display: block;
padding-left: 0;
margin: 0;
}
.contents.toc-only .topic-title {
display: none;
}
/* links */
a.fn-backref {
text-decoration: none;
}
a.footnote-reference {
vertical-align: super;
text-decoration: none;
}
/* tables */
table.docutils {
margin: 20px 30px 0 20px;
border-spacing: 0px;
}
table.docutils thead tr th {
background: #635b54;
color: #fff;
padding: 7px 10px;
font-weight: normal;
}
table.docutils td {
padding: 7px;
border-bottom: 1px dashed #d6d2cf;
}
table.docutils td .literal {
white-space: nowrap;
}
table.docutils thead tr th:first-child {
text-align: right;
}
table.docutils tr td:first-child {
text-align: right;
}
table.footnote, table.citation {
border: 0px;
padding: 5px;
margin: 5px;
}
table.citation td, table.footnote td {
border: 0px;
}
table.docutils td p, table.footnote td p, table.citation td p {
margin-top: 0px;
padding-top: 0px;
}
table.footnote td.label, table.citation td.label {
width: 12em;
padding-right: 10px;
text-align: right;
}
table.citation td.label a, table.footnote td.label a {
font-style: italic;
text-decoration: none;
color: #333;
}
p.caption {
color: #666;
font-style: italic;
margin-top: 5px;
padding-left: 5px;
text-align: center;
}
td p.first {
margin-top: 0;
}
td p.last {
margin-bottom: 0;
}
th.field-name, th.docinfo-name {
text-align: right;
padding-right: 5px;
white-space: nowrap;
}
table.field-list {
border: 0px;
}
table.field-list td {
border: 0px;
vertical-align: top;
padding: 1px;
}
/* doctest */
.doctest-output {
color: #a5504d;
}
.doctest-input {
color: #0d5d04;
}
.doctest-output {
color: #a5504d;
color: #c32528;
color: #bf5036;
}
.doctest-input {
color: #5d90cd;
color: #6a6a6a;
color: #0d5d04;
color: #27894f;
color: #00a33f;
color: #15973b;
color: #7f9a49;
color: #005d61;
color: #1d6c70;
color: #326008;
}
/* images */
img {
border: none;
vertical-align: top;
margin: 0;
padding: 0;
}
img.absmiddle {
vertical-align: middle;
}
/* lines */
hr {
noshade: noshade;
clear: both;
}
hr.clear {
clear: both;
height: 0;
width: 0;
margin: 0;
padding: 0;
color: #c00;
background-color: transparent;
border: 0px solid;
}
/* lists */
li {
margin-bottom: 10px;
}
/* utility classes */
.center {
text-align: center;
margin-top: 5px;
margin-bottom: 5px;
}
.hide {
display: none;
}
.image-caption {
font-style: italic;
text-align: right;
}
.float-left, .figure {
float: left;
padding: 5px;
margin-right: 12px;
border: 1px solid #ded0e8;
}
.figure {
width: 400px;
text-align: center;
}
.float-left-aligned {
float: left;
margin: 5px 12px 5px -30px;
}
.float-left-aligned .image-caption {
padding-top: 5px;
}
.float-right, .float-right-aligned {
float: right;
margin-left: 12px;
margin-bottom: 5px;
}
.float-right-aligned {
margin-right: -35px;
}
.float-right-aligned .image-caption {
padding-right: 5px;
}
.full-width, .full-width-lined {
clear: both;
margin-left: -30px;
margin-right: -35px;
}
.full-width pre {
margin: 0;
border-left: 0px;
border-right: 0px;
padding: 30px 35px 31px 30px;
-webkit-border-bottom-right-radius: 0px;
-moz-border-radius-bottomright: 0px;
border-bottom-right-radius: 0px;
-webkit-box-shadow: 0px 0px 0px transparent;
}
.full-width-lined {
border-bottom: 1px solid #cacaca;
border-top: 1px solid #cacaca;
margin-bottom: 20px;
margin-top: 20px;
}
.boxed {
border: 1px solid #cacaca;
-moz-border-radius: 5px;
@@ -547,578 +548,629 @@ li {
/* special */
h1.title {
display: none;
}
#abstract .topic-title {
display: none;
}
#table-of-contents .topic-title {
display: none;
}
.sidebox, .sidebox-grey {
padding: 17px 30px 17px 20px;
max-width: 180px;
float: right;
margin: 8px -35px 5px 10px;
}
.sidebox {
background-color: #dee;
border-right: 10px solid #488;
}
.sidebox-grey {
background-color: #eee;
border-right: 10px solid #888;
}
.intro-box {
clear: both;
width: 630px;
margin: 21px -35px 0 -30px;
background: #d6d2cf;
border-left: 10px solid #635b54;
padding: 15px 45px 16px 20px;
}
.intro-box a {
color: #635b54;
text-decoration: none;
background: url("../gfx/icon.link.gif") center right no-repeat;
padding-right: 17px;
margin-right: 3px;
}
.intro-box a:hover {
text-decoration: underline;
}
.double-column {
column-count: 2;
column-gap: 1.5em;
}
p.first {
display: inline;
}
/* document specific rules */
div#rationale a.external {
color: #888;
}
#ignore-this {
display: none;
}
.post-title {
clear: both;
margin-top: 1em;
margin-bottom: 2em;
border-top: 1px dashed #444;
padding-top: 1.4em;
line-height: 36px;
}
.post-link a {
color: #000;
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 36px;
font-weight: normal;
line-height: 36px;
text-decoration: none;
}
.post-footer {
margin-bottom: 9px;
}
.dulled {
color: #999;
font-style: italic;
}
.section-info {
padding-bottom: 1em;
border-bottom: 2px solid #544554;
margin-bottom: 1.5em;
margin-top: 1.2em;
}
.home-section-info {
margin-top: 1em;
text-align: right;
}
.right {
text-align: right;
}
.buffer {
margin-top: 6em;
}
.rss-entry { margin-bottom: 3em; }
.rss-entry .main, .feedburnerFeedBlock .main { font-size: 1.2em; padding: 25px; display: block; }
.feedburnerFeedBlock li {
list-style-type: none;
margin-bottom: 3em;
}
.feedburnerFeedBlock .headline {
display: none;
}
.section-header {
border-top: 3px solid #544554;
border-bottom: 3px solid #544554;
font-size: 2em;
text-align: center;
padding: 20px;
margin-bottom: 2em;
margin-top: 2em;
}
.index-link-info {
font-size: 0.8em;
color: #666;
}
.index-link-info a {
color: #666;
text-decoration: none;
}
.draft-article {
color: #ccc;
}
.if-time-permits {
border: 1px solid #ff6633;
padding: 4px;
color: #999;
}
.if-time-permits:before {
content: "IF TIME PERMITS";
background-color: #ff6633;
color: #fff;
padding: 5px;
margin-right: 3px;
margin-top: 3px;
}
a.button {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
}
a.button span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
}
a.button:active {
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.button:active span {
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
a.buttondown {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.buttondown span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
.tag-segment {
text-align: right;
}
.tag-segment span {
color: #fff;
padding: 0.5em;
font-size: 0.7em;
}
.tag-link {
text-decoration: none;
color: #000;
}
.tag {
background-color: #696969;
}
.tag-val-done {
background-color: #007f16;
background-color: #00782d;
background-color: #006400;
}
.tag-val-needsreview {
background-color: #a4ff00;
color: #000 !important;
}
.tag-val-inreview {
background-color: #3056bf;
}
.tag-val-todo {
background-color: #a60c00;
background-color: #d0006e;
background-color: #8B0000;
}
.tag-val-wip {
background-color: #a66e00;
background-color: #ff550f;
}
.tag-type-1 {
}
.tag-type-2 { /* #hashtags */
background-color: #2a4580;
background-color: #696969;
}
.tag-type-dep {
display: none;
}
.tag-type-milestone {
background-color: #00008B;
background-color: #06276f;
background-color: #a4ff00; /* nice colour! */
background-color: #002ca6;
background-color: #3056bf;
background-color: #898989;
}
.tag-type-priority {
background-color: #481254;
}
.tag-type-zuser {
background-color: #4573d5;
background-color: #696969;
}
#plan-tags a, #site-tags a {
margin-bottom: 0.7em;
}
#plan-container {
margin-top: 1.2em;
margin-bottom: 2.4em;
}
.plan-help {
font-size: 0.9em;
font-weight: bold;
text-align: right;
margin-bottom: 1.4em;
}
.retweetbutton { vertical-align: middle; display: inline; }
.retweetbutton iframe { vertical-align: middle; padding-bottom: 5px; }
#epigraph {
margin: 22px 40px;
color:#575757;
padding: 0 50px;
background: transparent url("http://cloud.github.com/downloads/tav/plexnet/gfx.blockquote.gif") no-repeat 0 0;
}
#epigraph-attribution {
text-align: right;
}
.article-nav {
color: #fff;
width: 705px;
margin: 0 0 14px 0;
display: none;
}
.article-nav a {
color: #fff;
text-decoration: none;
}
.article-nav a:hover {
color: #fff;
text-decoration: underline;
}
.article-title {
margin-top: 5px;
padding-bottom: 5px;
padding-top: 12px;
line-height: 36px;
}
.article-info {
color: #777;
font-size: 14px;
}
.article-info a {
color: #777;
text-decoration: none;
}
.article-info a:hover {
text-decoration: underline;
}
.additional-content-info {
float: right;
text-align: right;
margin-right: -35px;
}
.attention {
background-color: #bfeeff;
}
.more-link { display: none; }
.block-section {
border-top: 1px dashed #666;
margin-top: 20px;
padding-top: 20px;
}
/* Source code syntax highlighting */
.syntax .c { color: #919191 } /* Comment */
.syntax .cm { color: #919191 } /* Comment.Multiline */
.syntax .cp { color: #919191 } /* Comment.Preproc */
.syntax .cs { color: #919191 } /* Comment.Special */
.syntax .c1 { color: #919191 } /* Comment.Single */
.syntax .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.syntax .g { color: #101010 } /* Generic */
.syntax .gd { color: #d22323 } /* Generic.Deleted */
.syntax .ge { color: #101010; font-style: italic } /* Generic.Emph */
.syntax .gh { color: #101010 } /* Generic.Heading */
.syntax .gi { color: #589819 } /* Generic.Inserted */
.syntax .go { color: #6a6a6a } /* Generic.Output */
.syntax .gp { color: #bb8844 } /* Generic.Prompt */
.syntax .gr { color: #d22323 } /* Generic.Error */
.syntax .gs { color: #101010 } /* Generic.Strong */
.syntax .gt { color: #d22323 } /* Generic.Traceback */
.syntax .gu { color: #101010 } /* Generic.Subheading */
.syntax .k { color: #c32528 } /* Keyword */ /* espian red */
.syntax .k { color: #ff5600 } /* Keyword */ /* orangy */
.syntax .kc { color: #ff5600 } /* Keyword.Constant */
.syntax .kd { color: #ff5600 } /* Keyword.Declaration */
.syntax .kd { color: #ff5600 } /* Keyword.Declaration */
.syntax .kn { color: #ff5600 } /* Keyword */
.syntax .kp { color: #ff5600 } /* Keyword.Pseudo */
.syntax .kr { color: #ff5600 } /* Keyword.Reserved */
.syntax .kt { color: #ff5600 } /* Keyword.Type */
.syntax .l { color: #101010 } /* Literal */
.syntax .ld { color: #101010 } /* Literal.Date */
.syntax .m { color: #3677a9 } /* Literal.Number */ /* darkish pastely blue */
.syntax .m { color: #00a33f } /* Literal.Number */ /* brightish green */
.syntax .m { color: #1550a2 } /* Literal.Number */ /* darker blue */
.syntax .m { color: #5d90cd } /* Literal.Number */ /* pastely blue */
.syntax .mf { color: #5d90cd } /* Literal.Number.Float */
.syntax .mh { color: #5d90cd } /* Literal.Number.Hex */
.syntax .mi { color: #5d90cd } /* Literal.Number.Integer */
.syntax .il { color: #5d90cd } /* Literal.Number.Integer.Long */
.syntax .mo { color: #5d90cd } /* Literal.Number.Oct */
.syntax .bp { color: #a535ae } /* Name.Builtin.Pseudo */
.syntax .n { color: #101010 } /* Name */
.syntax .na { color: #bbbbbb } /* Name.Attribute */
.syntax .nb { color: #bf78cc } /* Name.Builtin */ /* pastely purple */
.syntax .nb { color: #af956f } /* Name.Builtin */ /* pastely light brown */
.syntax .nb { color: #a535ae } /* Name.Builtin */ /* brightish pastely purple */
.syntax .nc { color: #101010 } /* Name.Class */
.syntax .nd { color: #6d8091 } /* Name.Decorator */
.syntax .ne { color: #af956f } /* Name.Exception */
.syntax .nf { color: #3677a9 } /* Name.Function */
.syntax .nf { color: #1550a2 } /* Name.Function */
.syntax .ni { color: #101010 } /* Name.Entity */
.syntax .nl { color: #101010 } /* Name.Label */
.syntax .nn { color: #101010 } /* Name.Namespace */
.syntax .nn { color: #101010 } /* Name.Namespace */
.syntax .no { color: #101010 } /* Name.Constant */
.syntax .nx { color: #101010 } /* Name.Other */
.syntax .nt { color: #6d8091 } /* Name.Tag */
.syntax .nv { color: #101010 } /* Name.Variable */
.syntax .vc { color: #101010 } /* Name.Variable.Class */
.syntax .vg { color: #101010 } /* Name.Variable.Global */
.syntax .vi { color: #101010 } /* Name.Variable.Instance */
.syntax .py { color: #101010 } /* Name.Property */
.syntax .o { color: #ff5600 } /* Operator */ /* orangy */
.syntax .o { color: #101010 } /* Operator */
.syntax .ow { color: #101010 } /* Operator.Word */
.syntax .p { color: #101010 } /* Punctuation */
.syntax .s { color: #dd1144 } /* Literal.String */ /* darkish red */
.syntax .s { color: #c32528 } /* Literal.String */ /* espian red */
.syntax .s { color: #39946a } /* Literal.String */ /* pastely greeny */
.syntax .s { color: #5d90cd } /* Literal.String */ /* pastely blue */
.syntax .s { color: #00a33f } /* Literal.String */ /* brightish green */
.syntax .sb { color: #00a33f } /* Literal.String.Backtick */
.syntax .sc { color: #00a33f } /* Literal.String.Char */
.syntax .sd { color: #767676 } /* Literal.String.Doc */
.syntax .se { color: #00a33f } /* Literal.String.Escape */
.syntax .sh { color: #00a33f } /* Literal.String.Heredoc */
.syntax .si { color: #00a33f } /* Literal.String.Interpol */
.syntax .sr { color: #00a33f } /* Literal.String.Regex */
.syntax .ss { color: #00a33f } /* Literal.String.Symbol */
.syntax .sx { color: #00a33f } /* Literal.String.Other */
.syntax .s1 { color: #00a33f } /* Literal.String.Single */
.syntax .s2 { color: #00a33f } /* Literal.String.Double */
.syntax .w { color: #101010 } /* Text.Whitespace */
.syntax .x { color: #101010 } /* Other */
.syntax.bash .nb { color: #101010 }
.syntax.bash .nv { color: #c32528 }
.syntax.css .k { color: #606060 }
.syntax.css .nc { color: #c32528 }
.syntax.css .nf { color: #c32528 }
.syntax.css .nt { color: #c32528 }
.syntax.rst .k { color: #5d90cd }
.syntax.rst .ow { color: #5d90cd }
.syntax.rst .p { color: #5d90cd }
.syntax.yaml .l-Scalar-Plain { color: #5d90cd }
.syntax.yaml .p-Indicator { color: #101010 }
.footer-info {
border-top: 1px dotted #999;
border-bottom: 1px dotted #999;
padding: 10px 0;
}
.footer-info-block {
padding: 13px 10px 10px 37px;
}
.footer-info-block div {
margin-bottom: 10px;
}
table.borderless-table, .borderless-table tr, .borderless-table td {
border: 0px !important;
}
.share {
text-align: right;
- margin: 50px -20px 0px 0;
- margin: 50px 0px 0px 0;
+ margin-top: 40px;
font-size: 14px;
+ float: right;
}
a.fb-share, a.fb-share:active, a.fb-share:hover, a.fb-share:visited {
background: url("../gfx/share.facebook.png") no-repeat;
display: block;
float: right;
height: 22px;
outline; none;
overflow: hidden;
margin: 0 20px 0 14px;
margin: 10px 0px 0 14px;
position: relative;
text-indent: 9999px !important;
top: -2px;
vertical-align: middle;
width: 146px;
color: transparent;
}
a.fb-share:hover {
background: url("../gfx/share.facebook.png") no-repeat 0 -22px;
}
a.fb-share:active {
background: url("../gfx/share.facebook.png") no-repeat 0 -44px;
}
a.twitter-share, a.twitter-share:active, a.twitter-share:hover, a.twitter-share:visited {
background: url("../gfx/share.twitter.png") no-repeat;
display: block;
float: right;
height: 20px;
margin: 0 0 0 14px;
margin: 10px 0 0 14px;
outline: none;
overflow: hidden;
position: relative;
text-indent: 9999px !important;
vertical-align: middle;
width: 55px;
color: transparent;
}
a.twitter-share:hover {
background: url("../gfx/share.twitter.png") no-repeat 0 -21px;
}
a.twitter-share:active {
background: url("../gfx/share.twitter.png") no-repeat 0 -42px;
}
/* twitter widget version */
.twitter-share-button {
float: right;
vertical-align: middle;
display: inline;
padding-bottom: 4px;
}
.twitter-share-button iframe {
vertical-align: middle;
}
+
+.metrics {
+ float: left;
+ text-align: left;
+ font-size: 14px;
+ margin-top: 33px;
+ margin-left: -5px;
+}
+
+.metrics a {
+ color: #000;
+ text-decoration: none;
+}
+
+.metrics a:hover {
+ color: #333;
+ text-decoration: underline;
+}
+
+.metrics span {
+ font-size: 14px;
+}
+
+#share-box {
+ width: 48px;
+ position: fixed;
+ top: 240px;
+ background: #fff;
+ padding: 6px 3px 0px 2px;
+ text-align: center;
+ -webkit-border-bottom-right-radius: 5px;
+ -moz-border-radius-bottomright: 5px;
+ border-bottom-right-radius: 5px;
+ -webkit-border-top-right-radius: 5px;
+ -moz-border-radius-topright: 5px;
+ border-top-right-radius: 5px;
+ display: none;
+}
+
+#share-box div {
+ margin-bottom: 10px;
+ overflow: hidden;
+}
+
+#share-box a:hover {
+ opacity: 0.8;
+}
+
+#share-box strong {
+ font-size: 20px;
+}
diff --git a/website/gfx/icon.hackernews.png b/website/gfx/icon.hackernews.png
new file mode 100644
index 0000000..26b6384
Binary files /dev/null and b/website/gfx/icon.hackernews.png differ
diff --git a/website/gfx/icon.octocat.png b/website/gfx/icon.octocat.png
new file mode 100644
index 0000000..3dcc107
Binary files /dev/null and b/website/gfx/icon.octocat.png differ
diff --git a/website/gfx/icon.reddit.png b/website/gfx/icon.reddit.png
new file mode 100644
index 0000000..b38f8a0
Binary files /dev/null and b/website/gfx/icon.reddit.png differ
diff --git a/website/js/init.js b/website/js/init.js
index 76d5344..3739dd9 100644
--- a/website/js/init.js
+++ b/website/js/init.js
@@ -1,106 +1,131 @@
// Released into the public domain by tav <tav@espians.com>
var startup = function () {
+ var shareBoxDisplayed = false;
+ var displayShareBox = function () {
+ $(document).unbind('scroll', displayShareBox);
+ setTimeout(function () {
+ if (shareBoxDisplayed) {
+ return;
+ }
+ shareBoxDisplayed = true;
+ $('#share-box').show();
+ }, 1400);
+ };
+
+ $(document).bind('scroll', displayShareBox);
+ setTimeout(displayShareBox, 5000);
+
var query = '';
$("a").each(function(idx, elm) {
if (elm.rel && elm.rel.indexOf('disqus:') >= 0) {
query += 'url' + idx + '=' + encodeURIComponent(elm.rel.split('disqus:')[1]) + '&';
}
});
$.getScript('http://disqus.com/forums/' + DISQUS_FORUM + '/get_num_replies.js?' + query);
- $('.twitter-share').click(function () {
+ $('.share-twitter').click(function () {
window.open(this.href, 'twitter', 'width=600,height=429,scrollbars=yes');
return false;
});
- $('.fb-share').click(function () {
+ $('.share-fb').click(function () {
window.open(this.href, 'fb', 'width=600,height=400,scrollbars=yes');
return false;
});
if (!document.getElementById('table-of-contents'))
return;
document.getElementById('table-of-contents').style.display = 'none';
var abstractob = document.getElementById('abstract');
var toc_handler = document.createElement('span');
toc_handler.id = "toc-handler";
var toc_handler_a = document.createElement('a');
toc_handler_a.href = "#";
toc_handler_a.appendChild(document.createTextNode("Table of Contents"));
var toc_status = 0;
toc_handler_a.onclick = function () {
if (toc_status == 0) {
toc_status = 1;
document.getElementById('table-of-contents').style.display = 'block';
return false;
} else {
toc_status = 0;
document.getElementById('table-of-contents').style.display = 'none';
return false;
}
};
toc_handler.appendChild(document.createTextNode(" [ "));
toc_handler.appendChild(toc_handler_a);
toc_handler.appendChild(document.createTextNode(" ]"));
var p_elems = abstractob.getElementsByTagName("p");
p_elems[p_elems.length - 1].appendChild(toc_handler);
toc_handler.style.fontSize = '0.9em';
var hrefs = document.getElementById('table-of-contents').getElementsByTagName('a');
for (var i=0; i < hrefs.length; i++) {
if (hrefs[i].href.indexOf('#ignore-this') != -1)
hrefs[i].parentNode.style.display = 'none';
}
};
// -----------------------------------------------------------------------------
// Utility Functions
// -----------------------------------------------------------------------------
var setupGoogleAnalytics = function () {
var proto = document.location.protocol;
if (proto === 'file:')
return;
window._gaq = [
['_setAccount', GOOGLE_ANALYTICS_CODE],
['_trackPageview']
];
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
if (proto === 'https:') {
ga.src = 'https://ssl.google-analytics.com/ga.js';
} else {
ga.src = 'http://www.google-analytics.com/ga.js';
}
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(ga, script);
})();
};
var translate = function (elem) {
var url = 'http://translate.google.com/translate?u=';
if (elem.options[elem.selectedIndex].value !="") {
parent.location= url + encodeURIComponent(PAGE_URI) + elem.options[elem.selectedIndex].value;
}
};
+// -----------------------------------------------------------------------------
+// Load Metrics
+// -----------------------------------------------------------------------------
+
+var loadMetrics = function loadMetrics(data) {
+ $('.twitter-followers').text(data['twitter'] + " followers");
+ $('.github-followers').text(data['github'] + " followers");
+ $('.rss-readers').text(data['rss'] + " readers");
+};
+
// -----------------------------------------------------------------------------
// Init
// -----------------------------------------------------------------------------
setupGoogleAnalytics();
$(startup);
|
tav/oldblog
|
6c123e3a2bb0c10860e06f69ecb08a5ca7bb268a
|
Published the article on Fabric.
|
diff --git a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
index 8fa3c53..dca3dee 100644
--- a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
+++ b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
@@ -1,1241 +1,1573 @@
---
-created: 2011-02-14, 08:54
+created: 2011-02-21, 05:38
layout: post
-type: draft
license: Public Domain
---
======================================================
Fabric Python with Cleaner API and Parallel Deployment
======================================================
`Fabric <http://fabfile.org/>`_ is an awesome tool. Like `Capistrano
<https://github.com/capistrano/capistrano/wiki/2.x-Getting-Started>`_ and `Vlad
<http://rubyhitsquad.com/Vlad_the_Deployer.html>`_, it makes deployments a lot
simpler than with shell scripts on their own.
.. raw:: html
<div class="float-right-aligned">
<a href="http://www.flickr.com/photos/stars6/4381851322/in/photostream/"><img
src="http://farm3.static.flickr.com/2775/4381851322_d46fd7d75e.jpg"
alt="Datacenter Work" width="400px" height="267px" /></a><br />
<div class="image-caption">
by <a href="http://www.flickr.com/photos/stars6/">stars6</a>
</div>
</div>
However, once the complexity of your setup starts to grow, you very quickly
start wishing for a cleaner and more powerful API.
And once you are deploying to more than 30 servers, you really wish that Fabric
would run commands in parallel instead of doing them sequentially, one after
another.
Having recently experienced this pain, I decided to rework the core of Fabric.
I've documented it below -- describing all the changes to the `current Fabric
1.0a <http://docs.fabfile.org/1.0a/>`_ -- including funky new features like
``fab shell`` and staged deployments!
.. more
.. class:: intro-box
https://github.com/tav/pylibs/tree/master/fabric
Task Decorator
--------------
Traditionally, *all* functions within your ``fabfile.py`` were implicitly
exposed as Fabric commands. So once you started abstracting your script to be
more manageable, you had to use ``_underscore`` hacks to stop functions being
exposed as commands, e.g.
.. syntax:: python
from support.module import SomeClass as _SomeClass
from urllib import urlencode as _urlencode, urlopen as _urlopen
def _support_function():
...
Not only is this ugly and cumbersome, but it also goes against `The Zen of
Python <http://www.python.org/dev/peps/pep-0020/>`_ philosophy of "explicit is
better than implicit". So I've added a ``@task`` decorator to explicitly mark
functions as Fabric commands, e.g.
.. syntax:: python
from urllib import urlopen
from fabric.api import *
def get_latest_commit():
return urlopen('http://commits.server.com/latest').read()
@task
def check():
"""check if local changes have been committed"""
local_version = local('git rev-parse HEAD')
if local_version != get_latest_commit():
abort("!! Local changes haven't been committed !!")
@task
def deploy():
"""publish the latest version of the app"""
with cd('/var/app'):
run('git remote update')
run('git checkout %s' % get_latest_commit())
sudo("/etc/init.d/apache2 graceful")
The above uses ``@task`` to explicitly mark ``check`` and ``deploy`` as Fabric
commands so that they can be run as usual, i.e. ``fab check`` and ``fab
deploy``. Any functions and classes you import or define don't have to be
"hidden" with the ``_underscore`` hack.
For backwards compatibility, if you never use the ``@task`` decorator, you'll
continue to get the traditional behaviour.
YAML Config
-----------
It's preferable not to hard-code configurable values into fabfiles. This enables
you to reuse the same fabfile across different projects and keep it updated
without having to constantly copy, paste and modify.
So I've added native config support to Fabric. You can enable it by simply
specifying the ``env.config_file`` variable:
.. syntax:: python
env.config_file = 'deploy.yaml'
This will load and parse the specified `YAML file
<http://en.wikipedia.org/wiki/YAML>`_ before running any commands. The
configuration values will then be accessible from ``env.config``. This object is
simply a dictionary with dot-attribute access similar to the ``env`` dictionary.
You can then keep your fabfiles clean from hard-coded values, e.g.
.. syntax:: python
def get_latest_commit():
return urlopen(env.config.commits_server).read()
@task
def deploy():
with cd(env.config.app_directory):
...
Having configurable values also means that frameworks like Django could ship
default tasks for you to use, e.g.
.. syntax:: python
from django.fabric import deploy, test
Script Execution
----------------
It really helps to be able to quickly iterate the scripts that you will be
calling with Fabric. And whilst you should eventually create them as individual
files and sync them as part of your deployment, it'd be nice if you could try
them out during development.
To help with this I've added a new ``execute()`` builtin. This lets you execute
arbitrary scripts on remote hosts, e.g.
.. syntax:: python
@task
def stats():
memusage = execute("""
#! /usr/bin/env python
import psutil
pid = open('pidfile').read()
process = psutil.Process(int(pid))
print process.get_memory_percent()
""", 'memusage.py', verbose=False, dir='/var/ampify')
Behind the scenes, ``execute()`` will:
* Strip any common leading whitespace from every line in the source.
* Copy the source into a file on the remote server.
* If the optional ``name`` parameter (the 2nd parameter) had been specified,
then the given name will be used, otherwise an auto-generated name will be
used.
* If the optional ``dir`` parameter was specified, then the file will be created
within the given directory, otherwise it'll be created on the remote ``$HOME``
directory.
* The file will then be made executable, i.e. ``chmod +x``.
* And, finally, it will be run and the response will be returned. Unless the
``verbose`` parameter is set to ``False``, then it will by default also output
the response to the screen.
As you can imagine, ``execute()`` makes it very easy to rapidly try out and
-develop your development logic. Your scripts can be in whatever languages you
-can run on your remote hosts -- Ruby, Perl, Bash, Python, JavaScript, whatever.
+develop your deployment logic. Your scripts can be in whatever languages you can
+run on your remote hosts -- Ruby, Perl, Bash, Python, JavaScript, whatever.
Environment Variable Manager
----------------------------
When calling various command line tools, you often have to mess with environment
variables like ``$PATH``, ``$NODE_PATH``, ``$PYTHONPATH``, etc. To deal with
this, Fabric forced you to write things like:
.. syntax:: python
NODE_PATH = "NODE_PATH=$NODE_PATH:%s" % node_libs
run("%s vows" % NODE_PATH)
run("%s coffee -c amp.coffee" % NODE_PATH)
Instead you can now do:
.. syntax:: python
with env.NODE_PATH(node_libs):
run("vows")
run("coffee -c amp.coffee")
That is, if you call a property on the ``env`` object which is composed of only
-the ``ABCDEFGHIJKLMNOPQRSTUVWXYZ_`` characters, then a `Python Context Manager
+upper-case ASCII characters, then a `Python Context Manager
<http://www.python.org/dev/peps/pep-0343/>`_ is generated which will manage the
use of the environment variables for you.
The manager has the following constructor signature:
.. syntax:: python
manager(value, behaviour='append', sep=os.pathsep, reset=False)
So, if you'd called ``env.PATH(value, behaviour)``, the way the ``value`` is
treated will depend on the ``behaviour`` parameter which can be one of the
following:
* ``append`` -- appends value to the current ``$PATH``, i.e.
``PATH=$PATH:<value>``
* ``prepend`` -- prepends value to the current ``$PATH``, i.e.
``PATH=<value>:$PATH``
-* ``replace`` -- ignores ``$PATH`` altogether, i.e. ``PATH=<value>``
+* ``replace`` -- ignores current ``$PATH`` altogether, i.e. ``PATH=<value>``
The ``sep`` defaults to ``:`` on most platforms and determines how the values
-are concatenated. However, if you call the manager with no arguments at all or
+are concatenated. And if you call the manager with no arguments at all or
stringify it, it will return the string which would be used during execution,
e.g.
.. syntax:: python
print env.NODE_PATH # NODE_PATH=$NODE_PATH:/opt/ampify/libs/node
The various calls can be also nested, e.g.
.. syntax:: python
with env.PATH('/usr/local/bin'):
with env.PATH('/home/tav/bin'):
print env.PATH # PATH=$PATH:/usr/local/bin:/home/tav/bin
with env.PATH('/opt/local/bin', 'replace'):
with env.PATH('/bin', 'prepend'):
print env.PATH # PATH=/bin:/opt/local/bin
print env.PATH # PATH=$PATH:/usr/local/bin
You can specify ``reset=True`` to discard any nested values, e.g.
.. syntax:: python
with env.PATH('/opt/ampify/bin', 'prepend'):
with env.PATH('/home/tav/bin', reset=True):
print env.PATH # PATH=$PATH:/home/tav/bin
Extension Hooks
---------------
I've added native hooks support so that you can extend certain aspects of Fabric
without having to resort to monkey-patching. You attach functions to specific
hooks by using the new ``@hook`` decorator, e.g.
.. syntax:: python
@hook('config.loaded')
def default_config():
if 'port' in env.config:
return
port = prompt("port number?", default=8080, validate=int)
env.config.port = port
For the moment, only the following builtin hooks are defined. It's possible that
I may add support for individual ``<command>.before`` and ``<command>.after``
hooks, but so far I haven't needed that functionality.
+---------------------+-----------------------------+------------------------+
| Hook Name | Hook Function Signature | Description |
+=====================+=============================+========================+
| ``commands.before`` | ``func(cmds, cmds_to_run)`` | |hook-commands-before| |
+---------------------+-----------------------------+------------------------+
| ``config.loaded`` | ``func()`` | |hook-config-loaded| |
+---------------------+-----------------------------+------------------------+
| ``commands.after`` | ``func()`` | |hook-commands-after| |
+---------------------+-----------------------------+------------------------+
| ``listing.display`` | ``func()`` | |hook-listing-display| |
+---------------------+-----------------------------+------------------------+
.. |hook-config-loaded| replace::
Run after any config file has been parsed and loaded.
.. |hook-commands-after| replace::
Run after *all* the commands are run.
.. |hook-commands-before| replace::
Run before *all* the commands are run (including the config handling).
.. |hook-listing-display| replace::
Run when the commands listing has finished running in response to ``fab`` or
``fab --list``. Useful for adding extra info.
You can access the functions attached to a specific hook by calling
``hook.get()``, e.g.
.. syntax:: python
functions = hook.get('config.loaded')
You can also define your own custom hooks and call the attached functions by
using ``hook.call()``. This takes the hook name as the first parameter and all
subsequent parameters are used when calling the hook's attached functions.
Here's an example that shows ``hook.call()`` in action along with ``env.hook``
and the ability to attach the same function to multiple hooks by passing
multiple names to the ``@hook`` decorator:
.. syntax:: python
@hook('deploy.success', 'deploy.failure')
def irc_notify(release_id, info=None):
client = IrcClient('devbot', 'irc.freenode.net', '#esp')
if env.hook == 'deploy.success':
client.msg("Successfully deployed: %s" % release_id)
else:
client.msg("Failed deployment: %s" % release_id)
@hook('deploy.success')
def webhook_notify(release_id, info):
webhook.post({'id': release_id, 'payload': info})
@task
def deploy():
release_id = get_release_id()
try:
...
info = get_release_info()
except Exception:
hook.call('deploy.failure', release_id)
else:
hook.call('deploy.success', release_id, info)
And, finally, you can disable specific hooks via the ``--disable-hooks`` command
line option which takes space-separated patterns, e.g.
.. syntax:: console
$ fab deploy --disable-hooks 'config.loaded deploy.*'
You can override these disabled hooks in turn with the ``--enable-hooks``
option, e.g.
.. syntax:: console
$ fab deploy --disable-hooks 'deploy.*' --enable-hooks 'deploy.success'
Both ``hook.call()`` and ``hook.get()`` respect these command-line parameters,
so if you ever need to access the raw hook registry dict, you can access it
directly via ``hook.registry``.
Interpolation & Directories Support
-----------------------------------
Fabric provides a number of builtin functions that let you make command line
calls:
* ``local()`` -- runs a command on the local host.
* ``run()`` -- runs a command on a remote host.
* ``sudo()`` -- runs a sudoed command on a remote host.
I've added two optional parameters to these. A ``dir`` parameter can be used to
specify the directory from within which the command should be run, e.g.
.. syntax:: python
@task
def restart():
run("amp restart", dir='/opt/ampify')
And a ``format`` parameter can be used to access the new formatted strings
functionality, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}", format=True)
This makes use of the `Advanced String Formatting
<http://www.python.org/dev/peps/pep-3101/>`_ support that is available in Python
2.6 and later. The ``env`` object is used to look-up the various parameters,
i.e. the above is equivalent to:
.. syntax:: python
@task
def backup():
command = "backup.rb {app_directory} {s3_key}".format(**env)
run(command)
By default, ``format`` is set to ``False`` and the string is run without any
substitution. But if you happen to find formatting as useful a I do, you can
enable it as default by setting:
.. syntax:: python
env.format = True
You can then use it without having to constantly set ``format=True``, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}")
Fabric Contexts
---------------
I've used Fabric for everything from simple single-machine deployments to web
app deployments across multiple data centers to even physical multi-touch
installations at the `Museum of Australian Democracy
<http://www.moadoph.gov.au/exhibitions/prime-ministers-of-australia-exhibition/>`_.
And for everything but the simplest of setups, I've had to work around the
limited support offered by Fabric's ``@hosts`` and ``@roles`` in terms of:
* Managing configurable ``env`` values when dealing with different servers.
-* Executing workflows involving distinct sets of servers within the same Fabric
+* Executing workflows involving different sets of servers within the same Fabric
command, e.g. app servers, db servers, load balancers, etc.
And, clearly, I am `not
<http://lists.gnu.org/archive/html/fab-user/2009-05/msg00027.html>`_ `the
<http://lists.nongnu.org/archive/html/fab-user/2010-09/msg00023.html>`_ `only
<http://lists.nongnu.org/archive/html/fab-user/2010-12/msg00020.html>`_ `one
<http://lists.nongnu.org/archive/html/fab-user/2011-02/msg00005.html>`_ who has
experienced this pain. So I've introduced the notion of "contexts" and an
``env()`` context runner into the Fabric core. This means that you can now do
things like:
.. syntax:: python
- @task('app-servers')
- def deploy():
+ def purge_caches():
+ run('./purge-redis-cache', dir=env.redis_directory)
+ run('./purge-varnish-cache', dir=env.varnish_directory)
- env().run('./manage.py shutdown {app_directory}')
- env('build-servers').run('make build')
- env().run('./manage.py upgrade {app_directory}'
- env().run('./manage.py start {app_directory}'
+ @task
+ def deploy():
+ env('app-servers').run('./manage.py set-read-only {app_directory}')
+ env('db-servers').run('./upgrade.py {db_name}')
+ env('cache-servers').run(purge_caches)
+ env('app-servers').run('./manage.py restart {app_directory}')
And run it with a simple:
.. syntax:: console
$ fab deploy
-That's right. You no longer have to run insanely long command strings like:
+That's right. You no longer have to manually manage ``env`` values or run
+insanely long command strings like:
.. syntax:: console
$ fab run_tests freeze_requirements update_repository create_snapshot update_virtualenv update_media update_nginx graceful_migrate
-You might occasionally want to make a call on a subset of hosts for particular
-contexts. A utility ``.select()`` method is provided to help with this. If you
-pass it an integer value, it'll randomly choose as many values from the
-settings, e.g.
+You can call ``env()`` with a sequence of contexts as arguments and it'll act as
+a constructor for the new context runner object, e.g. with multiple contexts:
.. syntax:: python
- @task('build-servers')
- def build():
- env().select(3).run('{build_command}')
+ env('app-servers', 'db-servers')
-The ``.select()`` method can also take a filter function to let you do more
-custom selection, e.g. to select 2 build servers for each platform, you might do
-something like:
+And when you call a context runner method, e.g. ``.run()``, it will be run for
+each of the host/settings returned by ``env.get_settings()`` for the given
+contexts. So, for the following:
.. syntax:: python
- from itertools import groupby
- from random import sample
+ env('app-servers').run('./manage.py upgrade {app_directory}')
+What happens behind the scenes is somewhat equivalent to:
- def selector(settings):
- settings = sorted(settings, key=lambda s: s['platform'])
- grouped = groupby(settings, lambda s: s['platform'])
- return [sample(list(group), 2) for platform, group in grouped]
+.. syntax:: python
+ ctx = ('app-servers',)
+ responses = []
- @task('build-servers')
- def build():
- env().select(selector).run('{build_command}')
+ for cfg in env.get_settings(ctx):
+ with settings(ctx=ctx, **cfg):
+ response = run('./manage.py upgrade {app_directory}')
+ responses.append(response)
+
+ return responses
+
+That is, it is up to ``env.get_settings()`` to return the appropriate sequence
+of hosts and ``env`` settings for the given contexts, e.g.
+
+.. syntax:: python
+
+ [{'host_string': 'amp@appsrv21.espians.com', 'host': 'appsrv21.espians.com',
+ 'app_directory': '/opt/ampify'},
+ {'host_string': 'admin@appsrv23.espians.com', 'host': 'appsrv23.espians.com',
+ 'app_directory': '/var/ampify', 'shell': '/bin/tcsh -c'}]
And since deployment setups vary tremendously, instead of trying to make one
size fit all, I've made it so that you can define your own
``env.get_settings()`` function, e.g.
.. syntax:: python
from fabric.network import host_regex
- def get_settings(ctx):
+ def get_settings(contexts):
return [{
- 'host_string': host_string,
- 'host': host_regex.match(host_string).groupdict()['host']
- } for host_string in ctx]
+ 'host_string': context,
+ 'host': host_regex.match(context).groupdict()['host']
+ } for context in contexts]
env.get_settings = get_settings
-If any of the hosts threw an exception, then the corresponding element within
-``responses`` will contain it. Two new builtins are provided to quickly
-determine the nature of the response:
+It doesn't matter to Fabric what "context" means to you. In the above, for
+example, contexts are treated as hosts, e.g.
+
+.. syntax:: python
+
+ env('dev2.ampify.it', 'dev6.ampify.it')
+
+The default ``env.get_settings()`` interprets "contexts" in a specific way and
+this is described in the `Default Settings Manager`_ section. But you can simply
+override it to suit your specific deployment setup.
+
+
+Context Runner
+--------------
+
+The context runner supports a number of methods, including:
+
+* ``.execute()``
+
+* ``.local()``
+
+* ``.reboot()``
+
+* ``.run()``
+
+* ``.sudo()``
+
+They behave in the exact same way as their builtin counterparts. The return
+value for each of the calls will be a list-like object containing the response
+for each host in order, e.g.
+
+.. syntax:: python
+
+ responses = env('app-servers').sudo('make install')
+ for response in responses:
+ ...
+
+You can also pass in a function as the first parameter to ``.run()``. It will
+then be run for each of the hosts/settings. You can specify a ``warn_only=True``
+parameter to suppress and return any exceptions instead of raising them
+directly, e.g.
+
+.. syntax:: python
+
+ responses = env('app-servers').run(some_func, warn_only=True)
+ if succeeded(responses):
+ ...
+
+In addition, two new builtins are provided to quickly determine the nature of
+the responses:
* ``succeeded`` -- returns True if all the response items were successful.
* ``failed`` -- returns True if any of the response items failed or threw an
exception.
You can loop through the response and the corresponding host/setting values by
using the ``.ziphost()`` and ``.zipsetting()`` generator methods on the returned
list-like ``responses`` object, e.g.
+.. syntax:: python
+
+ responses = env('app-servers').multirun('make build')
+ for response, host in responses.ziphost():
+ ...
+
+You might occasionally want to make a call on a subset of hosts for particular
+contexts. A utility ``.select()`` method is provided to help with this. If you
+pass it an integer value, it'll randomly sample as many values from the
+settings, e.g.
+
.. syntax:: python
@task
- def deploy():
- responses = env('app-servers').multirun('make build')
- for response, host in responses.ziphost():
- ...
+ def build():
+ env('build-servers').select(3).run('{build_command}')
+
+The ``.select()`` method can also take a filter function to let you do more
+custom selection, e.g. to select 2 build servers for each platform, you might do
+something like:
-You can override the context for a task directly from the command line with the
-new ``@context`` syntax, e.g.
+.. syntax:: python
+
+ from itertools import groupby
+ from random import sample
+
+
+ def selector(settings):
+ settings = sorted(settings, key=lambda s: s['platform'])
+ grouped = groupby(settings, lambda s: s['platform'])
+ return [sample(list(group), 2) for platform, group in grouped]
-.. syntax:: console
- $ fab example1 @dev1.ampify.it
- ['dev1.ampify.it']
+ @task
+ def build():
+ env('build-servers').select(selector).run('{build_command}')
Parallel Deployment
-------------------
You no longer have to patiently wait whilst Fabric runs your commands on each
server one by one. By taking advantage of the ``.multirun()`` context runner
call, you can now run commands in parallel, e.g.
.. syntax:: python
@task
def deploy():
responses = env('app-servers').multirun('make build')
if failed(responses):
...
The above will run ``make build`` on the ``app-servers`` in parallel -- reducing
your deployment time significantly! The returned ``responses`` will be a list of
the individual responses from each host in order, just like with ``.run()``.
If any of the hosts threw an exception, then the corresponding element within
``responses`` will contain it. Exceptions will not be raised, irregardless of
whether you'd set ``warn_only`` -- it is up to you to deal with them.
By default you see the output from all hosts, but sometimes you just want a
summary, so you can specify ``condensed=True`` to ``.multirun()`` and it'll
provide a much quieter, running report instead, e.g.
::
[multirun] Running 'make build test' on 31 hosts
[multirun] Finished on dev2.ampify.it
[multirun] Finished on dev7.ampify.it
[multirun] 2/31 completed ...
Also, when dealing with large number of servers, you'll run into laggy servers
from time to time. And depending on your setup, it may not be critical that
*all* servers run the command. To help with this ``.multirun()`` takes two
optional parameters:
* ``laggards_timeout`` -- the number of seconds to wait for laggards once the
satisfactory number of responses have been received -- needs to be an int
value.
* ``wait_for`` -- the number of responses to wait for -- this should be an int,
but can also be a float value between ``0.0`` and ``1.0``, in which case it'll
be used as the factor of the total number of servers.
So, for the following:
.. syntax:: python
responses = env('app-servers').multirun(
'make build', laggards_timeout=20, wait_for=0.8
)
The ``make build`` command will be run on the various ``app-servers`` and once
80% of the responses have been received, it'll continue to wait up to 20 seconds
for any laggy servers before returning the responses.
The ``responses`` list will contain the new ``TIMEOUT`` builtin object for the
servers that didn't return a response in time. Like with the ``.run()`` context
runner call, ``.multirun()`` also accepts a function to execute instead of a
command string, e.g.
.. syntax:: python
env.format = True
def migrate_db():
run('./manage.py schemamigration --auto {app_name}')
run('./manage.py migrate {app_name}')
@task
def deploy():
env('frontends').multirun('routing --disable')
env('app-nodes').multirun(migrate_db)
env('frontends').multirun('routing --enable')
@task
def migrate():
env('app-nodes').multirun(migrate_db)
There's also a ``.multilocal()`` which runs the command locally for each of the
hosts in parallel, e.g.
.. syntax:: python
env.format = True
@task
def db_backup():
env('db-servers').multilocal('backup.rb {host}')
Behind the scenes, ``.multirun()`` uses ``fork()`` and `domain sockets
<http://en.wikipedia.org/wiki/Unix_domain_socket>`_, so it'll only work on Unix
platforms. You can specify the maximum number of parallel processes to spawn at
any one time by specifying ``env.multirun_pool_size`` which is set to ``10`` by
default, e.g.
.. syntax:: python
env.multirun_pool_size = 200
There's also an ``env.multirun_child_timeout`` which specifies the number of
seconds a child process will wait to hear from the parent before committing
suicide. It defaults to ``10`` seconds, but you can configure it to suit your
setup:
.. syntax:: python
env.multirun_child_timeout = 24
And, oh, there's also a ``.multisudo()`` for your convenience.
+Contextualised Tasks
+--------------------
+
+If you call ``env()`` without any contexts, it will use the contexts defined in
+the ``env.ctx`` tuple. This is automatically set by the context runner methods,
+but you can also set it by specifying contexts to the ``@task()`` decorator,
+e.g.
+
+.. syntax:: python
+
+ @task('app-servers')
+ def single():
+ print env.ctx
+
+
+ @task('app-servers', 'db-servers')
+ def multiple():
+ print env.ctx
+
+All this does is set ``env.ctx`` to the new tuple value, e.g.
+
+.. syntax:: console
+
+ $ fab single
+ ('app-servers',)
+
+ $ fab multiple
+ ('app-servers', 'db-servers')
+
+This is useful if you want to specify default contexts for a specific Fabric
+command, e.g.
+
+.. syntax:: python
+
+ @task('app-servers')
+ def deploy():
+
+ env().run('./manage.py set-read-only {app_directory}')
+ env('db-servers').run('./upgrade.py {db_name}')
+ env().run('./manage.py restart {app_directory}')
+
+One reason you might want to use default contexts is so that you can later use
+the new command line ``@context`` syntax to override it. So if you wanted to
+deploy to a specific server, perhaps a new one, you could do something like:
+
+.. syntax:: console
+
+ $ fab deploy @serv21.espians.com
+
+And ``serv21.espians.com`` will be used in place of ``app-servers``. You can
+specify multiple ``@context`` parameters on the command line and they will only
+apply to the immediately preceding Fabric command, e.g.
+
+.. syntax:: console
+
+ $ fab build @bld4.espians.com deploy @serv21.espians.com @serv22.espians.com
+
+
Fabric Shell
------------
Sometimes you just want to run a bunch of commands on a number of different
servers. So I've added a funky new feature -- Fabric shell mode:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqccu/python" title="Fabric Shell"><img
src="http://img.skitch.com/20110212-g8ha9cd5g441m4q3y21gewmnha.png" /></a>
</div>
Once you are in the shell, all of your commands will be sequentially ``run()``
on the respective hosts for your calling context. You can also use the
``.shell-command`` syntax to call shell builtin commands -- including your own
custom ones!
You start shells from within your Fabric commands by invoking the ``.shell()``
method of a context runner. Here's sample code to enable ``fab shell``:
.. syntax:: python
@task('app-servers')
def shell():
"""start a shell within the current context"""
env().shell(format=True)
The above defaults to the ``app-servers`` context when you run ``fab shell``,
but you can always override the context from the command line, e.g.
.. syntax:: console
$ fab shell @db-servers
And if your Python has been compiled with `readline support
<http://docs.python.org/library/readline.html>`_, then you can also leverage the
tab-completion support that I've added:
* Terms starting with ``{`` auto-complete on the properties within the ``env``
object to make it easy for you to use the string formatting support.
* Terms starting with ``.`` auto-complete on the available shell builtin
commands.
* All other terms auto-complete on the list of available executables on your
local machine's ``$PATH``.
Other readline features have been enabled too, e.g. command history with up/down
arrows, ``^r`` search and even cross-session history. You can configure where
the history is saved by setting ``env.shell_history_file`` which defaults to:
.. syntax:: python
env.shell_history_file = '~/.fab-shell-history'
Shell Builtins
--------------
As mentioned above, you can call various ``.shell-commands`` from within a
Fabric shell to do something other than ``run()`` a command on the various
hosts, e.g.
.. syntax:: irb
>> .multilocal backup.rb {host_string}
The above will run the equivalent of the following in parallel for each host:
.. syntax:: python
local("backup.rb {host_string}")
The following builtins are currently available:
* ``.cd`` -- changes the working directory for all future commands.
* ``.help`` -- displays a list of the available shell commands.
* ``.info`` -- list the current context and the respective hosts.
* ``.local`` -- runs the command locally.
* ``.multilocal`` -- runs the command in parallel locally for each host.
* ``.multirun`` -- runs the command in parallel on the various hosts.
* ``.multisudo`` -- runs the sudoed command in parallel on the various hosts.
* ``.sudo`` -- runs the sudoed command on the various hosts.
* ``.toggle-format`` -- toggles string formatting support.
-You can define your own by using the new ``@shell`` decorator, e.g.
+You can define your own using the new ``@shell`` decorator, e.g.
.. syntax:: python
@shell
def python_version(spec, arg):
with hide('running', 'output'):
- if arg == 'full':
- version = run('python -c "import sys; print sys.version"')
- else:
- version = run(
- "python -c 'import sys; print "
- '".".join(map(str, sys.version_info[:3]))\''
- )
+ version = run('./get-py-version')
puts("python %s" % version)
-The above can then be called from within a shell, e.g.
+And since the above satisfies the necessary ``func(spec, arg)`` function
+signature, it can be called from within a shell, e.g.
.. syntax:: irb
>> .python-version
[dev1.ampify.it] python 2.5.2
[dev3.ampify.it] python 2.7.0
The ``spec`` object is initialised with the various variables that the
``.shell()`` method was originally called with, e.g. ``dir``, ``format``, etc.
All changes made, e.g. ``spec.dir = '/var/ampify'``, are persistent and will
affect all subsequent commands within the shell.
The ``arg`` is a string value of everything following the shell command name,
e.g. for ``.local echo hi``, it will be ``"echo hi"``. The command name is
derived from the function name, but you can provide your own as the first
parameter to the ``@shell`` decorator.
And, finally, you can specify ``single=True`` to the ``@shell`` decorator to
specify that you only want the command to be run a single time and not
repeatedly for every host, e.g.
.. syntax:: python
@shell('hello', single=True)
def demo(spec, arg):
print "Hello", arg.upper()
-The above can then be called from within a shell, e.g.
+The above can then be called from within a shell and it won't repeat for every
+host/setting, e.g.
.. syntax:: irb
>> .hello tav
Hello TAV
The ``env.ctx`` is set for even single-mode shell commands, so you can always
take advantage of context runners, e.g.
.. syntax:: python
@shell
def backup(spec, arg):
env().multirun(...)
Command Line Listing
--------------------
When ``fab`` was run without any arguments, it used to spit out the help message
with the various command line options:
.. syntax:: console
$ fab
Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
Options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
-l, --list print list of possible commands and exit
--shortlist print non-verbose list of possible commands and exit
-d COMMAND, --display=COMMAND
print detailed info about a given command and exit
...
As useful as this was, I figured it'd be more useful to list the various
commands without having to constantly type ``fab --list``. So now when you run
``fab`` without any arguments, it lists the available commands instead, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
You can of course still access the help message by running either ``fab -h`` or
``fab --help``. And you can hide commands from being listed by specifying
-``display=None`` with the ``@task`` decorator, e.g.
+``display=None`` to the ``@task`` decorator, e.g.
.. syntax:: python
@task(display=None)
def armageddon():
...
Staged Deployment
-----------------
For most serious deployments, you tend to have distinct environments, e.g.
testing, staging, production, etc. And `existing
<http://blog.jeremi.info/entry/my-git-workflow-to-deploy-an-application-to-appengine>`_
`fabric <http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/>`__
`setups <https://github.com/bueda/ops>`_ tend to have similarly named commands
so you can run things like:
.. syntax:: console
$ fab production deploy
Now, not being a fan of repeatedly adding the same functionality to all my
fabfiles, I've added staged deployment support to Fabric. You can enable it by
specifying an ``env.stages`` list value, e.g.
.. syntax:: python
env.stages = ['staging', 'production']
The first item in the list is taken to be the *default* and overridable commands
of the following structure are automatically generated for each item:
.. syntax:: python
@task(display=None)
def production():
puts("env.stage = production", prefix='system')
env.stage = 'production'
-
-That is, it will update ``env.stage`` with the appropriate value and print out a
-message saying so, e.g.
+ config_file = env.config_file
+ if config_file:
+ if not isinstance(config_file, basestring):
+ config_file = '%s.yaml'
+ try:
+ env.config_file = config_file % stage
+ except TypeError:
+ env.config_file = config_file
+
+That is, it will update ``env.stage`` and ``env.config_file`` with the
+appropriate values and print out a message, e.g.
.. syntax:: console
$ fab production check deploy
[system] env.stage = production
...
And if your fab command line call didn't start with one of the stages, it will
automatically run the one for the default stage, e.g.
.. syntax:: console
$ fab check deploy
[system] env.stage = staging
...
For added convenience, the environments are also listed when you run ``fab``
without any arguments, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
Available environments:
staging
production
And, for further flexibility, you can override ``env.stages`` with the
``FAB_STAGES`` environment variable. This takes a comma-separated list of
environment stages and, again, the first is treated as the default, e.g.
.. syntax:: console
$ FAB_STAGES=development,production fab deploy
[system] env.stage = development
...
+The staged deployment support is compatible with the `YAML Config`_ support. So
+if you set ``env.config_file`` to ``True``, it will automatically look for a
+``<stage>.yaml`` file, e.g. ``production.yaml``
+
+.. syntax:: python
+
+ env.config_file = True
+
+However if you set it to a string which can be formatted, it will be replaced
+with the name of the staged environment, e.g.
+
+.. syntax:: python
+
+ env.config_file = 'etc/ampify/%s.yaml'
+
+That is, for ``fab development``, the above will use
+``etc/ampify/development.yaml``. And, finally, if ``env.config_file`` is simply
+a string with no formatting characters, it will be used as is, i.e. the same
+config file irregardless of ``env.stage``.
+
+
+Default Settings Manager
+------------------------
+
+The default ``env.get_settings()`` can be found in the ``fabric.contrib.tav``
+module. If ``env.config_file`` support isn't enabled it mimics the traditional
+``@hosts`` behaviour, i.e. all the contexts are treated as host strings, e.g.
+
+.. syntax:: pycon
+
+ >>> env.get_settings(('admin@dev1.ampify.it', 'dev3.ampify.it:2222'))
+ [{'host': 'dev1.ampify.it',
+ 'host_string': 'admin@dev1.ampify.it',
+ 'port': '22',
+ 'user': 'admin'},
+ {'host': 'dev3.ampify.it',
+ 'host_string': 'dev3.ampify.it',
+ 'port': '2222',
+ 'user': 'tav'}]
+
+However, if ``env.config_file`` is enabled, then a YAML config file like the
+following is expected:
+
+.. syntax:: yaml
+
+ default:
+ shell: /bin/bash -l -c
+
+ app-servers:
+ directory: /var/ampify
+ hosts:
+ - dev1.ampify.it:
+ debug: on
+ - dev2.ampify.it
+ - dev3.ampify.it:
+ directory: /opt/ampify
+ - dev4.ampify.it
+
+ build-servers:
+ cmd: make build
+ directory: /var/ampify/build
+ hosts:
+ - build@dev5.ampify.it
+ - dev6.ampify.it:
+ user: tav
+ - dev7.ampify.it
+
+ hostinfo:
+ dev*.ampify.it:
+ user: dev
+ debug: off
+ dev3.ampify.it:
+ shell: /bin/tcsh -c
+ dev7.ampify.it:
+ user: admin
+
+In the root of the config, everything except the ``default`` and ``hostinfo``
+properties are assumed to be contexts. And in each of the contexts, everything
+except the ``hosts`` property is assumed to be an ``env`` value.
+
+Three distinct types of contexts are supported:
+
+* Host contexts -- any context containing the ``.`` character but no slashes,
+ e.g. ``dev1.ampify.it``.
+
+ .. syntax:: pycon
+
+ >>> env.get_settings(
+ ... ('tav@dev1.ampify.it', 'dev7.ampify.it', 'dev3.ampify.it')
+ ... )
+ [{'debug': False,
+ 'host': 'dev1.ampify.it',
+ 'host_string': 'tav@dev1.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/bash -l -c',
+ 'user': 'tav'},
+ {'debug': False,
+ 'host': 'dev7.ampify.it',
+ 'host_string': 'dev7.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/bash -l -c',
+ 'user': 'admin'},
+ {'debug': False,
+ 'host': 'dev3.ampify.it',
+ 'host_string': 'dev3.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/tcsh -c',
+ 'user': 'dev'}]
+
+ The settings are composed in layers: first, any ``default`` values; any
+ matching ``*patterns`` in ``hostinfo``; any explicit matches within
+ ``hostinfo``; any specific information embedded within the context itself,
+ e.g. ``user@host:port``.
+
+* Non-host contexts, e.g. ``app-servers``.
+
+ .. syntax:: pycon
+
+ >>> env.get_settings(('app-servers',))
+ [{'debug': True,
+ 'directory': '/var/ampify',
+ 'host': 'dev1.ampify.it',
+ 'host_string': 'dev1.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/bash -l -c',
+ 'user': 'dev'},
+ {'debug': False,
+ 'directory': '/var/ampify',
+ 'host': 'dev2.ampify.it',
+ 'host_string': 'dev2.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/bash -l -c',
+ 'user': 'dev'},
+ {'debug': False,
+ 'directory': '/opt/ampify',
+ 'host': 'dev3.ampify.it',
+ 'host_string': 'dev3.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/tcsh -c',
+ 'user': 'dev'},
+ {'debug': False,
+ 'directory': '/var/ampify',
+ 'host': 'dev4.ampify.it',
+ 'host_string': 'dev4.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/bash -l -c',
+ 'user': 'dev'}]
+
+ First, the hosts are looked up in the ``hosts`` property of the specific
+ context and then a similar lookup is done for each of the hosts as with host
+ contexts with two minor differences:
+
+ 1. Any context-specific values, e.g. the properties for ``app-servers``, are
+ added as a layer after any ``default`` values.
+
+ 2. Any host-specific values defined within the context override everything
+ else.
+
+* Composite contexts -- made up of a non-host context followed by a slash and
+ comma-separated hosts, e.g. ``app-servers/dev1.ampify.it,dev3.ampify.it``.
+
+ .. syntax:: pycon
+
+ >>> env.get_settings(('app-servers/dev1.ampify.it,dev3.ampify.it',))
+ [{'debug': True,
+ 'directory': '/var/ampify',
+ 'host': 'dev1.ampify.it',
+ 'host_string': 'dev1.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/bash -l -c',
+ 'user': 'dev'},
+ {'debug': False,
+ 'directory': '/opt/ampify',
+ 'host': 'dev3.ampify.it',
+ 'host_string': 'dev3.ampify.it',
+ 'port': '22',
+ 'shell': '/bin/tcsh -c',
+ 'user': 'dev'}]
+
+ These are looked up similarly to non-host contexts, except that instead of
+ looking for ``hosts`` within the config, the specified hosts are used. This is
+ particularly useful for overriding contexts to a subset of servers from the
+ command-line.
+
+All in all, I've tried to provide a reasonably flexible default -- but you are
+welcome to override it to suit your particular needs, e.g. you might want to
+load the config dynamically over the network, etc.
+
+Finally, it's worth noting that all responses are cached by the default
+``env.get_settings()`` -- making it very cheap to switch contexts.
+
Hyphenated Commands
-------------------
This is a minor point, but I find hyphens, e.g. ``deploy-ampify``, to be more
aesthetically pleasing than underscores, i.e. ``deploy_ampify``. So Fabric now
displays and supports hyphenated variants of all commands, e.g. for the
following fabfile:
.. syntax:: python
from fabric.api import *
@task
def deploy_ampify():
"""deploy the current version of ampify"""
...
The command listing shows:
.. syntax:: console
$ fab
Available commands:
deploy-ampify deploy the current version of ampify
And you can run the command with:
.. syntax:: console
$ fab deploy-ampify
Command Line Env Flags
----------------------
You can now update the ``env`` object directly from the command line using the
new env flags syntax:
* ``+<key>`` sets the value of the key to ``True``.
* ``+<key>:<value>`` sets the key to the given string value.
So, for the following content in your fabfile:
.. syntax:: python
env.config_file = 'deploy.yaml'
env.debug = False
Running the following will set ``env.config_file`` to the new value:
.. syntax:: console
$ fab <commands> +config_file:alt.yaml
And the following will set ``env.debug`` to ``True``:
.. syntax:: console
$ fab <commands> +debug
The env flags are all set in the order given on the command line and before any
commands are run (including the config file handling if one is specified). And
you can, of course, specify as many env flags as you want.
Optimisations
-------------
It won't make much of a difference, but for my own sanity I've made a bunch of
minor optimisations to Fabric, e.g.
* Removed repeated look-up of attributes within loops.
* Removed repeated local imports within functions.
* Removed redundant double-wrapping of functions within the ``@hosts`` and
``@roles`` decorators.
Colors Support
--------------
You can enable the optional colors support by setting ``env.colors``, i.e.
.. syntax:: python
env.colors = True
Here's a screenshot of it in action:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqge6/fabric-shell"><img
src="http://img.skitch.com/20110211-nep3wmpi33qb2c4a13bf7fsgja.png"
alt="Fabric with Colors" /></a>
</div>
You can customise the colors by modifying the ``env.color_settings`` property.
By default it is set to:
.. syntax:: python
env.color_settings = {
'abort': yellow,
'error': yellow,
'finish': cyan,
'host_prefix': green,
'prefix': red,
'prompt': blue,
'task': red,
'warn': yellow
}
You can find the color functions in the ``fabric.colors`` module.
Logging Improvements
--------------------
The builtin ``puts()`` and ``fastprint()`` logging functions have also been
extended with the optional ``format`` parameter and ``env.format`` support
similar to the ``local()`` and ``run()`` builtins, so that instead of having to
do something like:
.. syntax:: python
@task
def db_migrate():
puts(
"[%s] [database] migrating schemas for %s" %
(env.host_string, env.db_name)
)
You can now just do:
.. syntax:: python
env.format = True
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database')
And it will output something like:
.. syntax:: console
$ fab db-migrate
[somehost.com] [database] migrating schemas for ampify
The second parameter which was previously a boolean-only value that was used to
control whether the host string was printed or not, can now also be a string
value -- in which case the string will be used as the prefix instead of the host
string.
You can still control if a host prefix is *also* printed by using the new
optional ``show_host`` parameter, e.g.
.. syntax:: python
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database', show_host=False)
Will output something like:
.. syntax:: console
$ fab db-migrate
[database] migrating schemas for ampify
And if you'd enabled ``env.colors``, the prefix will be also colored according
to your settings!
Autocompletion
--------------
`Bash completion <http://www.debian-administration.org/articles/316>`_ is one of
those features that really helps you to be more productive. Just include the
following in your ``~/.bashrc`` or equivalent file and you'll be able to use
Fabric's new command completion support:
.. syntax:: bash
_fab_completion() {
COMPREPLY=( $( \
COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \
COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
OPTPARSE_AUTO_COMPLETE=1 $1 ) )
}
complete -o default -F _fab_completion fab
It completes on all available commands and command line options, e.g.
.. syntax:: console
$ fab --dis<tab>
--disable-known-hosts --disable-hooks --display
Also, since Fabric has no way of knowing which `command line env flags`_ and
contexts you might be using, you can specify additional autocompletion items as
an ``env.autocomplete`` list value, e.g.
.. syntax:: python
env.autocomplete = ['+config_file:', '+debug', '@db-servers']
This will then make those values available for you to autocomplete, i.e.
.. syntax:: console
$ fab +<tab>
+config_file: +debug
Backwards Compatibility
-----------------------
All these changes should be fully backwards compatible. That is, unless you
happen to have specified any of the new ``env`` variables like ``env.stages``,
your existing fabfiles should run as they've always done. Do let me know if this
is not the case...
Usage
-----
If you'd like to take advantage of these various changes, the simplest thing to
do is to clone my `pylibs repository <https://github.com/tav/pylibs>`_ and put
it on your ``$PYTHONPATH``, i.e.
.. syntax:: console
$ git clone git://github.com/tav/pylibs.git
$ export PYTHONPATH=$PYTHONPATH:`pwd`/pylibs
Then create a ``fab`` script somewhere on your ``$PATH`` with the following
content:
.. syntax:: python
#! /usr/bin/env python
from fabric.main import main
main()
Make sure the script is executable, i.e.
.. syntax:: console
$ chmod +x fab
And as long as you have Python 2.6+, you should be good to go...
.. class:: intro-box
https://github.com/tav/pylibs/tree/master/fabric
Next Steps
----------
I have been talking to the Fabric maintainers about merging these changes
upstream. And so far they've been quite positive. But, as you can imagine, there
are a number of competing ideas about what is best for Fabric's future.
So if you like these features, then do leave a comment expressing your support.
It'd really help getting these features into the next version of Fabric.
-- Thanks, tav
\ No newline at end of file
|
tav/oldblog
|
6d6cac8d5e14d1971c843750a725bfdeecb7e1ed
|
Futher WIP on the Fabric article.
|
diff --git a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
index b50fcd5..8fa3c53 100644
--- a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
+++ b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
@@ -1,1137 +1,1224 @@
---
created: 2011-02-14, 08:54
layout: post
type: draft
license: Public Domain
---
======================================================
Fabric Python with Cleaner API and Parallel Deployment
======================================================
`Fabric <http://fabfile.org/>`_ is an awesome tool. Like `Capistrano
<https://github.com/capistrano/capistrano/wiki/2.x-Getting-Started>`_ and `Vlad
<http://rubyhitsquad.com/Vlad_the_Deployer.html>`_, it makes deployments a lot
simpler than with shell scripts on their own.
.. raw:: html
<div class="float-right-aligned">
<a href="http://www.flickr.com/photos/stars6/4381851322/in/photostream/"><img
src="http://farm3.static.flickr.com/2775/4381851322_d46fd7d75e.jpg"
alt="Datacenter Work" width="400px" height="267px" /></a><br />
<div class="image-caption">
by <a href="http://www.flickr.com/photos/stars6/">stars6</a>
</div>
</div>
However, once the complexity of your setup starts to grow, you very quickly
start wishing for a cleaner and more powerful API.
And once you are deploying to more than 30 servers, you really wish that Fabric
would run commands in parallel instead of doing them sequentially, one after
another.
Having recently experienced this pain, I decided to rework the core of Fabric.
I've documented it below -- describing all the changes to the `current Fabric
1.0a <http://docs.fabfile.org/1.0a/>`_ -- including funky new features like
``fab shell`` and staged deployments!
.. more
.. class:: intro-box
https://github.com/tav/pylibs/tree/master/fabric
Task Decorator
--------------
Traditionally, *all* functions within your ``fabfile.py`` were implicitly
exposed as Fabric commands. So once you started abstracting your script to be
more manageable, you had to use ``_underscore`` hacks to stop functions being
exposed as commands, e.g.
.. syntax:: python
from support.module import SomeClass as _SomeClass
from urllib import urlencode as _urlencode, urlopen as _urlopen
def _support_function():
...
Not only is this ugly and cumbersome, but it also goes against `The Zen of
Python <http://www.python.org/dev/peps/pep-0020/>`_ philosophy of "explicit is
better than implicit". So I've added a ``@task`` decorator to explicitly mark
functions as Fabric commands, e.g.
.. syntax:: python
from urllib import urlopen
from fabric.api import *
def get_latest_commit():
return urlopen('http://commits.server.com/latest').read()
@task
def check():
"""check if local changes have been committed"""
local_version = local('git rev-parse HEAD')
if local_version != get_latest_commit():
abort("!! Local changes haven't been committed !!")
@task
def deploy():
"""publish the latest version of the app"""
with cd('/var/app'):
run('git remote update')
run('git checkout %s' % get_latest_commit())
sudo("/etc/init.d/apache2 graceful")
The above uses ``@task`` to explicitly mark ``check`` and ``deploy`` as Fabric
commands so that they can be run as usual, i.e. ``fab check`` and ``fab
deploy``. Any functions and classes you import or define don't have to be
"hidden" with the ``_underscore`` hack.
For backwards compatibility, if you never use the ``@task`` decorator, you'll
continue to get the traditional behaviour.
YAML Config
-----------
It's preferable not to hard-code configurable values into fabfiles. This enables
you to reuse the same fabfile across different projects and keep it updated
without having to constantly copy, paste and modify.
So I've added native config support to Fabric. You can enable it by simply
specifying the ``env.config_file`` variable:
.. syntax:: python
env.config_file = 'deploy.yaml'
This will load and parse the specified `YAML file
<http://en.wikipedia.org/wiki/YAML>`_ before running any commands. The
configuration values will then be accessible from ``env.config``. This object is
simply a dictionary with dot-attribute access similar to the ``env`` dictionary.
You can then keep your fabfiles clean from hard-coded values, e.g.
.. syntax:: python
def get_latest_commit():
return urlopen(env.config.commits_server).read()
@task
def deploy():
with cd(env.config.app_directory):
...
+Having configurable values also means that frameworks like Django could ship
+default tasks for you to use, e.g.
+
+.. syntax:: python
+
+ from django.fabric import deploy, test
+
Script Execution
----------------
It really helps to be able to quickly iterate the scripts that you will be
calling with Fabric. And whilst you should eventually create them as individual
files and sync them as part of your deployment, it'd be nice if you could try
them out during development.
To help with this I've added a new ``execute()`` builtin. This lets you execute
arbitrary scripts on remote hosts, e.g.
.. syntax:: python
@task
def stats():
memusage = execute("""
#! /usr/bin/env python
import psutil
pid = open('pidfile').read()
process = psutil.Process(int(pid))
print process.get_memory_percent()
""", 'memusage.py', verbose=False, dir='/var/ampify')
Behind the scenes, ``execute()`` will:
* Strip any common leading whitespace from every line in the source.
* Copy the source into a file on the remote server.
* If the optional ``name`` parameter (the 2nd parameter) had been specified,
then the given name will be used, otherwise an auto-generated name will be
used.
* If the optional ``dir`` parameter was specified, then the file will be created
within the given directory, otherwise it'll be created on the remote ``$HOME``
directory.
* The file will then be made executable, i.e. ``chmod +x``.
* And, finally, it will be run and the response will be returned. Unless the
``verbose`` parameter is set to ``False``, then it will by default also output
the response to the screen.
As you can imagine, ``execute()`` makes it very easy to rapidly try out and
develop your development logic. Your scripts can be in whatever languages you
can run on your remote hosts -- Ruby, Perl, Bash, Python, JavaScript, whatever.
Environment Variable Manager
----------------------------
When calling various command line tools, you often have to mess with environment
variables like ``$PATH``, ``$NODE_PATH``, ``$PYTHONPATH``, etc. To deal with
this, Fabric forced you to write things like:
.. syntax:: python
NODE_PATH = "NODE_PATH=$NODE_PATH:%s" % node_libs
run("%s vows" % NODE_PATH)
run("%s coffee -c amp.coffee" % NODE_PATH)
Instead you can now do:
.. syntax:: python
with env.NODE_PATH(node_libs):
run("vows")
run("coffee -c amp.coffee")
That is, if you call a property on the ``env`` object which is composed of only
the ``ABCDEFGHIJKLMNOPQRSTUVWXYZ_`` characters, then a `Python Context Manager
<http://www.python.org/dev/peps/pep-0343/>`_ is generated which will manage the
use of the environment variables for you.
The manager has the following constructor signature:
.. syntax:: python
manager(value, behaviour='append', sep=os.pathsep, reset=False)
So, if you'd called ``env.PATH(value, behaviour)``, the way the ``value`` is
treated will depend on the ``behaviour`` parameter which can be one of the
following:
* ``append`` -- appends value to the current ``$PATH``, i.e.
``PATH=$PATH:<value>``
* ``prepend`` -- prepends value to the current ``$PATH``, i.e.
``PATH=<value>:$PATH``
* ``replace`` -- ignores ``$PATH`` altogether, i.e. ``PATH=<value>``
The ``sep`` defaults to ``:`` on most platforms and determines how the values
are concatenated. However, if you call the manager with no arguments at all or
stringify it, it will return the string which would be used during execution,
e.g.
.. syntax:: python
print env.NODE_PATH # NODE_PATH=$NODE_PATH:/opt/ampify/libs/node
The various calls can be also nested, e.g.
.. syntax:: python
with env.PATH('/usr/local/bin'):
with env.PATH('/home/tav/bin'):
print env.PATH # PATH=$PATH:/usr/local/bin:/home/tav/bin
with env.PATH('/opt/local/bin', 'replace'):
with env.PATH('/bin', 'prepend'):
print env.PATH # PATH=/bin:/opt/local/bin
print env.PATH # PATH=$PATH:/usr/local/bin
You can specify ``reset=True`` to discard any nested values, e.g.
.. syntax:: python
with env.PATH('/opt/ampify/bin', 'prepend'):
with env.PATH('/home/tav/bin', reset=True):
print env.PATH # PATH=$PATH:/home/tav/bin
Extension Hooks
---------------
I've added native hooks support so that you can extend certain aspects of Fabric
without having to resort to monkey-patching. You attach functions to specific
hooks by using the new ``@hook`` decorator, e.g.
.. syntax:: python
@hook('config.loaded')
def default_config():
if 'port' in env.config:
return
port = prompt("port number?", default=8080, validate=int)
env.config.port = port
For the moment, only the following builtin hooks are defined. It's possible that
I may add support for individual ``<command>.before`` and ``<command>.after``
hooks, but so far I haven't needed that functionality.
+---------------------+-----------------------------+------------------------+
| Hook Name | Hook Function Signature | Description |
+=====================+=============================+========================+
| ``commands.before`` | ``func(cmds, cmds_to_run)`` | |hook-commands-before| |
+---------------------+-----------------------------+------------------------+
| ``config.loaded`` | ``func()`` | |hook-config-loaded| |
+---------------------+-----------------------------+------------------------+
| ``commands.after`` | ``func()`` | |hook-commands-after| |
+---------------------+-----------------------------+------------------------+
| ``listing.display`` | ``func()`` | |hook-listing-display| |
+---------------------+-----------------------------+------------------------+
.. |hook-config-loaded| replace::
Run after any config file has been parsed and loaded.
.. |hook-commands-after| replace::
Run after *all* the commands are run.
.. |hook-commands-before| replace::
Run before *all* the commands are run (including the config handling).
.. |hook-listing-display| replace::
Run when the commands listing has finished running in response to ``fab`` or
``fab --list``. Useful for adding extra info.
You can access the functions attached to a specific hook by calling
``hook.get()``, e.g.
.. syntax:: python
functions = hook.get('config.loaded')
You can also define your own custom hooks and call the attached functions by
using ``hook.call()``. This takes the hook name as the first parameter and all
subsequent parameters are used when calling the hook's attached functions.
Here's an example that shows ``hook.call()`` in action along with ``env.hook``
and the ability to attach the same function to multiple hooks by passing
multiple names to the ``@hook`` decorator:
.. syntax:: python
@hook('deploy.success', 'deploy.failure')
def irc_notify(release_id, info=None):
client = IrcClient('devbot', 'irc.freenode.net', '#esp')
if env.hook == 'deploy.success':
client.msg("Successfully deployed: %s" % release_id)
else:
client.msg("Failed deployment: %s" % release_id)
@hook('deploy.success')
def webhook_notify(release_id, info):
webhook.post({'id': release_id, 'payload': info})
@task
def deploy():
release_id = get_release_id()
try:
...
info = get_release_info()
except Exception:
hook.call('deploy.failure', release_id)
else:
hook.call('deploy.success', release_id, info)
And, finally, you can disable specific hooks via the ``--disable-hooks`` command
line option which takes space-separated patterns, e.g.
.. syntax:: console
$ fab deploy --disable-hooks 'config.loaded deploy.*'
You can override these disabled hooks in turn with the ``--enable-hooks``
option, e.g.
.. syntax:: console
$ fab deploy --disable-hooks 'deploy.*' --enable-hooks 'deploy.success'
Both ``hook.call()`` and ``hook.get()`` respect these command-line parameters,
so if you ever need to access the raw hook registry dict, you can access it
directly via ``hook.registry``.
Interpolation & Directories Support
-----------------------------------
Fabric provides a number of builtin functions that let you make command line
calls:
* ``local()`` -- runs a command on the local host.
* ``run()`` -- runs a command on a remote host.
* ``sudo()`` -- runs a sudoed command on a remote host.
I've added two optional parameters to these. A ``dir`` parameter can be used to
specify the directory from within which the command should be run, e.g.
.. syntax:: python
@task
def restart():
run("amp restart", dir='/opt/ampify')
And a ``format`` parameter can be used to access the new formatted strings
functionality, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}", format=True)
This makes use of the `Advanced String Formatting
<http://www.python.org/dev/peps/pep-3101/>`_ support that is available in Python
2.6 and later. The ``env`` object is used to look-up the various parameters,
i.e. the above is equivalent to:
.. syntax:: python
@task
def backup():
command = "backup.rb {app_directory} {s3_key}".format(**env)
run(command)
By default, ``format`` is set to ``False`` and the string is run without any
substitution. But if you happen to find formatting as useful a I do, you can
enable it as default by setting:
.. syntax:: python
env.format = True
You can then use it without having to constantly set ``format=True``, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}")
Fabric Contexts
---------------
-Deployment setups vary tremendously. I've used Fabric for everything from simple
-single-machine deployments to web app deployments across multiple data centers
-to even physical multi-touch installations at the `Museum of Australian
-Democracy
+I've used Fabric for everything from simple single-machine deployments to web
+app deployments across multiple data centers to even physical multi-touch
+installations at the `Museum of Australian Democracy
<http://www.moadoph.gov.au/exhibitions/prime-ministers-of-australia-exhibition/>`_.
-But for anything but the simplest of setups, the support offered by Fabric in
-terms of ``@hosts`` and ``@roles`` is far from satisfactory.
+And for everything but the simplest of setups, I've had to work around the
+limited support offered by Fabric's ``@hosts`` and ``@roles`` in terms of:
-And providing an API that covers the various scenarios is hard!
+* Managing configurable ``env`` values when dealing with different servers.
-When doing a major upgrade of a web app, you might want to do something like:
+* Executing workflows involving distinct sets of servers within the same Fabric
+ command, e.g. app servers, db servers, load balancers, etc.
-* Switch the web servers to show a "planned maintenance" notice.
+And, clearly, I am `not
+<http://lists.gnu.org/archive/html/fab-user/2009-05/msg00027.html>`_ `the
+<http://lists.nongnu.org/archive/html/fab-user/2010-09/msg00023.html>`_ `only
+<http://lists.nongnu.org/archive/html/fab-user/2010-12/msg00020.html>`_ `one
+<http://lists.nongnu.org/archive/html/fab-user/2011-02/msg00005.html>`_ who has
+experienced this pain. So I've introduced the notion of "contexts" and an
+``env()`` context runner into the Fabric core. This means that you can now do
+things like:
-* Migrate the database to new schemas.
+.. syntax:: python
-* Upgrade the app servers.
+ @task('app-servers')
+ def deploy():
-* Update app routing on the configuration servers.
+ env().run('./manage.py shutdown {app_directory}')
+ env('build-servers').run('make build')
+ env().run('./manage.py upgrade {app_directory}'
+ env().run('./manage.py start {app_directory}'
-* Enable the web servers to continue serving requests normally.
+And run it with a simple:
-Context Runner
---------------
+.. syntax:: console
-Parallel Deployment
--------------------
+ $ fab deploy
-You no longer have to patiently wait whilst Fabric runs your commands on each
-server one by one. By taking advantage of the ``.multirun()`` context runner
-call, you can now run commands in parallel, e.g.
+That's right. You no longer have to run insanely long command strings like:
+
+.. syntax:: console
+
+ $ fab run_tests freeze_requirements update_repository create_snapshot update_virtualenv update_media update_nginx graceful_migrate
+
+You might occasionally want to make a call on a subset of hosts for particular
+contexts. A utility ``.select()`` method is provided to help with this. If you
+pass it an integer value, it'll randomly choose as many values from the
+settings, e.g.
.. syntax:: python
- @task
- def deploy():
- responses = env('app-servers').multirun('make build')
- if failed(responses):
- ...
+ @task('build-servers')
+ def build():
+ env().select(3).run('{build_command}')
-The above will run ``make build`` on the ``app-servers`` in parallel -- reducing
-your deployment time significantly! The returned ``responses`` will be a list of
-the individual responses from each host in order.
+The ``.select()`` method can also take a filter function to let you do more
+custom selection, e.g. to select 2 build servers for each platform, you might do
+something like:
+
+.. syntax:: python
+
+ from itertools import groupby
+ from random import sample
+
+
+ def selector(settings):
+ settings = sorted(settings, key=lambda s: s['platform'])
+ grouped = groupby(settings, lambda s: s['platform'])
+ return [sample(list(group), 2) for platform, group in grouped]
+
+
+ @task('build-servers')
+ def build():
+ env().select(selector).run('{build_command}')
+
+And since deployment setups vary tremendously, instead of trying to make one
+size fit all, I've made it so that you can define your own
+``env.get_settings()`` function, e.g.
+
+.. syntax:: python
+
+ from fabric.network import host_regex
+
+
+ def get_settings(ctx):
+ return [{
+ 'host_string': host_string,
+ 'host': host_regex.match(host_string).groupdict()['host']
+ } for host_string in ctx]
+
+
+ env.get_settings = get_settings
If any of the hosts threw an exception, then the corresponding element within
``responses`` will contain it. Two new builtins are provided to quickly
determine the nature of the response:
* ``succeeded`` -- returns True if all the response items were successful.
* ``failed`` -- returns True if any of the response items failed or threw an
exception.
You can loop through the response and the corresponding host/setting values by
using the ``.ziphost()`` and ``.zipsetting()`` generator methods on the returned
list-like ``responses`` object, e.g.
.. syntax:: python
@task
def deploy():
responses = env('app-servers').multirun('make build')
for response, host in responses.ziphost():
...
+You can override the context for a task directly from the command line with the
+new ``@context`` syntax, e.g.
+
+.. syntax:: console
+
+ $ fab example1 @dev1.ampify.it
+ ['dev1.ampify.it']
+
+
+Parallel Deployment
+-------------------
+
+You no longer have to patiently wait whilst Fabric runs your commands on each
+server one by one. By taking advantage of the ``.multirun()`` context runner
+call, you can now run commands in parallel, e.g.
+
+.. syntax:: python
+
+ @task
+ def deploy():
+ responses = env('app-servers').multirun('make build')
+ if failed(responses):
+ ...
+
+The above will run ``make build`` on the ``app-servers`` in parallel -- reducing
+your deployment time significantly! The returned ``responses`` will be a list of
+the individual responses from each host in order, just like with ``.run()``.
+
+If any of the hosts threw an exception, then the corresponding element within
+``responses`` will contain it. Exceptions will not be raised, irregardless of
+whether you'd set ``warn_only`` -- it is up to you to deal with them.
+
By default you see the output from all hosts, but sometimes you just want a
summary, so you can specify ``condensed=True`` to ``.multirun()`` and it'll
provide a much quieter, running report instead, e.g.
::
[multirun] Running 'make build test' on 31 hosts
[multirun] Finished on dev2.ampify.it
[multirun] Finished on dev7.ampify.it
[multirun] 2/31 completed ...
Also, when dealing with large number of servers, you'll run into laggy servers
from time to time. And depending on your setup, it may not be critical that
*all* servers run the command. To help with this ``.multirun()`` takes two
optional parameters:
* ``laggards_timeout`` -- the number of seconds to wait for laggards once the
satisfactory number of responses have been received -- needs to be an int
value.
* ``wait_for`` -- the number of responses to wait for -- this should be an int,
but can also be a float value between ``0.0`` and ``1.0``, in which case it'll
be used as the factor of the total number of servers.
So, for the following:
.. syntax:: python
responses = env('app-servers').multirun(
'make build', laggards_timeout=20, wait_for=0.8
)
The ``make build`` command will be run on the various ``app-servers`` and once
80% of the responses have been received, it'll continue to wait up to 20 seconds
for any laggy servers before returning the responses.
The ``responses`` list will contain the new ``TIMEOUT`` builtin object for the
-servers that didn't return a response in time Like with the ``.run()`` context
+servers that didn't return a response in time. Like with the ``.run()`` context
runner call, ``.multirun()`` also accepts a function to execute instead of a
command string, e.g.
.. syntax:: python
env.format = True
def migrate_db():
run('./manage.py schemamigration --auto {app_name}')
run('./manage.py migrate {app_name}')
@task
def deploy():
env('frontends').multirun('routing --disable')
env('app-nodes').multirun(migrate_db)
env('frontends').multirun('routing --enable')
@task
def migrate():
env('app-nodes').multirun(migrate_db)
There's also a ``.multilocal()`` which runs the command locally for each of the
hosts in parallel, e.g.
.. syntax:: python
env.format = True
@task
def db_backup():
env('db-servers').multilocal('backup.rb {host}')
Behind the scenes, ``.multirun()`` uses ``fork()`` and `domain sockets
<http://en.wikipedia.org/wiki/Unix_domain_socket>`_, so it'll only work on Unix
platforms. You can specify the maximum number of parallel processes to spawn at
any one time by specifying ``env.multirun_pool_size`` which is set to ``10`` by
default, e.g.
.. syntax:: python
env.multirun_pool_size = 200
There's also an ``env.multirun_child_timeout`` which specifies the number of
seconds a child process will wait to hear from the parent before committing
suicide. It defaults to ``10`` seconds, but you can configure it to suit your
setup:
.. syntax:: python
env.multirun_child_timeout = 24
And, oh, there's also a ``.multisudo()`` for your convenience.
Fabric Shell
------------
Sometimes you just want to run a bunch of commands on a number of different
servers. So I've added a funky new feature -- Fabric shell mode:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqccu/python" title="Fabric Shell"><img
src="http://img.skitch.com/20110212-g8ha9cd5g441m4q3y21gewmnha.png" /></a>
</div>
Once you are in the shell, all of your commands will be sequentially ``run()``
on the respective hosts for your calling context. You can also use the
``.shell-command`` syntax to call shell builtin commands -- including your own
custom ones!
You start shells from within your Fabric commands by invoking the ``.shell()``
method of a context runner. Here's sample code to enable ``fab shell``:
.. syntax:: python
- @task('app-servers', run_per_context=False)
+ @task('app-servers')
def shell():
"""start a shell within the current context"""
env().shell(format=True)
The above defaults to the ``app-servers`` context when you run ``fab shell``,
but you can always override the context from the command line, e.g.
.. syntax:: console
$ fab shell @db-servers
And if your Python has been compiled with `readline support
<http://docs.python.org/library/readline.html>`_, then you can also leverage the
tab-completion support that I've added:
* Terms starting with ``{`` auto-complete on the properties within the ``env``
object to make it easy for you to use the string formatting support.
* Terms starting with ``.`` auto-complete on the available shell builtin
commands.
* All other terms auto-complete on the list of available executables on your
local machine's ``$PATH``.
Other readline features have been enabled too, e.g. command history with up/down
arrows, ``^r`` search and even cross-session history. You can configure where
the history is saved by setting ``env.shell_history_file`` which defaults to:
.. syntax:: python
env.shell_history_file = '~/.fab-shell-history'
Shell Builtins
--------------
As mentioned above, you can call various ``.shell-commands`` from within a
Fabric shell to do something other than ``run()`` a command on the various
hosts, e.g.
.. syntax:: irb
>> .multilocal backup.rb {host_string}
The above will run the equivalent of the following in parallel for each host:
.. syntax:: python
local("backup.rb {host_string}")
The following builtins are currently available:
* ``.cd`` -- changes the working directory for all future commands.
* ``.help`` -- displays a list of the available shell commands.
* ``.info`` -- list the current context and the respective hosts.
* ``.local`` -- runs the command locally.
* ``.multilocal`` -- runs the command in parallel locally for each host.
* ``.multirun`` -- runs the command in parallel on the various hosts.
* ``.multisudo`` -- runs the sudoed command in parallel on the various hosts.
* ``.sudo`` -- runs the sudoed command on the various hosts.
* ``.toggle-format`` -- toggles string formatting support.
You can define your own by using the new ``@shell`` decorator, e.g.
.. syntax:: python
@shell
def python_version(spec, arg):
with hide('running', 'output'):
if arg == 'full':
version = run('python -c "import sys; print sys.version"')
else:
version = run(
"python -c 'import sys; print "
'".".join(map(str, sys.version_info[:3]))\''
)
puts("python %s" % version)
The above can then be called from within a shell, e.g.
.. syntax:: irb
>> .python-version
[dev1.ampify.it] python 2.5.2
[dev3.ampify.it] python 2.7.0
The ``spec`` object is initialised with the various variables that the
``.shell()`` method was originally called with, e.g. ``dir``, ``format``, etc.
All changes made, e.g. ``spec.dir = '/var/ampify'``, are persistent and will
affect all subsequent commands within the shell.
The ``arg`` is a string value of everything following the shell command name,
e.g. for ``.local echo hi``, it will be ``"echo hi"``. The command name is
derived from the function name, but you can provide your own as the first
parameter to the ``@shell`` decorator.
And, finally, you can specify ``single=True`` to the ``@shell`` decorator to
specify that you only want the command to be run a single time and not
repeatedly for every host, e.g.
.. syntax:: python
@shell('hello', single=True)
def demo(spec, arg):
print "Hello", arg.upper()
The above can then be called from within a shell, e.g.
.. syntax:: irb
>> .hello tav
Hello TAV
The ``env.ctx`` is set for even single-mode shell commands, so you can always
take advantage of context runners, e.g.
.. syntax:: python
@shell
def backup(spec, arg):
env().multirun(...)
Command Line Listing
--------------------
When ``fab`` was run without any arguments, it used to spit out the help message
with the various command line options:
.. syntax:: console
$ fab
Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
Options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
-l, --list print list of possible commands and exit
--shortlist print non-verbose list of possible commands and exit
-d COMMAND, --display=COMMAND
print detailed info about a given command and exit
...
As useful as this was, I figured it'd be more useful to list the various
commands without having to constantly type ``fab --list``. So now when you run
``fab`` without any arguments, it lists the available commands instead, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
You can of course still access the help message by running either ``fab -h`` or
``fab --help``. And you can hide commands from being listed by specifying
``display=None`` with the ``@task`` decorator, e.g.
.. syntax:: python
@task(display=None)
def armageddon():
...
Staged Deployment
-----------------
For most serious deployments, you tend to have distinct environments, e.g.
testing, staging, production, etc. And `existing
<http://blog.jeremi.info/entry/my-git-workflow-to-deploy-an-application-to-appengine>`_
`fabric <http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/>`__
`setups <https://github.com/bueda/ops>`_ tend to have similarly named commands
so you can run things like:
.. syntax:: console
$ fab production deploy
Now, not being a fan of repeatedly adding the same functionality to all my
fabfiles, I've added staged deployment support to Fabric. You can enable it by
specifying an ``env.stages`` list value, e.g.
.. syntax:: python
env.stages = ['staging', 'production']
The first item in the list is taken to be the *default* and overridable commands
of the following structure are automatically generated for each item:
.. syntax:: python
@task(display=None)
def production():
puts("env.stage = production", prefix='system')
env.stage = 'production'
That is, it will update ``env.stage`` with the appropriate value and print out a
message saying so, e.g.
.. syntax:: console
$ fab production check deploy
[system] env.stage = production
...
And if your fab command line call didn't start with one of the stages, it will
automatically run the one for the default stage, e.g.
.. syntax:: console
$ fab check deploy
[system] env.stage = staging
...
For added convenience, the environments are also listed when you run ``fab``
without any arguments, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
Available environments:
staging
production
And, for further flexibility, you can override ``env.stages`` with the
``FAB_STAGES`` environment variable. This takes a comma-separated list of
environment stages and, again, the first is treated as the default, e.g.
.. syntax:: console
$ FAB_STAGES=development,production fab deploy
[system] env.stage = development
...
Hyphenated Commands
-------------------
This is a minor point, but I find hyphens, e.g. ``deploy-ampify``, to be more
aesthetically pleasing than underscores, i.e. ``deploy_ampify``. So Fabric now
displays and supports hyphenated variants of all commands, e.g. for the
following fabfile:
.. syntax:: python
from fabric.api import *
@task
def deploy_ampify():
"""deploy the current version of ampify"""
...
The command listing shows:
.. syntax:: console
$ fab
Available commands:
deploy-ampify deploy the current version of ampify
And you can run the command with:
.. syntax:: console
$ fab deploy-ampify
Command Line Env Flags
----------------------
You can now update the ``env`` object directly from the command line using the
new env flags syntax:
* ``+<key>`` sets the value of the key to ``True``.
* ``+<key>:<value>`` sets the key to the given string value.
So, for the following content in your fabfile:
.. syntax:: python
env.config_file = 'deploy.yaml'
env.debug = False
Running the following will set ``env.config_file`` to the new value:
.. syntax:: console
$ fab <commands> +config_file:alt.yaml
And the following will set ``env.debug`` to ``True``:
.. syntax:: console
$ fab <commands> +debug
The env flags are all set in the order given on the command line and before any
commands are run (including the config file handling if one is specified). And
you can, of course, specify as many env flags as you want.
Optimisations
-------------
It won't make much of a difference, but for my own sanity I've made a bunch of
minor optimisations to Fabric, e.g.
* Removed repeated look-up of attributes within loops.
* Removed repeated local imports within functions.
* Removed redundant double-wrapping of functions within the ``@hosts`` and
``@roles`` decorators.
Colors Support
--------------
You can enable the optional colors support by setting ``env.colors``, i.e.
.. syntax:: python
env.colors = True
Here's a screenshot of it in action:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqge6/fabric-shell"><img
src="http://img.skitch.com/20110211-nep3wmpi33qb2c4a13bf7fsgja.png"
alt="Fabric with Colors" /></a>
</div>
You can customise the colors by modifying the ``env.color_settings`` property.
By default it is set to:
.. syntax:: python
env.color_settings = {
'abort': yellow,
'error': yellow,
'finish': cyan,
'host_prefix': green,
'prefix': red,
'prompt': blue,
'task': red,
'warn': yellow
}
You can find the color functions in the ``fabric.colors`` module.
Logging Improvements
--------------------
The builtin ``puts()`` and ``fastprint()`` logging functions have also been
extended with the optional ``format`` parameter and ``env.format`` support
similar to the ``local()`` and ``run()`` builtins, so that instead of having to
do something like:
.. syntax:: python
@task
def db_migrate():
puts(
"[%s] [database] migrating schemas for %s" %
(env.host_string, env.db_name)
)
You can now just do:
.. syntax:: python
env.format = True
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database')
And it will output something like:
.. syntax:: console
$ fab db-migrate
[somehost.com] [database] migrating schemas for ampify
The second parameter which was previously a boolean-only value that was used to
control whether the host string was printed or not, can now also be a string
value -- in which case the string will be used as the prefix instead of the host
string.
You can still control if a host prefix is *also* printed by using the new
optional ``show_host`` parameter, e.g.
.. syntax:: python
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database', show_host=False)
Will output something like:
.. syntax:: console
$ fab db-migrate
[database] migrating schemas for ampify
And if you'd enabled ``env.colors``, the prefix will be also colored according
to your settings!
Autocompletion
--------------
`Bash completion <http://www.debian-administration.org/articles/316>`_ is one of
those features that really helps you to be more productive. Just include the
following in your ``~/.bashrc`` or equivalent file and you'll be able to use
Fabric's new command completion support:
.. syntax:: bash
_fab_completion() {
COMPREPLY=( $( \
COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \
COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
OPTPARSE_AUTO_COMPLETE=1 $1 ) )
}
complete -o default -F _fab_completion fab
It completes on all available commands and command line options, e.g.
.. syntax:: console
$ fab --dis<tab>
--disable-known-hosts --disable-hooks --display
Also, since Fabric has no way of knowing which `command line env flags`_ and
contexts you might be using, you can specify additional autocompletion items as
an ``env.autocomplete`` list value, e.g.
.. syntax:: python
env.autocomplete = ['+config_file:', '+debug', '@db-servers']
This will then make those values available for you to autocomplete, i.e.
.. syntax:: console
$ fab +<tab>
+config_file: +debug
Backwards Compatibility
-----------------------
All these changes should be fully backwards compatible. That is, unless you
happen to have specified any of the new ``env`` variables like ``env.stages``,
your existing fabfiles should run as they've always done. Do let me know if this
is not the case...
Usage
-----
If you'd like to take advantage of these various changes, the simplest thing to
do is to clone my `pylibs repository <https://github.com/tav/pylibs>`_ and put
it on your ``$PYTHONPATH``, i.e.
.. syntax:: console
$ git clone git://github.com/tav/pylibs.git
$ export PYTHONPATH=$PYTHONPATH:`pwd`/pylibs
Then create a ``fab`` script somewhere on your ``$PATH`` with the following
content:
.. syntax:: python
#! /usr/bin/env python
from fabric.main import main
main()
Make sure the script is executable, i.e.
.. syntax:: console
$ chmod +x fab
And as long as you have Python 2.6+, you should be good to go...
|
tav/oldblog
|
648b694b55bfb558ee1898206d3494f1605fffff
|
Fixed Wikimedia image move and Google Analytics.
|
diff --git a/_layouts/site.genshi b/_layouts/site.genshi
index f8bb594..a3aed8d 100644
--- a/_layouts/site.genshi
+++ b/_layouts/site.genshi
@@ -1,180 +1,180 @@
---
license: Public Domain
---
<!DOCTYPE html>
<html xmlns:py="http://genshi.edgewall.org/">
<head>
<title>${Markup(site_title)}<py:if test="defined('title')"> » ${Markup(title)}</py:if></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
<meta name="tweetmeme-title" content="${Markup(title)}" />
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<meta name="author" content="tav" />
<meta name="description" content="${site_description}" />
<meta name="copyright" content="This work has been placed into the Public Domain." />
<meta name="document-rating" content="general" />
<link rel="icon" type="image/png" href="gfx/aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds.feedburner.com/asktav" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="css/site.css" />
<style type="text/css" media="print">
#ignore-this { display: none; }
</style>
<style type="text/css">
.ascii-art .literal-block {
line-height: 1em !important;
}
.cmd-line {
background-color: #000;
color: #fff;
padding: 5px;
margin-left: 2em;
margin-right: 2em;
}
.cmd-ps1 {
color: #999;
}
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
#site-title { padding-top: 0px; }
</style>
<![endif]-->
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://use.typekit.com/por2lgv.js"></script>
<script>
GOOGLE_ANALYTICS_CODE = "UA-90176-8";
GOOGLE_ANALYTICS_HOST = "tav.epians.com";
DISQUS_FORUM = 'asktav';
PAGE_URI = '${'http://tav.espians.com/' + __name__}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
try{
Typekit.load();
} catch(e) {};
</script>
- <script src="js/init.js"></script>
+ <script src="js/init.js?decafbad"></script>
</head>
<body>
<div id="main">
<div id="site-header">
<a href="/" id="site-title" title="${site_title}">
Tav's Blog →
</a>
<div id="site-links">
<form id="translation_form"><select id="lang_select" onchange="translate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form>
<a href="/" title="${site_description}">Home</a>
<a href="archive.html" title="Site Index">Archive</a>
<a href="about-tav.html" title="About Tav">About Tav</a>
</div>
<hr class="clear" />
</div>
<div class="article-nav"></div>
<div id="intro">
<div class="center">
<img src="gfx/profile-smoking.jpg" />
</div>
<h1>
I'm Tav, a 28yr old from London. I enjoy working on large-scale
social, economic and technological systems.
</h1>
<strong>Follow</strong>
<div class="follow-link">
<a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="gfx/icon.twitter.png" /></a> <a href="http://twitter.com/tav" title="Follow @tav on Twitter">tav</a>
</div>
<div class="follow-link">
<a href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog"><img
src="gfx/icon.rss.png" /></a> <a
href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog">tav's blog</a>
</div>
<div class="follow-link">
<a href="https://github.com/tav" title="Follow @tav on GitHub"><img src="gfx/icon.github.png" class="absmiddle" /></a> <a href="https://github.com/tav" title="Follow @tav on GitHub">tav</a>
</div>
<br/>
<strong>Contact</strong>
<div class="follow-link">
<a href="mailto:tav@espians.com" title="Email tav@espians.com"><img src="gfx/icon.gmail.png" /></a> <a href="mailto:tav@espians.com" title="Email tav@espians.com">tav@espians.com</a>
</div>
<div class="follow-link">
<a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook"><img src="gfx/icon.facebook.png" /></a> <a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook">asktav</a>
</div>
<div class="follow-link">
<a href="skype:addname?name=tavespian" title="Contact tavespian on Skype"><img src="gfx/icon.skype.png" /></a> <a href="skype:addname?name=tavespian" title="Contact tavespian on Skype">tavespian</a>
</div>
</div>
<div id="page">
<div>${Markup(content)}</div>
</div>
<hr class="clear" />
<div class="article-nav"></div>
</div>
</body>
</html>
diff --git a/evolution-of-ideas.txt b/evolution-of-ideas.txt
index 75e5623..8760cb3 100644
--- a/evolution-of-ideas.txt
+++ b/evolution-of-ideas.txt
@@ -1,111 +1,109 @@
---
created: 2008-07-08, 06:23
layout: post
license: Public Domain
---
==================
Evolution of Ideas
==================
-.. image:: http://upload.wikimedia.org/wikipedia/commons/9/9c/Darwin_ape.jpg
+.. image:: http://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Editorial_cartoon_depicting_Charles_Darwin_as_an_ape_%281871%29.jpg/256px-Editorial_cartoon_depicting_Charles_Darwin_as_an_ape_%281871%29.jpg
:alt: Caricature of Charles Darwin
:class: float-right-aligned
- :width: 200
- :height: 253
Ideas require the right kind of incubation. They need to be nurtured before
being taken into the world -- at the right moment in time.
The nurturing and timing of ideas is one aspect which most innovators and
entrepreneurs seem to miss. And I certainly can't talk about timing -- as the
`tyranny of timing
<http://findarticles.com/p/articles/mi_hb1437/is_200201/ai_n5944664>`_ is
something that I've had to learn the hard way.
But I've been extremely lucky with respect to the nurturing of ideas. For
reasons still unknown, extra-ordinary individuals seem to be attracted to me.
And their influences have been pure gold.
This is a reflection of something that I've heard referred to as the "Florence
Effect". That is, whilst statistically speaking we should have millions of
Einsteins and Da Vincis walking amongst us, the reason many of them haven't
tapped into their full potential is due to a lack of a nurturing, vibrant
community.
.. more
In contrast, if you take Florence or Rome during the `High Renaissance
<http://en.wikipedia.org/wiki/High_Renaissance>`_, you will see that the likes
of `Leonardo da Vinci <http://en.wikipedia.org/wiki/Leonardo_da_Vinci>`_,
`Michelangelo <http://en.wikipedia.org/wiki/Michelangelo>`_, `Raphael
<http://en.wikipedia.org/wiki/Raphael>`_, `Botticelli
<http://en.wikipedia.org/wiki/Botticelli>`_, `Ghirlandaio
<http://en.wikipedia.org/wiki/Ghirlandaio>`_ and `Perugino
<http://en.wikipedia.org/wiki/Perugino>`_ all hung around the same areas.
Not only would they have influenced, inspired and critiqued each other, but many
of them actively taught some of the others. Their social networks would have
overlapped considerably enough that ideas would have flowed much faster than at
other points in history.
The various localities of Florence and Rome -- with their various patrons --
acted as a positive `echo chamber
<http://en.wikipedia.org/wiki/Media_echo_chamber>`_ within which ideas and
inspirations would have flowed and been nurtured. We need such spaces for the
`cultural creatives <http://www.culturalcreatives.org/>`_ of our times.
For me, the `#esp IRC channel <irc://irc.freenode.net/esp>`_ has been one such
space. And you can see its influence even in the evolution of just two of the
ideas:
* Organisational Model & Pecus
* Gift Economy
For the first employment contract, I wrote (in 1999):
*The full employees collectively form the âEcclésiaâ, and this group owns
fifty percent of the Company shares. The Ecclésia elects (by the Australian
ballot) on a quarterly basis an executive council of 7 chief officers. This
council will decide on company policies on a day-to-day basis, and will put to
vote before the Ecclésia â matters of serious import. However, any member of
the Ecclésia may voice their opinion on all matters.*
*Company work will take place over the Company Extranet. The Ecclésia will
decide on new projects and assign values of their worth, as well as elect the
Project Leader. It is then up to the Project Leader, to define the Jobs needed
to be done for the success of the Project, and their respective values in plex
economic currency units (pecus).*
This later evolved to include trust-based algorithms and certifications -- as
can be seen from this `chat log about the Espian model
<http://web.archive.org/web/20020314184348/http://tav.espians.com/espian_model_chat>`_
in 2001. And on an unrelated front, I was also `rambling on the Espra dev list
<http://web.archive.org/web/20010414190833/lists.espra.net/pipermail/espra-dev/2001-February/000089.html>`_
about gift economies -- also in 2001.
But at that time, these were two separate ideas. But gradual conversations with
others helped identify key problems. And in the iterative refinements I came to
the intuitive realisation that they were somehow two aspects of the same whole.
That there was a simplicity beyond the complexity.
And in my attempt to unify the elements -- through hundreds of conversations --
early last year, I ended up with:
.. raw:: html
<div class="center">
<a href="http://cloud.github.com/downloads/tav/plexnet/gfx.toman-ecology.png" title="Toman Ecology"><img
src="http://cloud.github.com/downloads/tav/plexnet/gfx.toman-ecology.png"
alt="Toman Ecology"
width="498px"
height="361px" /></a>
</div>
But it was only after yet more criticism and dialogue earlier this year that I
finally ended up with the true essence of the model. What I now call the "Espian
ecology" -- where the initial Pecus I had touched upon and the gift economy are
just two parts of one simple structure.
I'll write an article on it later this month. Until then, what has your
experiences been with regards to the evolution of ideas?
\ No newline at end of file
diff --git a/website/js/init.js b/website/js/init.js
index 3ef0f65..76d5344 100644
--- a/website/js/init.js
+++ b/website/js/init.js
@@ -1,107 +1,106 @@
// Released into the public domain by tav <tav@espians.com>
var startup = function () {
var query = '';
$("a").each(function(idx, elm) {
if (elm.rel && elm.rel.indexOf('disqus:') >= 0) {
query += 'url' + idx + '=' + encodeURIComponent(elm.rel.split('disqus:')[1]) + '&';
}
});
$.getScript('http://disqus.com/forums/' + DISQUS_FORUM + '/get_num_replies.js?' + query);
$('.twitter-share').click(function () {
window.open(this.href, 'twitter', 'width=600,height=429,scrollbars=yes');
return false;
});
$('.fb-share').click(function () {
window.open(this.href, 'fb', 'width=600,height=400,scrollbars=yes');
return false;
});
if (!document.getElementById('table-of-contents'))
return;
document.getElementById('table-of-contents').style.display = 'none';
var abstractob = document.getElementById('abstract');
var toc_handler = document.createElement('span');
toc_handler.id = "toc-handler";
var toc_handler_a = document.createElement('a');
toc_handler_a.href = "#";
toc_handler_a.appendChild(document.createTextNode("Table of Contents"));
var toc_status = 0;
toc_handler_a.onclick = function () {
if (toc_status == 0) {
toc_status = 1;
document.getElementById('table-of-contents').style.display = 'block';
return false;
} else {
toc_status = 0;
document.getElementById('table-of-contents').style.display = 'none';
return false;
}
};
toc_handler.appendChild(document.createTextNode(" [ "));
toc_handler.appendChild(toc_handler_a);
toc_handler.appendChild(document.createTextNode(" ]"));
var p_elems = abstractob.getElementsByTagName("p");
p_elems[p_elems.length - 1].appendChild(toc_handler);
toc_handler.style.fontSize = '0.9em';
var hrefs = document.getElementById('table-of-contents').getElementsByTagName('a');
for (var i=0; i < hrefs.length; i++) {
if (hrefs[i].href.indexOf('#ignore-this') != -1)
hrefs[i].parentNode.style.display = 'none';
}
};
// -----------------------------------------------------------------------------
// Utility Functions
// -----------------------------------------------------------------------------
var setupGoogleAnalytics = function () {
var proto = document.location.protocol;
if (proto === 'file:')
return;
window._gaq = [
['_setAccount', GOOGLE_ANALYTICS_CODE],
- ['_setDomainName', GOOGLE_ANALYTICS_HOST],
['_trackPageview']
];
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
if (proto === 'https:') {
ga.src = 'https://ssl.google-analytics.com/ga.js';
} else {
- ga.src = 'http://ssl.google-analytics.com/ga.js';
+ ga.src = 'http://www.google-analytics.com/ga.js';
}
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(ga, script);
})();
};
var translate = function (elem) {
var url = 'http://translate.google.com/translate?u=';
if (elem.options[elem.selectedIndex].value !="") {
parent.location= url + encodeURIComponent(PAGE_URI) + elem.options[elem.selectedIndex].value;
}
};
// -----------------------------------------------------------------------------
// Init
// -----------------------------------------------------------------------------
setupGoogleAnalytics();
$(startup);
|
tav/oldblog
|
b96b32db0b062531d4454f129ab4716c8923350d
|
Finished the section on parallel deployment.
|
diff --git a/_layouts/site.genshi b/_layouts/site.genshi
index 95823ee..f8bb594 100644
--- a/_layouts/site.genshi
+++ b/_layouts/site.genshi
@@ -1,180 +1,180 @@
---
license: Public Domain
---
<!DOCTYPE html>
<html xmlns:py="http://genshi.edgewall.org/">
<head>
<title>${Markup(site_title)}<py:if test="defined('title')"> » ${Markup(title)}</py:if></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
<meta name="tweetmeme-title" content="${Markup(title)}" />
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<meta name="author" content="tav" />
<meta name="description" content="${site_description}" />
<meta name="copyright" content="This work has been placed into the Public Domain." />
<meta name="document-rating" content="general" />
<link rel="icon" type="image/png" href="gfx/aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds.feedburner.com/asktav" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="css/site.css" />
<style type="text/css" media="print">
#ignore-this { display: none; }
</style>
<style type="text/css">
.ascii-art .literal-block {
line-height: 1em !important;
}
.cmd-line {
background-color: #000;
color: #fff;
padding: 5px;
margin-left: 2em;
margin-right: 2em;
}
.cmd-ps1 {
color: #999;
}
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
#site-title { padding-top: 0px; }
</style>
<![endif]-->
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://use.typekit.com/por2lgv.js"></script>
<script>
GOOGLE_ANALYTICS_CODE = "UA-90176-8";
GOOGLE_ANALYTICS_HOST = "tav.epians.com";
DISQUS_FORUM = 'asktav';
PAGE_URI = '${'http://tav.espians.com/' + __name__}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
try{
Typekit.load();
} catch(e) {};
</script>
<script src="js/init.js"></script>
</head>
<body>
<div id="main">
<div id="site-header">
- <a href="/" id="site-title" title="Tav's Blog">
+ <a href="/" id="site-title" title="${site_title}">
Tav's Blog →
</a>
<div id="site-links">
<form id="translation_form"><select id="lang_select" onchange="translate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form>
<a href="/" title="${site_description}">Home</a>
<a href="archive.html" title="Site Index">Archive</a>
<a href="about-tav.html" title="About Tav">About Tav</a>
</div>
<hr class="clear" />
</div>
<div class="article-nav"></div>
<div id="intro">
<div class="center">
<img src="gfx/profile-smoking.jpg" />
</div>
<h1>
I'm Tav, a 28yr old from London. I enjoy working on large-scale
social, economic and technological systems.
</h1>
<strong>Follow</strong>
<div class="follow-link">
<a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="gfx/icon.twitter.png" /></a> <a href="http://twitter.com/tav" title="Follow @tav on Twitter">tav</a>
</div>
<div class="follow-link">
<a href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog"><img
src="gfx/icon.rss.png" /></a> <a
href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog">tav's blog</a>
</div>
<div class="follow-link">
<a href="https://github.com/tav" title="Follow @tav on GitHub"><img src="gfx/icon.github.png" class="absmiddle" /></a> <a href="https://github.com/tav" title="Follow @tav on GitHub">tav</a>
</div>
<br/>
<strong>Contact</strong>
<div class="follow-link">
<a href="mailto:tav@espians.com" title="Email tav@espians.com"><img src="gfx/icon.gmail.png" /></a> <a href="mailto:tav@espians.com" title="Email tav@espians.com">tav@espians.com</a>
</div>
<div class="follow-link">
<a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook"><img src="gfx/icon.facebook.png" /></a> <a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook">asktav</a>
</div>
<div class="follow-link">
<a href="skype:addname?name=tavespian" title="Contact tavespian on Skype"><img src="gfx/icon.skype.png" /></a> <a href="skype:addname?name=tavespian" title="Contact tavespian on Skype">tavespian</a>
</div>
</div>
<div id="page">
<div>${Markup(content)}</div>
</div>
<hr class="clear" />
<div class="article-nav"></div>
</div>
</body>
</html>
diff --git a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
index 0168ef6..b50fcd5 100644
--- a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
+++ b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
@@ -1,1004 +1,1110 @@
---
created: 2011-02-14, 08:54
layout: post
type: draft
license: Public Domain
---
======================================================
Fabric Python with Cleaner API and Parallel Deployment
======================================================
`Fabric <http://fabfile.org/>`_ is an awesome tool. Like `Capistrano
<https://github.com/capistrano/capistrano/wiki/2.x-Getting-Started>`_ and `Vlad
<http://rubyhitsquad.com/Vlad_the_Deployer.html>`_, it makes deployments a lot
simpler than with shell scripts on their own.
.. raw:: html
<div class="float-right-aligned">
<a href="http://www.flickr.com/photos/stars6/4381851322/in/photostream/"><img
src="http://farm3.static.flickr.com/2775/4381851322_d46fd7d75e.jpg"
alt="Datacenter Work" width="400px" height="267px" /></a><br />
<div class="image-caption">
by <a href="http://www.flickr.com/photos/stars6/">stars6</a>
</div>
</div>
However, once the complexity of your setup starts to grow, you very quickly
start wishing for a cleaner and more powerful API.
And once you are deploying to more than 30 servers, you really wish that Fabric
would run commands in parallel instead of doing them sequentially, one after
another.
Having recently experienced this pain, I decided to rework the core of Fabric.
I've documented it below -- describing all the changes to the `current Fabric
1.0a <http://docs.fabfile.org/1.0a/>`_ -- including funky new features like
``fab shell`` and staged deployments!
.. more
.. class:: intro-box
https://github.com/tav/pylibs/tree/master/fabric
Task Decorator
--------------
Traditionally, *all* functions within your ``fabfile.py`` were implicitly
exposed as Fabric commands. So once you started abstracting your script to be
more manageable, you had to use ``_underscore`` hacks to stop functions being
exposed as commands, e.g.
.. syntax:: python
from support.module import SomeClass as _SomeClass
from urllib import urlencode as _urlencode, urlopen as _urlopen
def _support_function():
...
Not only is this ugly and cumbersome, but it also goes against `The Zen of
Python <http://www.python.org/dev/peps/pep-0020/>`_ philosophy of "explicit is
better than implicit". So I've added a ``@task`` decorator to explicitly mark
functions as Fabric commands, e.g.
.. syntax:: python
from urllib import urlopen
from fabric.api import *
def get_latest_commit():
return urlopen('http://commits.server.com/latest').read()
@task
def check():
"""check if local changes have been committed"""
local_version = local('git rev-parse HEAD')
if local_version != get_latest_commit():
abort("!! Local changes haven't been committed !!")
@task
def deploy():
"""publish the latest version of the app"""
with cd('/var/app'):
run('git remote update')
run('git checkout %s' % get_latest_commit())
sudo("/etc/init.d/apache2 graceful")
The above uses ``@task`` to explicitly mark ``check`` and ``deploy`` as Fabric
commands so that they can be run as usual, i.e. ``fab check`` and ``fab
deploy``. Any functions and classes you import or define don't have to be
"hidden" with the ``_underscore`` hack.
For backwards compatibility, if you never use the ``@task`` decorator, you'll
continue to get the traditional behaviour.
YAML Config
-----------
It's preferable not to hard-code configurable values into fabfiles. This enables
you to reuse the same fabfile across different projects and keep it updated
without having to constantly copy, paste and modify.
So I've added native config support to Fabric. You can enable it by simply
specifying the ``env.config_file`` variable:
.. syntax:: python
env.config_file = 'deploy.yaml'
This will load and parse the specified `YAML file
<http://en.wikipedia.org/wiki/YAML>`_ before running any commands. The
configuration values will then be accessible from ``env.config``. This object is
simply a dictionary with dot-attribute access similar to the ``env`` dictionary.
You can then keep your fabfiles clean from hard-coded values, e.g.
.. syntax:: python
def get_latest_commit():
return urlopen(env.config.commits_server).read()
@task
def deploy():
with cd(env.config.app_directory):
...
Script Execution
----------------
It really helps to be able to quickly iterate the scripts that you will be
calling with Fabric. And whilst you should eventually create them as individual
files and sync them as part of your deployment, it'd be nice if you could try
them out during development.
To help with this I've added a new ``execute()`` builtin. This lets you execute
arbitrary scripts on remote hosts, e.g.
.. syntax:: python
@task
def stats():
memusage = execute("""
#! /usr/bin/env python
import psutil
pid = open('pidfile').read()
process = psutil.Process(int(pid))
print process.get_memory_percent()
""", 'memusage.py', verbose=False, dir='/var/ampify')
Behind the scenes, ``execute()`` will:
* Strip any common leading whitespace from every line in the source.
* Copy the source into a file on the remote server.
* If the optional ``name`` parameter (the 2nd parameter) had been specified,
then the given name will be used, otherwise an auto-generated name will be
used.
* If the optional ``dir`` parameter was specified, then the file will be created
within the given directory, otherwise it'll be created on the remote ``$HOME``
directory.
* The file will then be made executable, i.e. ``chmod +x``.
* And, finally, it will be run and the response will be returned. Unless the
``verbose`` parameter is set to ``False``, then it will by default also output
the response to the screen.
As you can imagine, ``execute()`` makes it very easy to rapidly try out and
develop your development logic. Your scripts can be in whatever languages you
can run on your remote hosts -- Ruby, Perl, Bash, Python, JavaScript, whatever.
Environment Variable Manager
----------------------------
When calling various command line tools, you often have to mess with environment
variables like ``$PATH``, ``$NODE_PATH``, ``$PYTHONPATH``, etc. To deal with
this, Fabric forced you to write things like:
.. syntax:: python
NODE_PATH = "NODE_PATH=$NODE_PATH:%s" % node_libs
run("%s vows" % NODE_PATH)
run("%s coffee -c amp.coffee" % NODE_PATH)
Instead you can now do:
.. syntax:: python
with env.NODE_PATH(node_libs):
run("vows")
run("coffee -c amp.coffee")
That is, if you call a property on the ``env`` object which is composed of only
the ``ABCDEFGHIJKLMNOPQRSTUVWXYZ_`` characters, then a `Python Context Manager
<http://www.python.org/dev/peps/pep-0343/>`_ is generated which will manage the
use of the environment variables for you.
The manager has the following constructor signature:
.. syntax:: python
manager(value, behaviour='append', sep=os.pathsep, reset=False)
So, if you'd called ``env.PATH(value, behaviour)``, the way the ``value`` is
treated will depend on the ``behaviour`` parameter which can be one of the
following:
* ``append`` -- appends value to the current ``$PATH``, i.e.
``PATH=$PATH:<value>``
* ``prepend`` -- prepends value to the current ``$PATH``, i.e.
``PATH=<value>:$PATH``
* ``replace`` -- ignores ``$PATH`` altogether, i.e. ``PATH=<value>``
The ``sep`` defaults to ``:`` on most platforms and determines how the values
are concatenated. However, if you call the manager with no arguments at all or
stringify it, it will return the string which would be used during execution,
e.g.
.. syntax:: python
print env.NODE_PATH # NODE_PATH=$NODE_PATH:/opt/ampify/libs/node
The various calls can be also nested, e.g.
.. syntax:: python
with env.PATH('/usr/local/bin'):
with env.PATH('/home/tav/bin'):
print env.PATH # PATH=$PATH:/usr/local/bin:/home/tav/bin
with env.PATH('/opt/local/bin', 'replace'):
with env.PATH('/bin', 'prepend'):
print env.PATH # PATH=/bin:/opt/local/bin
print env.PATH # PATH=$PATH:/usr/local/bin
You can specify ``reset=True`` to discard any nested values, e.g.
.. syntax:: python
with env.PATH('/opt/ampify/bin', 'prepend'):
with env.PATH('/home/tav/bin', reset=True):
print env.PATH # PATH=$PATH:/home/tav/bin
Extension Hooks
---------------
I've added native hooks support so that you can extend certain aspects of Fabric
without having to resort to monkey-patching. You attach functions to specific
hooks by using the new ``@hook`` decorator, e.g.
.. syntax:: python
@hook('config.loaded')
def default_config():
if 'port' in env.config:
return
port = prompt("port number?", default=8080, validate=int)
env.config.port = port
For the moment, only the following builtin hooks are defined. It's possible that
I may add support for individual ``<command>.before`` and ``<command>.after``
hooks, but so far I haven't needed that functionality.
+---------------------+-----------------------------+------------------------+
| Hook Name | Hook Function Signature | Description |
+=====================+=============================+========================+
-| ``exec.before`` | ``func(cmds, cmds_to_run)`` | |hook-exec-before| |
+| ``commands.before`` | ``func(cmds, cmds_to_run)`` | |hook-commands-before| |
+---------------------+-----------------------------+------------------------+
| ``config.loaded`` | ``func()`` | |hook-config-loaded| |
+---------------------+-----------------------------+------------------------+
-| ``exec.after`` | ``func()`` | |hook-exec-after| |
+| ``commands.after`` | ``func()`` | |hook-commands-after| |
+---------------------+-----------------------------+------------------------+
| ``listing.display`` | ``func()`` | |hook-listing-display| |
+---------------------+-----------------------------+------------------------+
.. |hook-config-loaded| replace::
Run after any config file has been parsed and loaded.
-.. |hook-exec-after| replace::
+.. |hook-commands-after| replace::
- Run after all the commands are run.
+ Run after *all* the commands are run.
-.. |hook-exec-before| replace::
+.. |hook-commands-before| replace::
- Run before all the commands are run (including the config handling).
+ Run before *all* the commands are run (including the config handling).
.. |hook-listing-display| replace::
Run when the commands listing has finished running in response to ``fab`` or
``fab --list``. Useful for adding extra info.
You can access the functions attached to a specific hook by calling
``hook.get()``, e.g.
.. syntax:: python
functions = hook.get('config.loaded')
You can also define your own custom hooks and call the attached functions by
using ``hook.call()``. This takes the hook name as the first parameter and all
subsequent parameters are used when calling the hook's attached functions.
Here's an example that shows ``hook.call()`` in action along with ``env.hook``
and the ability to attach the same function to multiple hooks by passing
multiple names to the ``@hook`` decorator:
.. syntax:: python
@hook('deploy.success', 'deploy.failure')
def irc_notify(release_id, info=None):
client = IrcClient('devbot', 'irc.freenode.net', '#esp')
if env.hook == 'deploy.success':
client.msg("Successfully deployed: %s" % release_id)
else:
client.msg("Failed deployment: %s" % release_id)
@hook('deploy.success')
def webhook_notify(release_id, info):
webhook.post({'id': release_id, 'payload': info})
@task
def deploy():
release_id = get_release_id()
try:
...
info = get_release_info()
except Exception:
hook.call('deploy.failure', release_id)
else:
hook.call('deploy.success', release_id, info)
And, finally, you can disable specific hooks via the ``--disable-hooks`` command
line option which takes space-separated patterns, e.g.
.. syntax:: console
$ fab deploy --disable-hooks 'config.loaded deploy.*'
You can override these disabled hooks in turn with the ``--enable-hooks``
option, e.g.
.. syntax:: console
$ fab deploy --disable-hooks 'deploy.*' --enable-hooks 'deploy.success'
Both ``hook.call()`` and ``hook.get()`` respect these command-line parameters,
so if you ever need to access the raw hook registry dict, you can access it
directly via ``hook.registry``.
Interpolation & Directories Support
-----------------------------------
Fabric provides a number of builtin functions that let you make command line
calls:
* ``local()`` -- runs a command on the local host.
* ``run()`` -- runs a command on a remote host.
* ``sudo()`` -- runs a sudoed command on a remote host.
I've added two optional parameters to these. A ``dir`` parameter can be used to
specify the directory from within which the command should be run, e.g.
.. syntax:: python
@task
def restart():
run("amp restart", dir='/opt/ampify')
And a ``format`` parameter can be used to access the new formatted strings
functionality, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}", format=True)
This makes use of the `Advanced String Formatting
<http://www.python.org/dev/peps/pep-3101/>`_ support that is available in Python
2.6 and later. The ``env`` object is used to look-up the various parameters,
i.e. the above is equivalent to:
.. syntax:: python
@task
def backup():
command = "backup.rb {app_directory} {s3_key}".format(**env)
run(command)
By default, ``format`` is set to ``False`` and the string is run without any
substitution. But if you happen to find formatting as useful a I do, you can
enable it as default by setting:
.. syntax:: python
env.format = True
You can then use it without having to constantly set ``format=True``, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}")
Fabric Contexts
---------------
Deployment setups vary tremendously. I've used Fabric for everything from simple
single-machine deployments to web app deployments across multiple data centers
to even physical multi-touch installations at the `Museum of Australian
Democracy
<http://www.moadoph.gov.au/exhibitions/prime-ministers-of-australia-exhibition/>`_.
-Unfortunately, I've consistently found the ``@hosts`` and ``@roles`` support
-offered by Fabric to be sub-optimal for these dramatically different setups.
+But for anything but the simplest of setups, the support offered by Fabric in
+terms of ``@hosts`` and ``@roles`` is far from satisfactory.
And providing an API that covers the various scenarios is hard!
When doing a major upgrade of a web app, you might want to do something like:
* Switch the web servers to show a "planned maintenance" notice.
* Migrate the database to new schemas.
* Upgrade the app servers.
* Update app routing on the configuration servers.
* Enable the web servers to continue serving requests normally.
Context Runner
--------------
Parallel Deployment
-------------------
-Like with the ``.run()`` context runner call, ``.multirun()`` also accepts a
-function to execute instead of a command string. The utility ``.multilocal()``
-method leverages this functionality to run commands locally for each of the
+You no longer have to patiently wait whilst Fabric runs your commands on each
+server one by one. By taking advantage of the ``.multirun()`` context runner
+call, you can now run commands in parallel, e.g.
+
+.. syntax:: python
+
+ @task
+ def deploy():
+ responses = env('app-servers').multirun('make build')
+ if failed(responses):
+ ...
+
+The above will run ``make build`` on the ``app-servers`` in parallel -- reducing
+your deployment time significantly! The returned ``responses`` will be a list of
+the individual responses from each host in order.
+
+If any of the hosts threw an exception, then the corresponding element within
+``responses`` will contain it. Two new builtins are provided to quickly
+determine the nature of the response:
+
+* ``succeeded`` -- returns True if all the response items were successful.
+
+* ``failed`` -- returns True if any of the response items failed or threw an
+ exception.
+
+You can loop through the response and the corresponding host/setting values by
+using the ``.ziphost()`` and ``.zipsetting()`` generator methods on the returned
+list-like ``responses`` object, e.g.
+
+.. syntax:: python
+
+ @task
+ def deploy():
+ responses = env('app-servers').multirun('make build')
+ for response, host in responses.ziphost():
+ ...
+
+By default you see the output from all hosts, but sometimes you just want a
+summary, so you can specify ``condensed=True`` to ``.multirun()`` and it'll
+provide a much quieter, running report instead, e.g.
+
+::
+
+ [multirun] Running 'make build test' on 31 hosts
+ [multirun] Finished on dev2.ampify.it
+ [multirun] Finished on dev7.ampify.it
+ [multirun] 2/31 completed ...
+
+Also, when dealing with large number of servers, you'll run into laggy servers
+from time to time. And depending on your setup, it may not be critical that
+*all* servers run the command. To help with this ``.multirun()`` takes two
+optional parameters:
+
+* ``laggards_timeout`` -- the number of seconds to wait for laggards once the
+ satisfactory number of responses have been received -- needs to be an int
+ value.
+
+* ``wait_for`` -- the number of responses to wait for -- this should be an int,
+ but can also be a float value between ``0.0`` and ``1.0``, in which case it'll
+ be used as the factor of the total number of servers.
+
+So, for the following:
+
+.. syntax:: python
+
+ responses = env('app-servers').multirun(
+ 'make build', laggards_timeout=20, wait_for=0.8
+ )
+
+The ``make build`` command will be run on the various ``app-servers`` and once
+80% of the responses have been received, it'll continue to wait up to 20 seconds
+for any laggy servers before returning the responses.
+
+The ``responses`` list will contain the new ``TIMEOUT`` builtin object for the
+servers that didn't return a response in time Like with the ``.run()`` context
+runner call, ``.multirun()`` also accepts a function to execute instead of a
+command string, e.g.
+
+.. syntax:: python
+
+ env.format = True
+
+
+ def migrate_db():
+ run('./manage.py schemamigration --auto {app_name}')
+ run('./manage.py migrate {app_name}')
+
+
+ @task
+ def deploy():
+ env('frontends').multirun('routing --disable')
+ env('app-nodes').multirun(migrate_db)
+ env('frontends').multirun('routing --enable')
+
+
+ @task
+ def migrate():
+ env('app-nodes').multirun(migrate_db)
+
+There's also a ``.multilocal()`` which runs the command locally for each of the
hosts in parallel, e.g.
.. syntax:: python
env.format = True
@task
def db_backup():
env('db-servers').multilocal('backup.rb {host}')
Behind the scenes, ``.multirun()`` uses ``fork()`` and `domain sockets
<http://en.wikipedia.org/wiki/Unix_domain_socket>`_, so it'll only work on Unix
platforms. You can specify the maximum number of parallel processes to spawn at
any one time by specifying ``env.multirun_pool_size`` which is set to ``10`` by
default, e.g.
.. syntax:: python
env.multirun_pool_size = 200
+There's also an ``env.multirun_child_timeout`` which specifies the number of
+seconds a child process will wait to hear from the parent before committing
+suicide. It defaults to ``10`` seconds, but you can configure it to suit your
+setup:
+
+.. syntax:: python
+
+ env.multirun_child_timeout = 24
+
And, oh, there's also a ``.multisudo()`` for your convenience.
Fabric Shell
------------
Sometimes you just want to run a bunch of commands on a number of different
servers. So I've added a funky new feature -- Fabric shell mode:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqccu/python" title="Fabric Shell"><img
src="http://img.skitch.com/20110212-g8ha9cd5g441m4q3y21gewmnha.png" /></a>
</div>
Once you are in the shell, all of your commands will be sequentially ``run()``
on the respective hosts for your calling context. You can also use the
``.shell-command`` syntax to call shell builtin commands -- including your own
custom ones!
You start shells from within your Fabric commands by invoking the ``.shell()``
method of a context runner. Here's sample code to enable ``fab shell``:
.. syntax:: python
@task('app-servers', run_per_context=False)
def shell():
"""start a shell within the current context"""
env().shell(format=True)
The above defaults to the ``app-servers`` context when you run ``fab shell``,
but you can always override the context from the command line, e.g.
.. syntax:: console
$ fab shell @db-servers
And if your Python has been compiled with `readline support
<http://docs.python.org/library/readline.html>`_, then you can also leverage the
tab-completion support that I've added:
* Terms starting with ``{`` auto-complete on the properties within the ``env``
object to make it easy for you to use the string formatting support.
* Terms starting with ``.`` auto-complete on the available shell builtin
commands.
* All other terms auto-complete on the list of available executables on your
local machine's ``$PATH``.
Other readline features have been enabled too, e.g. command history with up/down
arrows, ``^r`` search and even cross-session history. You can configure where
the history is saved by setting ``env.shell_history_file`` which defaults to:
.. syntax:: python
env.shell_history_file = '~/.fab-shell-history'
Shell Builtins
--------------
As mentioned above, you can call various ``.shell-commands`` from within a
Fabric shell to do something other than ``run()`` a command on the various
hosts, e.g.
.. syntax:: irb
>> .multilocal backup.rb {host_string}
The above will run the equivalent of the following in parallel for each host:
.. syntax:: python
local("backup.rb {host_string}")
The following builtins are currently available:
* ``.cd`` -- changes the working directory for all future commands.
* ``.help`` -- displays a list of the available shell commands.
* ``.info`` -- list the current context and the respective hosts.
* ``.local`` -- runs the command locally.
* ``.multilocal`` -- runs the command in parallel locally for each host.
* ``.multirun`` -- runs the command in parallel on the various hosts.
* ``.multisudo`` -- runs the sudoed command in parallel on the various hosts.
* ``.sudo`` -- runs the sudoed command on the various hosts.
* ``.toggle-format`` -- toggles string formatting support.
You can define your own by using the new ``@shell`` decorator, e.g.
.. syntax:: python
@shell
def python_version(spec, arg):
with hide('running', 'output'):
if arg == 'full':
version = run('python -c "import sys; print sys.version"')
else:
version = run(
"python -c 'import sys; print "
'".".join(map(str, sys.version_info[:3]))\''
)
puts("python %s" % version)
The above can then be called from within a shell, e.g.
.. syntax:: irb
>> .python-version
[dev1.ampify.it] python 2.5.2
[dev3.ampify.it] python 2.7.0
The ``spec`` object is initialised with the various variables that the
``.shell()`` method was originally called with, e.g. ``dir``, ``format``, etc.
All changes made, e.g. ``spec.dir = '/var/ampify'``, are persistent and will
affect all subsequent commands within the shell.
The ``arg`` is a string value of everything following the shell command name,
e.g. for ``.local echo hi``, it will be ``"echo hi"``. The command name is
derived from the function name, but you can provide your own as the first
parameter to the ``@shell`` decorator.
And, finally, you can specify ``single=True`` to the ``@shell`` decorator to
specify that you only want the command to be run a single time and not
repeatedly for every host, e.g.
.. syntax:: python
@shell('hello', single=True)
def demo(spec, arg):
print "Hello", arg.upper()
The above can then be called from within a shell, e.g.
.. syntax:: irb
>> .hello tav
Hello TAV
The ``env.ctx`` is set for even single-mode shell commands, so you can always
take advantage of context runners, e.g.
.. syntax:: python
@shell
def backup(spec, arg):
env().multirun(...)
Command Line Listing
--------------------
When ``fab`` was run without any arguments, it used to spit out the help message
with the various command line options:
.. syntax:: console
$ fab
Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
Options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
-l, --list print list of possible commands and exit
--shortlist print non-verbose list of possible commands and exit
-d COMMAND, --display=COMMAND
print detailed info about a given command and exit
...
As useful as this was, I figured it'd be more useful to list the various
commands without having to constantly type ``fab --list``. So now when you run
``fab`` without any arguments, it lists the available commands instead, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
You can of course still access the help message by running either ``fab -h`` or
``fab --help``. And you can hide commands from being listed by specifying
``display=None`` with the ``@task`` decorator, e.g.
.. syntax:: python
@task(display=None)
def armageddon():
...
Staged Deployment
-----------------
For most serious deployments, you tend to have distinct environments, e.g.
testing, staging, production, etc. And `existing
<http://blog.jeremi.info/entry/my-git-workflow-to-deploy-an-application-to-appengine>`_
`fabric <http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/>`__
`setups <https://github.com/bueda/ops>`_ tend to have similarly named commands
so you can run things like:
.. syntax:: console
$ fab production deploy
Now, not being a fan of repeatedly adding the same functionality to all my
fabfiles, I've added staged deployment support to Fabric. You can enable it by
specifying an ``env.stages`` list value, e.g.
.. syntax:: python
env.stages = ['staging', 'production']
The first item in the list is taken to be the *default* and overridable commands
of the following structure are automatically generated for each item:
.. syntax:: python
@task(display=None)
def production():
puts("env.stage = production", prefix='system')
env.stage = 'production'
That is, it will update ``env.stage`` with the appropriate value and print out a
message saying so, e.g.
.. syntax:: console
$ fab production check deploy
[system] env.stage = production
...
And if your fab command line call didn't start with one of the stages, it will
automatically run the one for the default stage, e.g.
.. syntax:: console
$ fab check deploy
[system] env.stage = staging
...
For added convenience, the environments are also listed when you run ``fab``
without any arguments, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
Available environments:
staging
production
And, for further flexibility, you can override ``env.stages`` with the
``FAB_STAGES`` environment variable. This takes a comma-separated list of
environment stages and, again, the first is treated as the default, e.g.
.. syntax:: console
$ FAB_STAGES=development,production fab deploy
[system] env.stage = development
...
Hyphenated Commands
-------------------
This is a minor point, but I find hyphens, e.g. ``deploy-ampify``, to be more
aesthetically pleasing than underscores, i.e. ``deploy_ampify``. So Fabric now
displays and supports hyphenated variants of all commands, e.g. for the
following fabfile:
.. syntax:: python
from fabric.api import *
@task
def deploy_ampify():
"""deploy the current version of ampify"""
...
The command listing shows:
.. syntax:: console
$ fab
Available commands:
deploy-ampify deploy the current version of ampify
And you can run the command with:
.. syntax:: console
$ fab deploy-ampify
Command Line Env Flags
----------------------
You can now update the ``env`` object directly from the command line using the
new env flags syntax:
* ``+<key>`` sets the value of the key to ``True``.
* ``+<key>:<value>`` sets the key to the given string value.
So, for the following content in your fabfile:
.. syntax:: python
env.config_file = 'deploy.yaml'
env.debug = False
Running the following will set ``env.config_file`` to the new value:
.. syntax:: console
$ fab <commands> +config_file:alt.yaml
And the following will set ``env.debug`` to ``True``:
.. syntax:: console
$ fab <commands> +debug
The env flags are all set in the order given on the command line and before any
commands are run (including the config file handling if one is specified). And
you can, of course, specify as many env flags as you want.
Optimisations
-------------
It won't make much of a difference, but for my own sanity I've made a bunch of
minor optimisations to Fabric, e.g.
* Removed repeated look-up of attributes within loops.
* Removed repeated local imports within functions.
* Removed redundant double-wrapping of functions within the ``@hosts`` and
``@roles`` decorators.
Colors Support
--------------
You can enable the optional colors support by setting ``env.colors``, i.e.
.. syntax:: python
env.colors = True
Here's a screenshot of it in action:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqge6/fabric-shell"><img
src="http://img.skitch.com/20110211-nep3wmpi33qb2c4a13bf7fsgja.png"
alt="Fabric with Colors" /></a>
</div>
You can customise the colors by modifying the ``env.color_settings`` property.
By default it is set to:
.. syntax:: python
env.color_settings = {
'abort': yellow,
'error': yellow,
'finish': cyan,
'host_prefix': green,
'prefix': red,
'prompt': blue,
'task': red,
'warn': yellow
}
You can find the color functions in the ``fabric.colors`` module.
Logging Improvements
--------------------
The builtin ``puts()`` and ``fastprint()`` logging functions have also been
extended with the optional ``format`` parameter and ``env.format`` support
similar to the ``local()`` and ``run()`` builtins, so that instead of having to
do something like:
.. syntax:: python
@task
def db_migrate():
puts(
"[%s] [database] migrating schemas for %s" %
(env.host_string, env.db_name)
)
You can now just do:
.. syntax:: python
env.format = True
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database')
And it will output something like:
.. syntax:: console
$ fab db-migrate
[somehost.com] [database] migrating schemas for ampify
The second parameter which was previously a boolean-only value that was used to
control whether the host string was printed or not, can now also be a string
value -- in which case the string will be used as the prefix instead of the host
string.
You can still control if a host prefix is *also* printed by using the new
optional ``show_host`` parameter, e.g.
.. syntax:: python
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database', show_host=False)
Will output something like:
.. syntax:: console
$ fab db-migrate
[database] migrating schemas for ampify
And if you'd enabled ``env.colors``, the prefix will be also colored according
to your settings!
Autocompletion
--------------
`Bash completion <http://www.debian-administration.org/articles/316>`_ is one of
those features that really helps you to be more productive. Just include the
following in your ``~/.bashrc`` or equivalent file and you'll be able to use
Fabric's new command completion support:
.. syntax:: bash
_fab_completion() {
COMPREPLY=( $( \
COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \
COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
OPTPARSE_AUTO_COMPLETE=1 $1 ) )
}
complete -o default -F _fab_completion fab
It completes on all available commands and command line options, e.g.
.. syntax:: console
$ fab --dis<tab>
--disable-known-hosts --disable-hooks --display
Also, since Fabric has no way of knowing which `command line env flags`_ and
contexts you might be using, you can specify additional autocompletion items as
an ``env.autocomplete`` list value, e.g.
.. syntax:: python
env.autocomplete = ['+config_file:', '+debug', '@db-servers']
This will then make those values available for you to autocomplete, i.e.
.. syntax:: console
$ fab +<tab>
+config_file: +debug
Backwards Compatibility
-----------------------
All these changes should be fully backwards compatible. That is, unless you
happen to have specified any of the new ``env`` variables like ``env.stages``,
your existing fabfiles should run as they've always done. Do let me know if this
is not the case...
Usage
-----
If you'd like to take advantage of these various changes, the simplest thing to
diff --git a/yatiblog.conf b/yatiblog.conf
index c75fc12..0a3216d 100644
--- a/yatiblog.conf
+++ b/yatiblog.conf
@@ -1,17 +1,19 @@
site_url: http://tav.espians.com
site_title: Tav's Blog
site_nick: asktav
-site_description: An exploration of the ideas and the journey towards creating a potent world for all of us.
+site_description:
+ I'm Tav, a 28-year old from London. I enjoy working on
+ large-scale social, economic and technological systems.
site_analytics_code: UA-90176-8
site_author: tav
site_author_nick: tav
site_context: tav
with_props: true
type: post
index_pages:
- index.html: index.genshi
- archive.html: archive.genshi
- feed.rss: feed.genshi
- index.js: indexjs.genshi
|
tav/oldblog
|
59333e757baf520934539c7af077524346a6c376
|
Further WIP on Fabric.
|
diff --git a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
index 600861b..0168ef6 100644
--- a/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
+++ b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
@@ -1,990 +1,1048 @@
---
created: 2011-02-14, 08:54
layout: post
type: draft
license: Public Domain
---
======================================================
Fabric Python with Cleaner API and Parallel Deployment
======================================================
`Fabric <http://fabfile.org/>`_ is an awesome tool. Like `Capistrano
<https://github.com/capistrano/capistrano/wiki/2.x-Getting-Started>`_ and `Vlad
<http://rubyhitsquad.com/Vlad_the_Deployer.html>`_, it makes deployments a lot
simpler than with shell scripts on their own.
.. raw:: html
<div class="float-right-aligned">
<a href="http://www.flickr.com/photos/stars6/4381851322/in/photostream/"><img
src="http://farm3.static.flickr.com/2775/4381851322_d46fd7d75e.jpg"
alt="Datacenter Work" width="400px" height="267px" /></a><br />
<div class="image-caption">
by <a href="http://www.flickr.com/photos/stars6/">stars6</a>
</div>
</div>
However, once the complexity of your setup starts to grow, you very quickly
start wishing for a cleaner and more powerful API.
And once you are deploying to more than 30 servers, you really wish that Fabric
would run commands in parallel instead of doing them sequentially, one after
another.
Having recently experienced this pain, I decided to rework the core of Fabric.
I've documented it below -- describing all the changes to the `current Fabric
1.0a <http://docs.fabfile.org/1.0a/>`_ -- including funky new features like
``fab shell`` and staged deployments!
.. more
.. class:: intro-box
https://github.com/tav/pylibs/tree/master/fabric
Task Decorator
--------------
Traditionally, *all* functions within your ``fabfile.py`` were implicitly
exposed as Fabric commands. So once you started abstracting your script to be
more manageable, you had to use ``_underscore`` hacks to stop functions being
exposed as commands, e.g.
.. syntax:: python
from support.module import SomeClass as _SomeClass
from urllib import urlencode as _urlencode, urlopen as _urlopen
def _support_function():
...
Not only is this ugly and cumbersome, but it also goes against `The Zen of
Python <http://www.python.org/dev/peps/pep-0020/>`_ philosophy of "explicit is
better than implicit". So I've added a ``@task`` decorator to explicitly mark
functions as Fabric commands, e.g.
.. syntax:: python
from urllib import urlopen
from fabric.api import *
def get_latest_commit():
return urlopen('http://commits.server.com/latest').read()
@task
def check():
"""check if local changes have been committed"""
local_version = local('git rev-parse HEAD')
if local_version != get_latest_commit():
abort("!! Local changes haven't been committed !!")
@task
def deploy():
"""publish the latest version of the app"""
with cd('/var/app'):
run('git remote update')
run('git checkout %s' % get_latest_commit())
sudo("/etc/init.d/apache2 graceful")
The above uses ``@task`` to explicitly mark ``check`` and ``deploy`` as Fabric
commands so that they can be run as usual, i.e. ``fab check`` and ``fab
deploy``. Any functions and classes you import or define don't have to be
"hidden" with the ``_underscore`` hack.
For backwards compatibility, if you never use the ``@task`` decorator, you'll
continue to get the traditional behaviour.
YAML Config
-----------
It's preferable not to hard-code configurable values into fabfiles. This enables
you to reuse the same fabfile across different projects and keep it updated
without having to constantly copy, paste and modify.
So I've added native config support to Fabric. You can enable it by simply
specifying the ``env.config_file`` variable:
.. syntax:: python
env.config_file = 'deploy.yaml'
This will load and parse the specified `YAML file
<http://en.wikipedia.org/wiki/YAML>`_ before running any commands. The
configuration values will then be accessible from ``env.config``. This object is
simply a dictionary with dot-attribute access similar to the ``env`` dictionary.
You can then keep your fabfiles clean from hard-coded values, e.g.
.. syntax:: python
def get_latest_commit():
return urlopen(env.config.commits_server).read()
@task
def deploy():
with cd(env.config.app_directory):
...
Script Execution
----------------
It really helps to be able to quickly iterate the scripts that you will be
calling with Fabric. And whilst you should eventually create them as individual
files and sync them as part of your deployment, it'd be nice if you could try
them out during development.
-To help with this I've added a new ``execute`` builtin. This lets you execute
+To help with this I've added a new ``execute()`` builtin. This lets you execute
arbitrary scripts on remote hosts, e.g.
.. syntax:: python
@task
def stats():
memusage = execute("""
#! /usr/bin/env python
import psutil
pid = open('pidfile').read()
process = psutil.Process(int(pid))
print process.get_memory_percent()
""", 'memusage.py', verbose=False, dir='/var/ampify')
-Behind the scenes, ``execute`` will:
+Behind the scenes, ``execute()`` will:
* Strip any common leading whitespace from every line in the source.
* Copy the source into a file on the remote server.
* If the optional ``name`` parameter (the 2nd parameter) had been specified,
then the given name will be used, otherwise an auto-generated name will be
used.
* If the optional ``dir`` parameter was specified, then the file will be created
within the given directory, otherwise it'll be created on the remote ``$HOME``
directory.
* The file will then be made executable, i.e. ``chmod +x``.
* And, finally, it will be run and the response will be returned. Unless the
``verbose`` parameter is set to ``False``, then it will by default also output
the response to the screen.
-As you can imagine, ``execute`` makes it very easy to rapidly try out and
+As you can imagine, ``execute()`` makes it very easy to rapidly try out and
develop your development logic. Your scripts can be in whatever languages you
can run on your remote hosts -- Ruby, Perl, Bash, Python, JavaScript, whatever.
+Environment Variable Manager
+----------------------------
+
+When calling various command line tools, you often have to mess with environment
+variables like ``$PATH``, ``$NODE_PATH``, ``$PYTHONPATH``, etc. To deal with
+this, Fabric forced you to write things like:
+
+.. syntax:: python
+
+ NODE_PATH = "NODE_PATH=$NODE_PATH:%s" % node_libs
+ run("%s vows" % NODE_PATH)
+ run("%s coffee -c amp.coffee" % NODE_PATH)
+
+Instead you can now do:
+
+.. syntax:: python
+
+ with env.NODE_PATH(node_libs):
+ run("vows")
+ run("coffee -c amp.coffee")
+
+That is, if you call a property on the ``env`` object which is composed of only
+the ``ABCDEFGHIJKLMNOPQRSTUVWXYZ_`` characters, then a `Python Context Manager
+<http://www.python.org/dev/peps/pep-0343/>`_ is generated which will manage the
+use of the environment variables for you.
+
+The manager has the following constructor signature:
+
+.. syntax:: python
+
+ manager(value, behaviour='append', sep=os.pathsep, reset=False)
+
+So, if you'd called ``env.PATH(value, behaviour)``, the way the ``value`` is
+treated will depend on the ``behaviour`` parameter which can be one of the
+following:
+
+* ``append`` -- appends value to the current ``$PATH``, i.e.
+ ``PATH=$PATH:<value>``
+
+* ``prepend`` -- prepends value to the current ``$PATH``, i.e.
+ ``PATH=<value>:$PATH``
+
+* ``replace`` -- ignores ``$PATH`` altogether, i.e. ``PATH=<value>``
+
+The ``sep`` defaults to ``:`` on most platforms and determines how the values
+are concatenated. However, if you call the manager with no arguments at all or
+stringify it, it will return the string which would be used during execution,
+e.g.
+
+.. syntax:: python
+
+ print env.NODE_PATH # NODE_PATH=$NODE_PATH:/opt/ampify/libs/node
+
+The various calls can be also nested, e.g.
+
+.. syntax:: python
+
+ with env.PATH('/usr/local/bin'):
+ with env.PATH('/home/tav/bin'):
+ print env.PATH # PATH=$PATH:/usr/local/bin:/home/tav/bin
+ with env.PATH('/opt/local/bin', 'replace'):
+ with env.PATH('/bin', 'prepend'):
+ print env.PATH # PATH=/bin:/opt/local/bin
+ print env.PATH # PATH=$PATH:/usr/local/bin
+
+You can specify ``reset=True`` to discard any nested values, e.g.
+
+.. syntax:: python
+
+ with env.PATH('/opt/ampify/bin', 'prepend'):
+ with env.PATH('/home/tav/bin', reset=True):
+ print env.PATH # PATH=$PATH:/home/tav/bin
+
+
Extension Hooks
---------------
I've added native hooks support so that you can extend certain aspects of Fabric
without having to resort to monkey-patching. You attach functions to specific
hooks by using the new ``@hook`` decorator, e.g.
.. syntax:: python
@hook('config.loaded')
def default_config():
if 'port' in env.config:
return
port = prompt("port number?", default=8080, validate=int)
env.config.port = port
-For the moment, only the following hooks are defined. It's possible that I may
-add support for individual ``<command>.before`` and ``<command>.after`` hooks,
-but so far I haven't needed that functionality.
+For the moment, only the following builtin hooks are defined. It's possible that
+I may add support for individual ``<command>.before`` and ``<command>.after``
+hooks, but so far I haven't needed that functionality.
+---------------------+-----------------------------+------------------------+
| Hook Name | Hook Function Signature | Description |
+=====================+=============================+========================+
| ``exec.before`` | ``func(cmds, cmds_to_run)`` | |hook-exec-before| |
+---------------------+-----------------------------+------------------------+
| ``config.loaded`` | ``func()`` | |hook-config-loaded| |
+---------------------+-----------------------------+------------------------+
| ``exec.after`` | ``func()`` | |hook-exec-after| |
+---------------------+-----------------------------+------------------------+
| ``listing.display`` | ``func()`` | |hook-listing-display| |
+---------------------+-----------------------------+------------------------+
.. |hook-config-loaded| replace::
Run after any config file has been parsed and loaded.
.. |hook-exec-after| replace::
Run after all the commands are run.
.. |hook-exec-before| replace::
Run before all the commands are run (including the config handling).
.. |hook-listing-display| replace::
Run when the commands listing has finished running in response to ``fab`` or
``fab --list``. Useful for adding extra info.
+You can access the functions attached to a specific hook by calling
+``hook.get()``, e.g.
+
+.. syntax:: python
+
+ functions = hook.get('config.loaded')
+
+You can also define your own custom hooks and call the attached functions by
+using ``hook.call()``. This takes the hook name as the first parameter and all
+subsequent parameters are used when calling the hook's attached functions.
+
+Here's an example that shows ``hook.call()`` in action along with ``env.hook``
+and the ability to attach the same function to multiple hooks by passing
+multiple names to the ``@hook`` decorator:
+
+.. syntax:: python
+
+ @hook('deploy.success', 'deploy.failure')
+ def irc_notify(release_id, info=None):
+ client = IrcClient('devbot', 'irc.freenode.net', '#esp')
+ if env.hook == 'deploy.success':
+ client.msg("Successfully deployed: %s" % release_id)
+ else:
+ client.msg("Failed deployment: %s" % release_id)
+
+
+ @hook('deploy.success')
+ def webhook_notify(release_id, info):
+ webhook.post({'id': release_id, 'payload': info})
+
+
+ @task
+ def deploy():
+ release_id = get_release_id()
+ try:
+ ...
+ info = get_release_info()
+ except Exception:
+ hook.call('deploy.failure', release_id)
+ else:
+ hook.call('deploy.success', release_id, info)
+
+And, finally, you can disable specific hooks via the ``--disable-hooks`` command
+line option which takes space-separated patterns, e.g.
+
+.. syntax:: console
+
+ $ fab deploy --disable-hooks 'config.loaded deploy.*'
+
+You can override these disabled hooks in turn with the ``--enable-hooks``
+option, e.g.
+
+.. syntax:: console
+
+ $ fab deploy --disable-hooks 'deploy.*' --enable-hooks 'deploy.success'
+
+Both ``hook.call()`` and ``hook.get()`` respect these command-line parameters,
+so if you ever need to access the raw hook registry dict, you can access it
+directly via ``hook.registry``.
+
Interpolation & Directories Support
-----------------------------------
Fabric provides a number of builtin functions that let you make command line
calls:
-* ``local`` -- runs a command on the local host.
+* ``local()`` -- runs a command on the local host.
-* ``run`` -- runs a command on a remote host.
+* ``run()`` -- runs a command on a remote host.
-* ``sudo`` -- runs a sudoed command on a remote host.
+* ``sudo()`` -- runs a sudoed command on a remote host.
I've added two optional parameters to these. A ``dir`` parameter can be used to
specify the directory from within which the command should be run, e.g.
.. syntax:: python
@task
def restart():
run("amp restart", dir='/opt/ampify')
And a ``format`` parameter can be used to access the new formatted strings
functionality, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}", format=True)
This makes use of the `Advanced String Formatting
<http://www.python.org/dev/peps/pep-3101/>`_ support that is available in Python
2.6 and later. The ``env`` object is used to look-up the various parameters,
i.e. the above is equivalent to:
.. syntax:: python
@task
def backup():
command = "backup.rb {app_directory} {s3_key}".format(**env)
run(command)
By default, ``format`` is set to ``False`` and the string is run without any
substitution. But if you happen to find formatting as useful a I do, you can
enable it as default by setting:
.. syntax:: python
env.format = True
You can then use it without having to constantly set ``format=True``, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}")
Fabric Contexts
---------------
Deployment setups vary tremendously. I've used Fabric for everything from simple
single-machine deployments to web app deployments across multiple data centers
to even physical multi-touch installations at the `Museum of Australian
Democracy
<http://www.moadoph.gov.au/exhibitions/prime-ministers-of-australia-exhibition/>`_.
-Unfortunately, I've consistently found the ``hosts`` and ``roles`` support
+Unfortunately, I've consistently found the ``@hosts`` and ``@roles`` support
offered by Fabric to be sub-optimal for these dramatically different setups.
And providing an API that covers the various scenarios is hard!
When doing a major upgrade of a web app, you might want to do something like:
* Switch the web servers to show a "planned maintenance" notice.
* Migrate the database to new schemas.
* Upgrade the app servers.
* Update app routing on the configuration servers.
* Enable the web servers to continue serving requests normally.
-And the support for ``hosts`` and ``roles`` that Fabric provides is good enough
-in that context. However,
-
Context Runner
--------------
Parallel Deployment
-------------------
-Like with the ``run`` context runner call, ``multirun`` also accepts a function
-to execute instead of a command string. The utility ``multilocal`` method
-leverages this functionality to run commands locally for each of the hosts in
-parallel, e.g.
+Like with the ``.run()`` context runner call, ``.multirun()`` also accepts a
+function to execute instead of a command string. The utility ``.multilocal()``
+method leverages this functionality to run commands locally for each of the
+hosts in parallel, e.g.
.. syntax:: python
env.format = True
@task
def db_backup():
env('db-servers').multilocal('backup.rb {host}')
-Behind the scenes, ``multirun`` uses ``fork`` and `domain sockets
+Behind the scenes, ``.multirun()`` uses ``fork()`` and `domain sockets
<http://en.wikipedia.org/wiki/Unix_domain_socket>`_, so it'll only work on Unix
platforms. You can specify the maximum number of parallel processes to spawn at
any one time by specifying ``env.multirun_pool_size`` which is set to ``10`` by
default, e.g.
.. syntax:: python
env.multirun_pool_size = 200
-And, oh, there's also a ``multisudo`` for your convenience.
+And, oh, there's also a ``.multisudo()`` for your convenience.
Fabric Shell
------------
Sometimes you just want to run a bunch of commands on a number of different
servers. So I've added a funky new feature -- Fabric shell mode:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqccu/python" title="Fabric Shell"><img
src="http://img.skitch.com/20110212-g8ha9cd5g441m4q3y21gewmnha.png" /></a>
</div>
Once you are in the shell, all of your commands will be sequentially ``run()``
on the respective hosts for your calling context. You can also use the
``.shell-command`` syntax to call shell builtin commands -- including your own
custom ones!
You start shells from within your Fabric commands by invoking the ``.shell()``
method of a context runner. Here's sample code to enable ``fab shell``:
.. syntax:: python
@task('app-servers', run_per_context=False)
def shell():
"""start a shell within the current context"""
env().shell(format=True)
The above defaults to the ``app-servers`` context when you run ``fab shell``,
but you can always override the context from the command line, e.g.
.. syntax:: console
$ fab shell @db-servers
And if your Python has been compiled with `readline support
<http://docs.python.org/library/readline.html>`_, then you can also leverage the
tab-completion support that I've added:
* Terms starting with ``{`` auto-complete on the properties within the ``env``
object to make it easy for you to use the string formatting support.
* Terms starting with ``.`` auto-complete on the available shell builtin
commands.
* All other terms auto-complete on the list of available executables on your
local machine's ``$PATH``.
Other readline features have been enabled too, e.g. command history with up/down
arrows, ``^r`` search and even cross-session history. You can configure where
the history is saved by setting ``env.shell_history_file`` which defaults to:
.. syntax:: python
env.shell_history_file = '~/.fab-shell-history'
Shell Builtins
--------------
As mentioned above, you can call various ``.shell-commands`` from within a
Fabric shell to do something other than ``run()`` a command on the various
hosts, e.g.
.. syntax:: irb
>> .multilocal backup.rb {host_string}
The above will run the equivalent of the following in parallel for each host:
.. syntax:: python
local("backup.rb {host_string}")
The following builtins are currently available:
* ``.cd`` -- changes the working directory for all future commands.
* ``.help`` -- displays a list of the available shell commands.
* ``.info`` -- list the current context and the respective hosts.
* ``.local`` -- runs the command locally.
* ``.multilocal`` -- runs the command in parallel locally for each host.
* ``.multirun`` -- runs the command in parallel on the various hosts.
* ``.multisudo`` -- runs the sudoed command in parallel on the various hosts.
* ``.sudo`` -- runs the sudoed command on the various hosts.
* ``.toggle-format`` -- toggles string formatting support.
You can define your own by using the new ``@shell`` decorator, e.g.
.. syntax:: python
@shell
def python_version(spec, arg):
with hide('running', 'output'):
if arg == 'full':
version = run('python -c "import sys; print sys.version"')
else:
version = run(
"python -c 'import sys; print "
'".".join(map(str, sys.version_info[:3]))\''
)
puts("python %s" % version)
The above can then be called from within a shell, e.g.
.. syntax:: irb
>> .python-version
[dev1.ampify.it] python 2.5.2
[dev3.ampify.it] python 2.7.0
The ``spec`` object is initialised with the various variables that the
``.shell()`` method was originally called with, e.g. ``dir``, ``format``, etc.
All changes made, e.g. ``spec.dir = '/var/ampify'``, are persistent and will
affect all subsequent commands within the shell.
The ``arg`` is a string value of everything following the shell command name,
e.g. for ``.local echo hi``, it will be ``"echo hi"``. The command name is
derived from the function name, but you can provide your own as the first
parameter to the ``@shell`` decorator.
And, finally, you can specify ``single=True`` to the ``@shell`` decorator to
specify that you only want the command to be run a single time and not
repeatedly for every host, e.g.
.. syntax:: python
@shell('hello', single=True)
def demo(spec, arg):
print "Hello", arg.upper()
The above can then be called from within a shell, e.g.
.. syntax:: irb
>> .hello tav
Hello TAV
The ``env.ctx`` is set for even single-mode shell commands, so you can always
take advantage of context runners, e.g.
.. syntax:: python
@shell
def backup(spec, arg):
env().multirun(...)
-Environment Variable Manager
-----------------------------
-
-When calling various command line tools, you often have to mess with environment
-variables like ``$PATH``, ``$NODE_PATH``, ``$PYTHONPATH``, etc. To deal with
-this, Fabric forced you to write things like:
-
-.. syntax:: python
-
- NODE_PATH = "NODE_PATH=$NODE_PATH:%s" % node_libs
- run("%s vows" % NODE_PATH)
- run("%s coffee -c amp.coffee" % NODE_PATH)
-
-Instead you can now do:
-
-.. syntax:: python
-
- with env.NODE_PATH(node_libs):
- run("vows")
- run("coffee -c amp.coffee")
-
-That is, if you call a property on the ``env`` object which is composed of only
-the ``ABCDEFGHIJKLMNOPQRSTUVWXYZ_`` characters, then a `Python Context Manager
-<http://www.python.org/dev/peps/pep-0343/>`_ is generated which will manage the
-use of the environment variables for you.
-
-The manager has the following constructor signature:
-
-.. syntax:: python
-
- manager(value, behaviour='append', sep=os.pathsep, reset=False)
-
-So, if you'd called ``env.PATH(value, behaviour)``, the way the ``value`` is
-treated will depend on the ``behaviour`` parameter which can be one of the
-following:
-
-* ``append`` -- appends value to the current ``$PATH``, i.e.
- ``PATH=$PATH:<value>``
-
-* ``prepend`` -- prepends value to the current ``$PATH``, i.e.
- ``PATH=<value>:$PATH``
-
-* ``replace`` -- ignores ``$PATH`` altogether, i.e. ``PATH=<value>``
-
-The ``sep`` defaults to ``:`` on most platforms and determines how the values
-are concatenated. However, if you call the manager with no arguments at all or
-stringify it, it will return the string which would be used during execution,
-e.g.
-
-.. syntax:: python
-
- print env.NODE_PATH # NODE_PATH=$NODE_PATH:/opt/ampify/libs/node
-
-The various calls can be also nested, e.g.
-
-.. syntax:: python
-
- with env.PATH('/usr/local/bin'):
- with env.PATH('/home/tav/bin'):
- print env.PATH # PATH=$PATH:/usr/local/bin:/home/tav/bin
- with env.PATH('/opt/local/bin', 'replace'):
- with env.PATH('/bin', 'prepend'):
- print env.PATH # PATH=/bin:/opt/local/bin
- print env.PATH # PATH=$PATH:/usr/local/bin
-
-You can specify ``reset=True`` to discard any nested values, e.g.
-
-.. syntax:: python
-
- with env.PATH('/opt/ampify/bin', 'prepend'):
- with env.PATH('/home/tav/bin', reset=True):
- print env.PATH # PATH=$PATH:/home/tav/bin
-
-
Command Line Listing
--------------------
When ``fab`` was run without any arguments, it used to spit out the help message
with the various command line options:
.. syntax:: console
$ fab
Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
Options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
-l, --list print list of possible commands and exit
--shortlist print non-verbose list of possible commands and exit
-d COMMAND, --display=COMMAND
print detailed info about a given command and exit
...
As useful as this was, I figured it'd be more useful to list the various
commands without having to constantly type ``fab --list``. So now when you run
``fab`` without any arguments, it lists the available commands instead, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
You can of course still access the help message by running either ``fab -h`` or
``fab --help``. And you can hide commands from being listed by specifying
``display=None`` with the ``@task`` decorator, e.g.
.. syntax:: python
@task(display=None)
def armageddon():
...
Staged Deployment
-----------------
For most serious deployments, you tend to have distinct environments, e.g.
testing, staging, production, etc. And `existing
<http://blog.jeremi.info/entry/my-git-workflow-to-deploy-an-application-to-appengine>`_
`fabric <http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/>`__
`setups <https://github.com/bueda/ops>`_ tend to have similarly named commands
so you can run things like:
.. syntax:: console
$ fab production deploy
Now, not being a fan of repeatedly adding the same functionality to all my
fabfiles, I've added staged deployment support to Fabric. You can enable it by
specifying an ``env.stages`` list value, e.g.
.. syntax:: python
env.stages = ['staging', 'production']
The first item in the list is taken to be the *default* and overridable commands
of the following structure are automatically generated for each item:
.. syntax:: python
@task(display=None)
def production():
puts("env.stage = production", prefix='system')
env.stage = 'production'
That is, it will update ``env.stage`` with the appropriate value and print out a
message saying so, e.g.
.. syntax:: console
$ fab production check deploy
[system] env.stage = production
...
And if your fab command line call didn't start with one of the stages, it will
automatically run the one for the default stage, e.g.
.. syntax:: console
$ fab check deploy
[system] env.stage = staging
...
For added convenience, the environments are also listed when you run ``fab``
without any arguments, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
Available environments:
staging
production
And, for further flexibility, you can override ``env.stages`` with the
``FAB_STAGES`` environment variable. This takes a comma-separated list of
environment stages and, again, the first is treated as the default, e.g.
.. syntax:: console
$ FAB_STAGES=development,production fab deploy
[system] env.stage = development
...
Hyphenated Commands
-------------------
This is a minor point, but I find hyphens, e.g. ``deploy-ampify``, to be more
aesthetically pleasing than underscores, i.e. ``deploy_ampify``. So Fabric now
displays and supports hyphenated variants of all commands, e.g. for the
following fabfile:
.. syntax:: python
from fabric.api import *
@task
def deploy_ampify():
"""deploy the current version of ampify"""
...
The command listing shows:
.. syntax:: console
$ fab
Available commands:
deploy-ampify deploy the current version of ampify
And you can run the command with:
.. syntax:: console
$ fab deploy-ampify
Command Line Env Flags
----------------------
You can now update the ``env`` object directly from the command line using the
new env flags syntax:
* ``+<key>`` sets the value of the key to ``True``.
* ``+<key>:<value>`` sets the key to the given string value.
So, for the following content in your fabfile:
.. syntax:: python
env.config_file = 'deploy.yaml'
env.debug = False
Running the following will set ``env.config_file`` to the new value:
.. syntax:: console
$ fab <commands> +config_file:alt.yaml
And the following will set ``env.debug`` to ``True``:
.. syntax:: console
$ fab <commands> +debug
The env flags are all set in the order given on the command line and before any
commands are run (including the config file handling if one is specified). And
you can, of course, specify as many env flags as you want.
Optimisations
-------------
It won't make much of a difference, but for my own sanity I've made a bunch of
minor optimisations to Fabric, e.g.
* Removed repeated look-up of attributes within loops.
* Removed repeated local imports within functions.
-* Removed redundant double-wrapping of functions within the ``hosts`` and
- ``roles`` decorators.
+* Removed redundant double-wrapping of functions within the ``@hosts`` and
+ ``@roles`` decorators.
Colors Support
--------------
You can enable the optional colors support by setting ``env.colors``, i.e.
.. syntax:: python
env.colors = True
Here's a screenshot of it in action:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqge6/fabric-shell"><img
src="http://img.skitch.com/20110211-nep3wmpi33qb2c4a13bf7fsgja.png"
alt="Fabric with Colors" /></a>
</div>
You can customise the colors by modifying the ``env.color_settings`` property.
By default it is set to:
.. syntax:: python
env.color_settings = {
'abort': yellow,
'error': yellow,
'finish': cyan,
'host_prefix': green,
'prefix': red,
'prompt': blue,
'task': red,
'warn': yellow
}
You can find the color functions in the ``fabric.colors`` module.
Logging Improvements
--------------------
-The builtin ``puts`` and ``fastprint`` logging functions have also been extended
-with the optional ``format`` parameter and ``env.format`` support similar to the
-``local`` and ``run`` builtins, so that instead of having to do something like:
+The builtin ``puts()`` and ``fastprint()`` logging functions have also been
+extended with the optional ``format`` parameter and ``env.format`` support
+similar to the ``local()`` and ``run()`` builtins, so that instead of having to
+do something like:
.. syntax:: python
@task
def db_migrate():
puts(
"[%s] [database] migrating schemas for %s" %
(env.host_string, env.db_name)
)
You can now just do:
.. syntax:: python
env.format = True
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database')
And it will output something like:
.. syntax:: console
$ fab db-migrate
[somehost.com] [database] migrating schemas for ampify
The second parameter which was previously a boolean-only value that was used to
control whether the host string was printed or not, can now also be a string
value -- in which case the string will be used as the prefix instead of the host
string.
You can still control if a host prefix is *also* printed by using the new
optional ``show_host`` parameter, e.g.
.. syntax:: python
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database', show_host=False)
Will output something like:
.. syntax:: console
$ fab db-migrate
[database] migrating schemas for ampify
And if you'd enabled ``env.colors``, the prefix will be also colored according
to your settings!
Autocompletion
--------------
`Bash completion <http://www.debian-administration.org/articles/316>`_ is one of
those features that really helps you to be more productive. Just include the
following in your ``~/.bashrc`` or equivalent file and you'll be able to use
Fabric's new command completion support:
.. syntax:: bash
_fab_completion() {
COMPREPLY=( $( \
COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \
COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
OPTPARSE_AUTO_COMPLETE=1 $1 ) )
}
complete -o default -F _fab_completion fab
It completes on all available commands and command line options, e.g.
.. syntax:: console
$ fab --dis<tab>
- --disable-known-hosts --display
+ --disable-known-hosts --disable-hooks --display
Also, since Fabric has no way of knowing which `command line env flags`_ and
contexts you might be using, you can specify additional autocompletion items as
an ``env.autocomplete`` list value, e.g.
.. syntax:: python
env.autocomplete = ['+config_file:', '+debug', '@db-servers']
This will then make those values available for you to autocomplete, i.e.
.. syntax:: console
$ fab +<tab>
+config_file: +debug
Backwards Compatibility
-----------------------
All these changes should be fully backwards compatible. That is, unless you
happen to have specified any of the new ``env`` variables like ``env.stages``,
your existing fabfiles should run as they've always done. Do let me know if this
is not the case...
Usage
-----
If you'd like to take advantage of these various changes, the simplest thing to
do is to clone my `pylibs repository <https://github.com/tav/pylibs>`_ and put
it on your ``$PYTHONPATH``, i.e.
.. syntax:: console
$ git clone git://github.com/tav/pylibs.git
$ export PYTHONPATH=$PYTHONPATH:`pwd`/pylibs
Then create a ``fab`` script somewhere on your ``$PATH`` with the following
content:
.. syntax:: python
#! /usr/bin/env python
from fabric.main import main
main()
Make sure the script is executable, i.e.
.. syntax:: console
$ chmod +x fab
And as long as you have Python 2.6+, you should be good to go...
.. class:: intro-box
https://github.com/tav/pylibs/tree/master/fabric
Next Steps
----------
I have been talking to the Fabric maintainers about merging these changes
upstream. And so far they've been quite positive. But, as you can imagine, there
are a number of competing ideas about what is best for Fabric's future.
So if you like these features, then do leave a comment expressing your support.
It'd really help getting these features into the next version of Fabric.
-- Thanks, tav
\ No newline at end of file
|
tav/oldblog
|
1090953ea6b3096477440486ce931a0395dcd3cc
|
Post on why stories like Egypt are good.
|
diff --git a/_layouts/site.genshi b/_layouts/site.genshi
index f5c1fc8..95823ee 100644
--- a/_layouts/site.genshi
+++ b/_layouts/site.genshi
@@ -1,180 +1,180 @@
---
license: Public Domain
---
<!DOCTYPE html>
<html xmlns:py="http://genshi.edgewall.org/">
<head>
<title>${Markup(site_title)}<py:if test="defined('title')"> » ${Markup(title)}</py:if></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
<meta name="tweetmeme-title" content="${Markup(title)}" />
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<meta name="author" content="tav" />
<meta name="description" content="${site_description}" />
<meta name="copyright" content="This work has been placed into the Public Domain." />
<meta name="document-rating" content="general" />
<link rel="icon" type="image/png" href="gfx/aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds.feedburner.com/asktav" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="css/site.css" />
<style type="text/css" media="print">
#ignore-this { display: none; }
</style>
<style type="text/css">
.ascii-art .literal-block {
line-height: 1em !important;
}
.cmd-line {
background-color: #000;
color: #fff;
padding: 5px;
margin-left: 2em;
margin-right: 2em;
}
.cmd-ps1 {
color: #999;
}
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
#site-title { padding-top: 0px; }
</style>
<![endif]-->
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://use.typekit.com/por2lgv.js"></script>
<script>
GOOGLE_ANALYTICS_CODE = "UA-90176-8";
GOOGLE_ANALYTICS_HOST = "tav.epians.com";
DISQUS_FORUM = 'asktav';
PAGE_URI = '${'http://tav.espians.com/' + __name__}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
try{
Typekit.load();
} catch(e) {};
</script>
<script src="js/init.js"></script>
</head>
<body>
<div id="main">
<div id="site-header">
<a href="/" id="site-title" title="Tav's Blog">
Tav's Blog →
</a>
<div id="site-links">
<form id="translation_form"><select id="lang_select" onchange="translate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form>
<a href="/" title="${site_description}">Home</a>
<a href="archive.html" title="Site Index">Archive</a>
<a href="about-tav.html" title="About Tav">About Tav</a>
</div>
<hr class="clear" />
</div>
<div class="article-nav"></div>
<div id="intro">
<div class="center">
<img src="gfx/profile-smoking.jpg" />
</div>
- <p>
+ <h1>
I'm Tav, a 28yr old from London. I enjoy working on large-scale
social, economic and technological systems.
- </p>
+ </h1>
<strong>Follow</strong>
<div class="follow-link">
<a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="gfx/icon.twitter.png" /></a> <a href="http://twitter.com/tav" title="Follow @tav on Twitter">tav</a>
</div>
<div class="follow-link">
<a href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog"><img
src="gfx/icon.rss.png" /></a> <a
href="http://feeds.feedburner.com/asktav" rel="alternate"
type="application/rss+xml" title="Subscribe to Tav's Blog">tav's blog</a>
</div>
<div class="follow-link">
<a href="https://github.com/tav" title="Follow @tav on GitHub"><img src="gfx/icon.github.png" class="absmiddle" /></a> <a href="https://github.com/tav" title="Follow @tav on GitHub">tav</a>
</div>
<br/>
<strong>Contact</strong>
<div class="follow-link">
<a href="mailto:tav@espians.com" title="Email tav@espians.com"><img src="gfx/icon.gmail.png" /></a> <a href="mailto:tav@espians.com" title="Email tav@espians.com">tav@espians.com</a>
</div>
<div class="follow-link">
<a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook"><img src="gfx/icon.facebook.png" /></a> <a href="http://www.facebook.com/asktav" title="Follow @asktav on Facebook">asktav</a>
</div>
<div class="follow-link">
<a href="skype:addname?name=tavespian" title="Contact tavespian on Skype"><img src="gfx/icon.skype.png" /></a> <a href="skype:addname?name=tavespian" title="Contact tavespian on Skype">tavespian</a>
</div>
</div>
<div id="page">
<div>${Markup(content)}</div>
</div>
<hr class="clear" />
<div class="article-nav"></div>
</div>
</body>
</html>
diff --git a/fabric-with-cleaner-api-and-parallel-deployment-support.txt b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
similarity index 92%
rename from fabric-with-cleaner-api-and-parallel-deployment-support.txt
rename to fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
index 2e9cfa9..901a976 100644
--- a/fabric-with-cleaner-api-and-parallel-deployment-support.txt
+++ b/fabric-python-with-cleaner-api-and-parallel-deployment-support.txt
@@ -1,680 +1,715 @@
---
+created: 2011-02-14, 08:54
layout: post
+type: draft
license: Public Domain
---
-=======================================================
-Fabric with Cleaner API and Parallel Deployment Support
-=======================================================
+======================================================
+Fabric Python with Cleaner API and Parallel Deployment
+======================================================
`Fabric <http://fabfile.org/>`_ is an awesome tool. Like `Capistrano
<https://github.com/capistrano/capistrano/wiki/2.x-Getting-Started>`_ and `Vlad
<http://rubyhitsquad.com/Vlad_the_Deployer.html>`_, it makes deployments a lot
simpler than with shell scripts on their own.
.. raw:: html
<div class="float-right-aligned">
<a href="http://www.flickr.com/photos/stars6/4381851322/in/photostream/"><img
src="http://farm3.static.flickr.com/2775/4381851322_d46fd7d75e.jpg"
alt="Datacenter Work" width="400px" height="267px" /></a><br />
<div class="image-caption">
by <a href="http://www.flickr.com/photos/stars6/">stars6</a>
</div>
</div>
However, once the complexity of your setup starts to grow, you very quickly
start wishing for a cleaner and more powerful API.
And once you are deploying to more than 30 servers, you really wish that Fabric
would run commands in parallel instead of doing them sequentially, one after
another.
Having recently experienced this pain, I decided to rework the core of Fabric.
I've documented it below -- describing all the changes to the `current Fabric
1.0a <http://docs.fabfile.org/1.0a/>`_.
.. more
.. class:: intro-box
https://github.com/tav/pylibs/tree/master/fabric
Task Decorator
--------------
Traditionally, *all* functions within your ``fabfile.py`` were implicitly
exposed as Fabric commands. So once you started abstracting your script to be
more manageable, you had to use ``_underscore`` hacks to stop functions being
exposed as commands, e.g.
.. syntax:: python
from support.module import SomeClass as _SomeClass
from urllib import urlencode as _urlencode, urlopen as _urlopen
def _support_function():
...
Not only is this ugly and cumbersome, but it also goes against `The Zen of
Python <http://www.python.org/dev/peps/pep-0020/>`_ philosophy of "explicit is
better than implicit". So I've added a ``@task`` decorator to explicitly mark
functions as Fabric commands, e.g.
.. syntax:: python
from urllib import urlopen
from fabric.api import *
def get_latest_commit():
return urlopen('http://commits.server.com/latest').read()
@task
def check():
"""check if local changes have been committed"""
local_version = local('git rev-parse HEAD')
if local_version != get_latest_commit():
abort("!! Local changes haven't been committed !!")
@task
def deploy():
"""publish the latest version of the app"""
with cd('/var/app'):
run('git remote update')
run('git checkout %s' % get_latest_commit())
sudo("/etc/init.d/apache2 graceful")
The above uses ``@task`` to explicitly mark ``check`` and ``deploy`` as Fabric
commands so that they can be run as usual, i.e. ``fab check`` and ``fab
deploy``. Any functions and classes you import or define don't have to be
"hidden" with the ``_underscore`` hack.
For backwards compatibility, if you never use the ``@task`` decorator, you'll
continue to get the traditional behaviour.
YAML Config
-----------
It's preferable not to hard-code configurable values into fabfiles. This enables
you to reuse the same fabfile across different projects and keep it updated
without having to constantly copy, paste and modify.
So I've added native config support to Fabric. You can enable it by simply
specifying the ``env.config_file`` variable:
.. syntax:: python
env.config_file = 'deploy.yaml'
This will load and parse the specified `YAML file
<http://en.wikipedia.org/wiki/YAML>`_ before running any commands. The
configuration values will then be accessible from ``env.config``. This object is
simply a dictionary with dot-attribute access similar to the ``env`` dictionary.
You can then keep your fabfiles clean from hard-coded values, e.g.
.. syntax:: python
def get_latest_commit():
return urlopen(env.config.commits_server).read()
@task
def deploy():
with cd(env.config.app_directory):
...
Script Execution
----------------
It really helps to be able to quickly iterate the scripts that you will be
calling with Fabric. And whilst you should eventually create them as individual
files and sync them as part of your deployment, it'd be nice if you could try
them out during development.
To help with this I've added a new ``execute`` builtin. This lets you execute
arbitrary scripts on remote hosts, e.g.
.. syntax:: python
@task
def stats():
memusage = execute("""
#! /usr/bin/env python
import psutil
pid = open('pidfile').read()
process = psutil.Process(int(pid))
print process.get_memory_percent()
""", 'memusage.py', verbose=False, dir='/var/ampify')
Behind the scenes, ``execute`` will:
* Strip any common leading whitespace from every line in the source.
* Copy the source into a file on the remote server.
* If the optional ``name`` parameter (the 2nd parameter) had been specified,
then the given name will be used, otherwise an auto-generated name will be
used.
* If the optional ``dir`` parameter was specified, then the file will be created
within the given directory, otherwise it'll be created on the remote ``$HOME``
directory.
* The file will then be made executable, i.e. ``chmod +x``.
* And, finally, it will be run and the response will be returned. Unless the
``verbose`` parameter is set to ``False``, then it will by default also output
the response to the screen.
As you can imagine, ``execute`` makes it very easy to rapidly try out and
develop your development logic. Your scripts can be in whatever languages you
can run on your remote hosts -- Ruby, Perl, Bash, Python, JavaScript, whatever.
Extension Hooks
---------------
I've added native hooks support so that you can extend certain aspects of Fabric
without having to resort to monkey-patching. You attach functions to specific
hooks by using the new ``@hook`` decorator, e.g.
.. syntax:: python
@hook('config.loaded')
def default_config():
if 'port' in env.config:
return
port = prompt("port number?", default=8080, validate=int)
env.config.port = port
For the moment, only the following hooks are defined. It's possible that I may
add support for individual ``<command>.before`` and ``<command>.after`` hooks,
but so far I haven't needed that functionality.
+---------------------+-----------------------------+------------------------+
| Hook Name | Hook Function Signature | Description |
+=====================+=============================+========================+
| ``exec.before`` | ``func(cmds, cmds_to_run)`` | |hook-exec-before| |
+---------------------+-----------------------------+------------------------+
| ``config.loaded`` | ``func()`` | |hook-config-loaded| |
+---------------------+-----------------------------+------------------------+
| ``exec.after`` | ``func()`` | |hook-exec-after| |
+---------------------+-----------------------------+------------------------+
| ``listing.display`` | ``func()`` | |hook-listing-display| |
+---------------------+-----------------------------+------------------------+
.. |hook-config-loaded| replace::
Run after any config file has been parsed and loaded.
.. |hook-exec-after| replace::
Run after all the commands are run.
.. |hook-exec-before| replace::
Run before all the commands are run (including the config handling).
.. |hook-listing-display| replace::
Run when the commands listing has finished running in response to ``fab`` or
``fab --list``. Useful for adding extra info.
Environment Variable Manager
----------------------------
Command Strings & Directories
-----------------------------
Fabric provides a number of builtin functions that let you make command-line
calls:
* ``local`` -- runs a command on the local host.
* ``run`` -- runs a command on a remote host.
* ``sudo`` -- runs a sudoed command on a remote host.
I've added two optional parameters to these. A ``dir`` parameter can be used to
specify the directory from within which the command should be run, e.g.
.. syntax:: python
@task
def restart():
run("amp restart", dir='/opt/ampify')
And a ``format`` parameter can be used to access the new formatted command
strings functionality, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}", format=True)
This makes use of the `Advanced String Formatting
<http://www.python.org/dev/peps/pep-3101/>`_ support that is available in Python
2.6 and later. The ``env`` object is used to look-up the various parameters,
i.e. the above is equivalent to:
.. syntax:: python
@task
def backup():
command = "backup.rb {app_directory} {s3_key}".format(**env)
run(command)
By default, ``format`` is set to ``False`` and the command string is run without
any substitution. But if you happen to find formatting as useful a I do, you can
enable it as default by setting:
.. syntax:: python
env.format = True
You can then use it without having to constantly set ``format=True``, e.g.
.. syntax:: python
@task
def backup():
run("backup.rb {app_directory} {s3_key}")
Fabric Contexts
---------------
Context Runner
--------------
Parallel Deployment
-------------------
Fabric Shell
------------
Shell Builtins
--------------
Command Line Listing
--------------------
When ``fab`` was run without any arguments, it used to spit out the help message
with the various command line options:
.. syntax:: console
$ fab
Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
Options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
-l, --list print list of possible commands and exit
--shortlist print non-verbose list of possible commands and exit
-d COMMAND, --display=COMMAND
print detailed info about a given command and exit
...
As useful as this was, I figured it'd be more useful to list the various
commands without having to constantly type ``fab --list``. So now when you run
``fab`` without any arguments, it lists the available commands instead, e.g.
.. syntax:: console
$ fab
Available commands:
check check if local changes have been committed
deploy publish the latest version of the app
You can of course still access the help message by running either ``fab -h`` or
``fab --help``. And you can hide commands from being listed by specifying
``display=None`` with the ``@task`` decorator, e.g.
.. syntax:: python
@task(display=None)
def armageddon():
...
Staged Deployment
-----------------
For most serious deployments, you tend to have distinct environments, e.g.
testing, staging, production, etc. And `existing
<http://blog.jeremi.info/entry/my-git-workflow-to-deploy-an-application-to-appengine>`_
`fabric <http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/>`__
`setups <https://github.com/bueda/ops>`_ tend to have similarly named commands
so you can run things like:
.. syntax:: console
$ fab production deploy
Now, not being a fan of repeatedly adding the same functionality to all my
fabfiles, I've added staged deployment support to Fabric. You can enable it by
specifying an ``env.stages`` list value, e.g.
.. syntax:: python
env.stages = ['staging', 'production']
The first item in the list is taken to be the *default* and overridable commands
of the following structure are automatically generated for each item:
.. syntax:: python
@task(display=None)
def production():
puts("env.stage = production", prefix='system')
env.stage = 'production'
That is, it will update ``env.stage`` with the appropriate value and print out a
message saying so, e.g.
.. syntax:: console
$ fab production check deploy
[system] env.stage = production
...
And if your fab command-line call didn't start with one of the stages, it will
automatically run the one for the default stage, e.g.
.. syntax:: console
$ fab check deploy
[system] env.stage = staging
...
For added convenience, the environments are also listed when you run ``fab``
without any arguments, e.g.
.. syntax:: console
$ fab
Available commands:
- check check if the blog is up-to-date
- deploy publish the latest version of the blog
+ check check if local changes have been committed
+ deploy publish the latest version of the app
Available environments:
staging
production
And, for further flexibility, you can override ``env.stages`` with the
``FAB_STAGES`` environment variable. This takes a comma-separated list of
environment stages and, again, the first is treated as the default, e.g.
.. syntax:: console
$ FAB_STAGES=development,production fab deploy
[system] env.stage = development
...
Hyphenated Commands
-------------------
This is a minor point, but I find hyphens, e.g. ``deploy-ampify``, to be more
aesthetically pleasing than underscores, i.e. ``deploy_ampify``. So Fabric now
displays and supports hyphenated variants of all commands, e.g. for the
following fabfile:
.. syntax:: python
from fabric.api import *
@task
def deploy_ampify():
"""deploy the current version of ampify"""
...
The command listing shows:
.. syntax:: console
$ fab
Available commands:
deploy-ampify deploy the current version of ampify
And you can run the command with:
.. syntax:: console
$ fab deploy-ampify
Command Line Env Flags
----------------------
You can now update the ``env`` object directly from the command line using the
new env flags syntax:
* ``+<key>`` sets the value of the key to ``True``.
* ``+<key>:<value>`` sets the key to the given string value.
So, for the following content in your fabfile:
.. syntax:: python
env.config_file = 'deploy.yaml'
env.debug = False
Running the following will set ``env.config_file`` to the new value:
.. syntax:: console
$ fab <commands> +config_file:alt.yaml
And the following will set ``env.debug`` to ``True``:
.. syntax:: console
$ fab <commands> +debug
The env flags are all set in the order given on the command line and before any
commands are run (including the config file handling if one is specified). And
you can, of course, specify as many env flags as you want.
Optimisations
-------------
It won't make much of a difference, but for my own sanity I've made a bunch of
minor optimisations to Fabric, e.g.
* Removed repeated look-up of attributes within loops.
* Removed repeated local imports within functions.
* Removed redundant double-wrapping of functions within the ``hosts`` and
``roles`` decorators.
Colors Support
--------------
You can enable the optional colors support by setting ``env.colors``, i.e.
.. syntax:: python
env.colors = True
Here's a screenshot of it in action:
.. raw:: html
<div class="center">
<a href="https://skitch.com/tav./rqge6/fabric-shell"><img
src="http://img.skitch.com/20110211-nep3wmpi33qb2c4a13bf7fsgja.png"
alt="Fabric with Colors" /></a>
</div>
You can customise the colors by modifying the ``env.color_settings`` property.
By default it is set to:
.. syntax:: python
env.color_settings = {
'abort': yellow,
'error': yellow,
'finish': cyan,
'host_prefix': green,
'prefix': red,
'prompt': blue,
'task': red,
'warn': yellow
}
You can find the color functions in the ``fabric.colors`` module.
Logging Improvements
--------------------
-The builtin ``puts`` and ``fastprint`` logging functions have been extended so
-that instead of having to do something like:
+The builtin ``puts`` and ``fastprint`` logging functions have also been extended
+with the optional ``format`` parameter and ``env.format`` support similar to the
+``local`` and ``run`` builtins, so that instead of having to do something like:
.. syntax:: python
@task
def db_migrate():
puts(
"[%s] [database] migrating schemas for %s" %
(env.host_string, env.db_name)
)
You can now just do:
.. syntax:: python
+ env.format = True
+
@task
def db_migrate():
puts("migrating schemas for {db_name}", 'database')
+And it will output something like:
+
+.. syntax:: console
+
+ $ fab db-migrate
+ [somehost.com] [database] migrating schemas for ampify
+
+The second parameter which was previously a boolean-only value that was used to
+control whether the host string was printed or not, can now also be a string
+value -- in which case the string will be used as the prefix instead of the host
+string.
+
+You can still control if a host prefix is *also* printed by using the new
+optional ``show_host`` parameter, e.g.
+
+.. syntax:: python
+
+ @task
+ def db_migrate():
+ puts("migrating schemas for {db_name}", 'database', show_host=False)
+
+Will output something like:
+
+.. syntax:: console
+
+ $ fab db-migrate
+ [database] migrating schemas for ampify
+
+And if you'd enabled ``env.colors``, the prefix will be also colored according
+to your settings!
Autocompletion
--------------
`Bash completion <http://www.debian-administration.org/articles/316>`_ is one of
those features that really helps you to be more productive. Just include the
following in your ``~/.bashrc`` or equivalent file and you'll be able to use
Fabric's new command completion support:
.. syntax:: bash
_fab_completion() {
COMPREPLY=( $( \
COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \
COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
OPTPARSE_AUTO_COMPLETE=1 $1 ) )
}
complete -o default -F _fab_completion fab
It completes on all available commands and command line options, e.g.
.. syntax:: console
$ fab --dis<tab>
--disable-known-hosts --display
Also, since Fabric has no way of knowing which `command line env flags`_ you
might be using, you can specify additional autocompletion items as an
``env.autocomplete`` list value, e.g.
.. syntax:: python
env.autocomplete = ['+config_file:', '+debug']
This will then make those values available for you to autocomplete, i.e.
.. syntax:: console
$ fab +<tab>
+config_file: +debug
Backwards Compatibility
-----------------------
All these changes should be fully backwards compatible. That is, unless you
happen to have specified any of the new ``env`` variables like ``env.stages``,
your existing fabfiles should run as they've always done. Do let me know if this
is not the case...
-.. class:: intro-box
-
-https://github.com/tav/pylibs/tree/master/fabric
-
Usage
-----
If you'd like to take advantage of these various changes, the simplest thing to
do is to clone my `pylibs repository <https://github.com/tav/pylibs>`_ and put
it on your ``$PYTHONPATH``, i.e.
.. syntax:: console
$ git clone git://github.com/tav/pylibs.git
$ export PYTHONPATH=$PYTHONPATH:`pwd`/pylibs
Then create a ``fab`` script somewhere on your ``$PATH`` with the following
content:
.. syntax:: python
#! /usr/bin/env python
from fabric.main import main
main()
Make sure to make the script executable, i.e.
.. syntax:: console
$ chmod +x fab
And as long as you have Python 2.6+, you should be good to go...
+.. class:: intro-box
+
+https://github.com/tav/pylibs/tree/master/fabric
+
Next Steps
----------
I have been talking to the Fabric maintainers about merging these changes
upstream. And so far they've been quite positive. But, as you can imagine, there
are a number of competing ideas about what is best for Fabric's future.
So if you like these features, then do leave a comment expressing your support.
It'd really help getting these features into the next version of Fabric.
-- Thanks, tav
\ No newline at end of file
diff --git a/website/css/site.css b/website/css/site.css
index 7efcf66..5489f3d 100644
--- a/website/css/site.css
+++ b/website/css/site.css
@@ -1,625 +1,632 @@
/*
* aaken default stylesheet -- by tav
*
*/
a {
color: #0000dd;
text-decoration: underline;
}
a:hover, a:active {
text-decoration: none;
}
a.no-underline {
text-decoration: none;
}
a.no-underline:hover {
text-decoration: underline;
}
body {
background-color: #3e3935;
background-image: url("../gfx/bg.jpg");
font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
font-size: 18px;
margin: 0;
padding: 0;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-weight: normal !important;
clear: both;
font-size: 36px;
margin: 0;
}
h1 {
font-size: 30px;
margin: 18px 0 14px 0;
}
pre {
background-color: #fefef1;
border: 1px solid #f7a600;
border-left: 5px solid #f7a600;
color: #101010;
font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
overflow: hidden;
padding: 12px 15px 13px 12px;
margin: 20px 30px 0 20px;
-webkit-border-bottom-right-radius: 12px;
-moz-border-radius-bottomright: 12px;
border-bottom-right-radius: 12px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
}
pre:hover {
overflow: auto;
}
pre.ascii-art {
line-height: 1em;
}
pre code {
background-color: transparent;
border: 0;
padding: 0;
border: 1px solid #c00;
}
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
strong {
font-family: "museo-1", "museo-2", Verdana, Arial, sans-serif;
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 1.4em;
font-weight: normal;
}
sup {
display: none;
}
li ul {
margin-top: 10px;
}
/* sections */
.content {
clear: both;
line-height: 1.5em;
margin-bottom: 1em;
}
#intro {
background: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
float: right;
padding: 5px 10px 10px 10px;
width: 200px;
line-height: 1.5em;
}
+#intro h1 {
+ font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
+ font-size: 18px;
+ line-height: 27px;
+ margin: 18px 0 24px 0;
+}
+
#main {
margin: 0px auto;
text-align: left;
width: 944px;
}
#page {
background: #fff;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
float: left;
width: 640px;
padding-left: 30px;
padding-right: 35px;
padding-top: 15px;
padding-bottom: 10px;
margin-bottom: 14px;
margin-right: 10px;
}
#site-header {
margin: 12px 0 14px 0;
text-align: right;
}
#site-title {
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border: 1px solid #fff;
color: #000;
font-family: "zalamander-caps-1","zalamander-caps-2", "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 3em;
float: left;
padding: 9px 15px 0px 15px;
text-decoration: none;
}
#site-title:hover {
border: 1px solid #000;
}
.wf-inactive #site-title {
padding-top: 0px;
padding-bottom: 8px;
}
#site-links {
padding-top: 4px;
}
#site-links a {
margin-left: 8px;
padding: 4px 6px;
text-decoration: none;
color: #fff;
font-size: 20px;
}
#site-links a:hover {
color: #000;
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#translation_form {
display: inline;
margin-right: 20px;
}
.follow-link {
margin: 12px 0 8px 16px;
}
/* disqus */
#dsq-global-toolbar, #dsq-sort-by, #dsq-like-tooltip {
display: none;
}
#dsq-subscribe, #dsq-footer, .dsq-item-trackback, #dsq-account-dropdown {
display: none;
}
#dsq-content h3 {
margin: 25px 0 25px 0 !important;
}
.dsq-comment-header a {
color: #2d2827;
}
/* rst classes */
.docinfo {
margin-left: 5px;
margin-top: 20px;
}
.abstract {
margin-top: 20px;
}
code, .literal {
background-color: #fefbf6;
border: 1px solid #dbd0be;
padding: 2px 4px;
font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
}
.topic-title {
font-weight: bold;
text-align: center;
}
.note {
color: #aaa;
margin-left: 10px;
font-style: italic;
}
.attention {
background-color: #FFC3C3;
padding: 1.5em;
margin-top: 1em;
margin-bottom: 1em;
text-align: center;
}
.admonition-title {
display: none
}
.highlight {
text-align: center;
border: 1px solid #c00;
background-color: #fff;
background-color: #c00;
color: #fff;
padding: 5px;
}
/* rst error */
.system-messages {
display: none;
}
/* toc */
.contents {
padding-left: 3em;
margin: 10px;
display: none;
}
.contents.toc-only {
display: block;
padding-left: 0;
margin: 0;
}
.contents.toc-only .topic-title {
display: none;
}
/* links */
a.fn-backref {
text-decoration: none;
}
a.footnote-reference {
vertical-align: super;
text-decoration: none;
}
/* tables */
table.docutils {
margin: 20px 30px 0 20px;
border-spacing: 0px;
}
table.docutils thead tr th {
background: #635b54;
color: #fff;
padding: 7px 10px;
font-weight: normal;
}
table.docutils td {
padding: 7px;
border-bottom: 1px dashed #d6d2cf;
}
table.docutils td .literal {
white-space: nowrap;
}
table.docutils thead tr th:first-child {
text-align: right;
}
table.docutils tr td:first-child {
text-align: right;
}
table.footnote, table.citation {
border: 0px;
padding: 5px;
margin: 5px;
}
table.citation td, table.footnote td {
border: 0px;
}
table.docutils td p, table.footnote td p, table.citation td p {
margin-top: 0px;
padding-top: 0px;
}
table.footnote td.label, table.citation td.label {
width: 12em;
padding-right: 10px;
text-align: right;
}
table.citation td.label a, table.footnote td.label a {
font-style: italic;
text-decoration: none;
color: #333;
}
p.caption {
color: #666;
font-style: italic;
margin-top: 5px;
padding-left: 5px;
text-align: center;
}
td p.first {
margin-top: 0;
}
td p.last {
margin-bottom: 0;
}
th.field-name, th.docinfo-name {
text-align: right;
padding-right: 5px;
white-space: nowrap;
}
table.field-list {
border: 0px;
}
table.field-list td {
border: 0px;
vertical-align: top;
padding: 1px;
}
/* doctest */
.doctest-output {
color: #a5504d;
}
.doctest-input {
color: #0d5d04;
}
.doctest-output {
color: #a5504d;
color: #c32528;
color: #bf5036;
}
.doctest-input {
color: #5d90cd;
color: #6a6a6a;
color: #0d5d04;
color: #27894f;
color: #00a33f;
color: #15973b;
color: #7f9a49;
color: #005d61;
color: #1d6c70;
color: #326008;
}
/* images */
img {
border: none;
vertical-align: top;
margin: 0;
padding: 0;
}
img.absmiddle {
vertical-align: middle;
}
/* lines */
hr {
noshade: noshade;
clear: both;
}
hr.clear {
clear: both;
height: 0;
width: 0;
margin: 0;
padding: 0;
color: #c00;
background-color: transparent;
border: 0px solid;
}
/* lists */
li {
margin-bottom: 10px;
}
/* utility classes */
.center {
text-align: center;
margin-top: 5px;
margin-bottom: 5px;
}
.hide {
display: none;
}
.image-caption {
font-style: italic;
text-align: right;
}
.float-left, .figure {
float: left;
padding: 5px;
margin-right: 12px;
border: 1px solid #ded0e8;
}
.figure {
width: 400px;
text-align: center;
}
.float-left-aligned {
float: left;
margin: 5px 12px 5px -30px;
}
.float-left-aligned .image-caption {
padding-top: 5px;
}
.float-right, .float-right-aligned {
float: right;
margin-left: 12px;
margin-bottom: 5px;
}
.float-right-aligned {
margin-right: -35px;
}
.float-right-aligned .image-caption {
padding-right: 5px;
}
.full-width, .full-width-lined {
clear: both;
margin-left: -30px;
margin-right: -35px;
}
.full-width pre {
margin: 0;
border-left: 0px;
border-right: 0px;
padding: 30px 35px 31px 30px;
-webkit-border-bottom-right-radius: 0px;
-moz-border-radius-bottomright: 0px;
border-bottom-right-radius: 0px;
-webkit-box-shadow: 0px 0px 0px transparent;
}
.full-width-lined {
border-bottom: 1px solid #cacaca;
border-top: 1px solid #cacaca;
margin-bottom: 20px;
margin-top: 20px;
}
.boxed {
border: 1px solid #cacaca;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
margin-top: 10px;
}
/* special */
h1.title {
display: none;
}
#abstract .topic-title {
display: none;
}
#table-of-contents .topic-title {
display: none;
}
.sidebox, .sidebox-grey {
padding: 17px 30px 17px 20px;
max-width: 180px;
float: right;
margin: 8px -35px 5px 10px;
}
.sidebox {
background-color: #dee;
border-right: 10px solid #488;
}
.sidebox-grey {
background-color: #eee;
border-right: 10px solid #888;
}
.intro-box {
clear: both;
width: 630px;
margin: 21px -35px 0 -30px;
background: #d6d2cf;
border-left: 10px solid #635b54;
padding: 15px 45px 16px 20px;
}
.intro-box a {
color: #635b54;
text-decoration: none;
background: url("../gfx/icon.link.gif") center right no-repeat;
padding-right: 17px;
margin-right: 3px;
}
.intro-box a:hover {
text-decoration: underline;
}
.double-column {
column-count: 2;
column-gap: 1.5em;
}
p.first {
display: inline;
}
/* document specific rules */
div#rationale a.external {
color: #888;
}
#ignore-this {
display: none;
}
.post-title {
clear: both;
margin-top: 1em;
margin-bottom: 2em;
border-top: 1px dashed #444;
padding-top: 1.4em;
line-height: 36px;
}
.post-link a {
color: #000;
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 36px;
font-weight: normal;
line-height: 36px;
diff --git a/why-stories-like-egypt-are-fit-for-hacker-news.txt b/why-stories-like-egypt-are-fit-for-hacker-news.txt
new file mode 100644
index 0000000..7f43408
--- /dev/null
+++ b/why-stories-like-egypt-are-fit-for-hacker-news.txt
@@ -0,0 +1,60 @@
+---
+created: 2011-02-11, 18:55
+layout: post
+license: Public Domain
+---
+
+==============================================
+Why Stories Like Egypt Are Fit For Hacker News
+==============================================
+
+Every time a story like Egypt appears on `Hacker News
+<http://news.ycombinator.com>`_, some people inevitably comment that it's
+unsuitable for HN. As much as the attempted curation is appreciated, it is these
+comments that are often off topic.
+
+.. raw:: html
+
+ <div class="float-right-aligned">
+ <a href="https://img.skitch.com/20110211-csp26cs7qpin4xejqpxn7t5hia.jpg"
+ title="Egypt Tahrir Square 2011"><img
+ src="https://img.skitch.com/20110211-1yfkkic75xd6ua7s7mj47cmwbi.jpg"
+ /></a>
+ <div class="image-caption">
+ by <a href="http://blogs.aljazeera.net/">Al Jazeera</a>
+ </div>
+ </div>
+
+ <style type="text/css">
+ .content ul {
+ padding-left: 20px;
+ padding-right: 0;
+ margin-left: 0;
+ margin-right: 0;
+ }
+ </style>
+
+If anything, stories like Egypt are well-suited given that:
+
+* It's historic! Just look at the picture to the right! If something truly
+ momentous is happening, then I'd like to see discussion about it on HN -- it
+ tends to be well-informed.
+
+* The `Hacker News Guidelines <http://ycombinator.com/newsguidelines.html>`_
+ explicitly allows for political stories that demonstrate "evidence of some
+ interesting new phenomenon".
+
+* It's arguably more worthy of discussion than the majority of the `Techcrunch
+ posts
+ <http://searchyc.com/submissions/techcrunch.com?only=domain&sort=by_date>`_
+ that we see on HN.
+
+* It's an entrepreneurial opportunity! With a GDP of nearly $500bn, Egypt just
+ became a lot more attractive for innovative startups.
+
+The occasional non-tech/startup post doesn't mean that Hacker News is going to
+the shits. We are not in danger of becoming Reddit 2.0 anytime soon either. So,
+please, can we reserve the comments about off-topic posts to the kind of posts
+that truly are off-topic?
+
+-- Cheers, tav
\ No newline at end of file
|
tav/oldblog
|
76b8d7f9ac08884c482bd8481378ab61f4f7396c
|
Early draft of the fabric post.
|
diff --git a/_layouts/post.genshi b/_layouts/post.genshi
index 729375b..8c3b200 100644
--- a/_layouts/post.genshi
+++ b/_layouts/post.genshi
@@ -1,80 +1,80 @@
---
layout: site
license: Public Domain
---
<div xmlns:py="http://genshi.edgewall.org/">
<?python
from time import time
from operator import lt
from posixpath import splitext
from urllib import quote_plus, urlencode
def unescape(s):
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("&", "&")
return s
page_url = disqus_url = 'http://tav.espians.com/' + __name__
if defined('created') and lt(created[:7], "2009-07"):
disqus_url = 'http://www.asktav.com/' + __name__
MONTHS = [
'Zero Month',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
?>
<div class="article-title">
<div class="post-link"><a href="${__name__}">${Markup(title)}</a></div>
<div class="additional-content-info">
<a href="#disqus_thread" rel="disqus:${disqus_url}">Add a Comment</a>
<script type="text/javascript">
tweetmeme_url = '${page_url}';
tweetmeme_source = 'tav';
tweetmeme_service = 'bit.ly';
tweetmeme_style = 'compact';
</script>
·
<div class="retweetbutton">
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
</div>
<div class="article-info">
» by <a href="http://tav.espians.com">tav</a><span py:if="defined('created')"> on <span class="post-date">${MONTHS[int(created[5:7])]} ${int(created[8:10])}, ${created[:4]} @ <a href="http://github.com/tav/blog/commits/master/${splitext(__name__)[0]}.txt">${created[-5:]}</a></span></span> <a href="http://creativecommons.org/publicdomain/zero/1.0/" title="Public Domain"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Cc-pd.svg/64px-Cc-pd.svg.png" width="20px" height="20px" alt="Public Domain" class="absmiddle" /></a>
</div>
</div>
-<div py:if="not defined('created')" class="attention">
+<!--<div py:if="not defined('created')" class="attention">
This is an early draft. Many sections are incomplete. A lot more is being written.
-</div>
+</div>-->
<div class="content">
<div py:content="Markup(content)"></div>
</div>
<hr class="clear" />
<div class="share">
If you found this post useful, then please<br />
<a href="http://www.facebook.com/sharer.php?t=${quote_plus(unescape(title))}&${urlencode({'u': page_url})}" title="Share on Facebook" class="fb-share">share on Facebook</a>
<a href="http://twitter.com/share?text=RT+%40tav+${quote_plus(unescape(title))}&${urlencode({'url': page_url})}" title="Retweet" class="twitter-share">or Tweet</a>
</div>
<hr class="clear" />
<br />
<script type="text/javascript">
ARTICLE_NAME = '${__name__}';
</script>
<script type="text/javascript" src="index.js?${int(time()/4)}" />
<div id="disqus-comments-section">
<script type="text/javascript">
disqus_url = "${disqus_url}";
disqus_title = "${Markup(title)}";
</script>
<div id="disqus_thread"></div><script type="text/javascript"
src="http://disqus.com/forums/${site_nick}/embed.js"></script><noscript><a
href="http://${site_nick}.disqus.com/?${urlencode({'url': disqus_url})}">View the forum
thread.</a></noscript>
</div>
</div>
diff --git a/fabric-with-cleaner-api-and-parallel-deployment-support.txt b/fabric-with-cleaner-api-and-parallel-deployment-support.txt
new file mode 100644
index 0000000..2e9cfa9
--- /dev/null
+++ b/fabric-with-cleaner-api-and-parallel-deployment-support.txt
@@ -0,0 +1,680 @@
+---
+layout: post
+license: Public Domain
+---
+
+=======================================================
+Fabric with Cleaner API and Parallel Deployment Support
+=======================================================
+
+`Fabric <http://fabfile.org/>`_ is an awesome tool. Like `Capistrano
+<https://github.com/capistrano/capistrano/wiki/2.x-Getting-Started>`_ and `Vlad
+<http://rubyhitsquad.com/Vlad_the_Deployer.html>`_, it makes deployments a lot
+simpler than with shell scripts on their own.
+
+.. raw:: html
+
+ <div class="float-right-aligned">
+ <a href="http://www.flickr.com/photos/stars6/4381851322/in/photostream/"><img
+ src="http://farm3.static.flickr.com/2775/4381851322_d46fd7d75e.jpg"
+ alt="Datacenter Work" width="400px" height="267px" /></a><br />
+ <div class="image-caption">
+ by <a href="http://www.flickr.com/photos/stars6/">stars6</a>
+ </div>
+ </div>
+
+However, once the complexity of your setup starts to grow, you very quickly
+start wishing for a cleaner and more powerful API.
+
+And once you are deploying to more than 30 servers, you really wish that Fabric
+would run commands in parallel instead of doing them sequentially, one after
+another.
+
+Having recently experienced this pain, I decided to rework the core of Fabric.
+I've documented it below -- describing all the changes to the `current Fabric
+1.0a <http://docs.fabfile.org/1.0a/>`_.
+
+.. more
+
+.. class:: intro-box
+
+https://github.com/tav/pylibs/tree/master/fabric
+
+
+Task Decorator
+--------------
+
+Traditionally, *all* functions within your ``fabfile.py`` were implicitly
+exposed as Fabric commands. So once you started abstracting your script to be
+more manageable, you had to use ``_underscore`` hacks to stop functions being
+exposed as commands, e.g.
+
+.. syntax:: python
+
+ from support.module import SomeClass as _SomeClass
+ from urllib import urlencode as _urlencode, urlopen as _urlopen
+
+ def _support_function():
+ ...
+
+Not only is this ugly and cumbersome, but it also goes against `The Zen of
+Python <http://www.python.org/dev/peps/pep-0020/>`_ philosophy of "explicit is
+better than implicit". So I've added a ``@task`` decorator to explicitly mark
+functions as Fabric commands, e.g.
+
+.. syntax:: python
+
+ from urllib import urlopen
+ from fabric.api import *
+
+
+ def get_latest_commit():
+ return urlopen('http://commits.server.com/latest').read()
+
+
+ @task
+ def check():
+ """check if local changes have been committed"""
+
+ local_version = local('git rev-parse HEAD')
+
+ if local_version != get_latest_commit():
+ abort("!! Local changes haven't been committed !!")
+
+
+ @task
+ def deploy():
+ """publish the latest version of the app"""
+
+ with cd('/var/app'):
+ run('git remote update')
+ run('git checkout %s' % get_latest_commit())
+
+ sudo("/etc/init.d/apache2 graceful")
+
+The above uses ``@task`` to explicitly mark ``check`` and ``deploy`` as Fabric
+commands so that they can be run as usual, i.e. ``fab check`` and ``fab
+deploy``. Any functions and classes you import or define don't have to be
+"hidden" with the ``_underscore`` hack.
+
+For backwards compatibility, if you never use the ``@task`` decorator, you'll
+continue to get the traditional behaviour.
+
+
+YAML Config
+-----------
+
+It's preferable not to hard-code configurable values into fabfiles. This enables
+you to reuse the same fabfile across different projects and keep it updated
+without having to constantly copy, paste and modify.
+
+So I've added native config support to Fabric. You can enable it by simply
+specifying the ``env.config_file`` variable:
+
+.. syntax:: python
+
+ env.config_file = 'deploy.yaml'
+
+This will load and parse the specified `YAML file
+<http://en.wikipedia.org/wiki/YAML>`_ before running any commands. The
+configuration values will then be accessible from ``env.config``. This object is
+simply a dictionary with dot-attribute access similar to the ``env`` dictionary.
+
+You can then keep your fabfiles clean from hard-coded values, e.g.
+
+.. syntax:: python
+
+ def get_latest_commit():
+ return urlopen(env.config.commits_server).read()
+
+
+ @task
+ def deploy():
+ with cd(env.config.app_directory):
+ ...
+
+
+Script Execution
+----------------
+
+It really helps to be able to quickly iterate the scripts that you will be
+calling with Fabric. And whilst you should eventually create them as individual
+files and sync them as part of your deployment, it'd be nice if you could try
+them out during development.
+
+To help with this I've added a new ``execute`` builtin. This lets you execute
+arbitrary scripts on remote hosts, e.g.
+
+.. syntax:: python
+
+ @task
+ def stats():
+
+ memusage = execute("""
+
+ #! /usr/bin/env python
+ import psutil
+
+ pid = open('pidfile').read()
+ process = psutil.Process(int(pid))
+ print process.get_memory_percent()
+
+ """, 'memusage.py', verbose=False, dir='/var/ampify')
+
+Behind the scenes, ``execute`` will:
+
+* Strip any common leading whitespace from every line in the source.
+
+* Copy the source into a file on the remote server.
+
+* If the optional ``name`` parameter (the 2nd parameter) had been specified,
+ then the given name will be used, otherwise an auto-generated name will be
+ used.
+
+* If the optional ``dir`` parameter was specified, then the file will be created
+ within the given directory, otherwise it'll be created on the remote ``$HOME``
+ directory.
+
+* The file will then be made executable, i.e. ``chmod +x``.
+
+* And, finally, it will be run and the response will be returned. Unless the
+ ``verbose`` parameter is set to ``False``, then it will by default also output
+ the response to the screen.
+
+As you can imagine, ``execute`` makes it very easy to rapidly try out and
+develop your development logic. Your scripts can be in whatever languages you
+can run on your remote hosts -- Ruby, Perl, Bash, Python, JavaScript, whatever.
+
+
+Extension Hooks
+---------------
+
+I've added native hooks support so that you can extend certain aspects of Fabric
+without having to resort to monkey-patching. You attach functions to specific
+hooks by using the new ``@hook`` decorator, e.g.
+
+.. syntax:: python
+
+ @hook('config.loaded')
+ def default_config():
+
+ if 'port' in env.config:
+ return
+
+ port = prompt("port number?", default=8080, validate=int)
+ env.config.port = port
+
+For the moment, only the following hooks are defined. It's possible that I may
+add support for individual ``<command>.before`` and ``<command>.after`` hooks,
+but so far I haven't needed that functionality.
+
++---------------------+-----------------------------+------------------------+
+| Hook Name | Hook Function Signature | Description |
++=====================+=============================+========================+
+| ``exec.before`` | ``func(cmds, cmds_to_run)`` | |hook-exec-before| |
++---------------------+-----------------------------+------------------------+
+| ``config.loaded`` | ``func()`` | |hook-config-loaded| |
++---------------------+-----------------------------+------------------------+
+| ``exec.after`` | ``func()`` | |hook-exec-after| |
++---------------------+-----------------------------+------------------------+
+| ``listing.display`` | ``func()`` | |hook-listing-display| |
++---------------------+-----------------------------+------------------------+
+
+.. |hook-config-loaded| replace::
+
+ Run after any config file has been parsed and loaded.
+
+.. |hook-exec-after| replace::
+
+ Run after all the commands are run.
+
+.. |hook-exec-before| replace::
+
+ Run before all the commands are run (including the config handling).
+
+.. |hook-listing-display| replace::
+
+ Run when the commands listing has finished running in response to ``fab`` or
+ ``fab --list``. Useful for adding extra info.
+
+
+Environment Variable Manager
+----------------------------
+
+Command Strings & Directories
+-----------------------------
+
+Fabric provides a number of builtin functions that let you make command-line
+calls:
+
+* ``local`` -- runs a command on the local host.
+
+* ``run`` -- runs a command on a remote host.
+
+* ``sudo`` -- runs a sudoed command on a remote host.
+
+I've added two optional parameters to these. A ``dir`` parameter can be used to
+specify the directory from within which the command should be run, e.g.
+
+.. syntax:: python
+
+ @task
+ def restart():
+ run("amp restart", dir='/opt/ampify')
+
+And a ``format`` parameter can be used to access the new formatted command
+strings functionality, e.g.
+
+.. syntax:: python
+
+ @task
+ def backup():
+ run("backup.rb {app_directory} {s3_key}", format=True)
+
+This makes use of the `Advanced String Formatting
+<http://www.python.org/dev/peps/pep-3101/>`_ support that is available in Python
+2.6 and later. The ``env`` object is used to look-up the various parameters,
+i.e. the above is equivalent to:
+
+.. syntax:: python
+
+ @task
+ def backup():
+ command = "backup.rb {app_directory} {s3_key}".format(**env)
+ run(command)
+
+By default, ``format`` is set to ``False`` and the command string is run without
+any substitution. But if you happen to find formatting as useful a I do, you can
+enable it as default by setting:
+
+.. syntax:: python
+
+ env.format = True
+
+You can then use it without having to constantly set ``format=True``, e.g.
+
+.. syntax:: python
+
+ @task
+ def backup():
+ run("backup.rb {app_directory} {s3_key}")
+
+
+Fabric Contexts
+---------------
+
+Context Runner
+--------------
+
+Parallel Deployment
+-------------------
+
+Fabric Shell
+------------
+
+Shell Builtins
+--------------
+
+Command Line Listing
+--------------------
+
+When ``fab`` was run without any arguments, it used to spit out the help message
+with the various command line options:
+
+.. syntax:: console
+
+ $ fab
+ Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
+
+ Options:
+ -h, --help show this help message and exit
+ -V, --version show program's version number and exit
+ -l, --list print list of possible commands and exit
+ --shortlist print non-verbose list of possible commands and exit
+ -d COMMAND, --display=COMMAND
+ print detailed info about a given command and exit
+ ...
+
+As useful as this was, I figured it'd be more useful to list the various
+commands without having to constantly type ``fab --list``. So now when you run
+``fab`` without any arguments, it lists the available commands instead, e.g.
+
+.. syntax:: console
+
+ $ fab
+ Available commands:
+
+ check check if local changes have been committed
+ deploy publish the latest version of the app
+
+You can of course still access the help message by running either ``fab -h`` or
+``fab --help``. And you can hide commands from being listed by specifying
+``display=None`` with the ``@task`` decorator, e.g.
+
+.. syntax:: python
+
+ @task(display=None)
+ def armageddon():
+ ...
+
+
+Staged Deployment
+-----------------
+
+For most serious deployments, you tend to have distinct environments, e.g.
+testing, staging, production, etc. And `existing
+<http://blog.jeremi.info/entry/my-git-workflow-to-deploy-an-application-to-appengine>`_
+`fabric <http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/>`__
+`setups <https://github.com/bueda/ops>`_ tend to have similarly named commands
+so you can run things like:
+
+.. syntax:: console
+
+ $ fab production deploy
+
+Now, not being a fan of repeatedly adding the same functionality to all my
+fabfiles, I've added staged deployment support to Fabric. You can enable it by
+specifying an ``env.stages`` list value, e.g.
+
+.. syntax:: python
+
+ env.stages = ['staging', 'production']
+
+The first item in the list is taken to be the *default* and overridable commands
+of the following structure are automatically generated for each item:
+
+.. syntax:: python
+
+ @task(display=None)
+ def production():
+ puts("env.stage = production", prefix='system')
+ env.stage = 'production'
+
+That is, it will update ``env.stage`` with the appropriate value and print out a
+message saying so, e.g.
+
+.. syntax:: console
+
+ $ fab production check deploy
+ [system] env.stage = production
+ ...
+
+And if your fab command-line call didn't start with one of the stages, it will
+automatically run the one for the default stage, e.g.
+
+.. syntax:: console
+
+ $ fab check deploy
+ [system] env.stage = staging
+ ...
+
+For added convenience, the environments are also listed when you run ``fab``
+without any arguments, e.g.
+
+.. syntax:: console
+
+ $ fab
+ Available commands:
+
+ check check if the blog is up-to-date
+ deploy publish the latest version of the blog
+
+ Available environments:
+
+ staging
+ production
+
+And, for further flexibility, you can override ``env.stages`` with the
+``FAB_STAGES`` environment variable. This takes a comma-separated list of
+environment stages and, again, the first is treated as the default, e.g.
+
+.. syntax:: console
+
+ $ FAB_STAGES=development,production fab deploy
+ [system] env.stage = development
+ ...
+
+
+Hyphenated Commands
+-------------------
+
+This is a minor point, but I find hyphens, e.g. ``deploy-ampify``, to be more
+aesthetically pleasing than underscores, i.e. ``deploy_ampify``. So Fabric now
+displays and supports hyphenated variants of all commands, e.g. for the
+following fabfile:
+
+.. syntax:: python
+
+ from fabric.api import *
+
+ @task
+ def deploy_ampify():
+ """deploy the current version of ampify"""
+ ...
+
+The command listing shows:
+
+.. syntax:: console
+
+ $ fab
+ Available commands:
+
+ deploy-ampify deploy the current version of ampify
+
+And you can run the command with:
+
+.. syntax:: console
+
+ $ fab deploy-ampify
+
+
+Command Line Env Flags
+----------------------
+
+You can now update the ``env`` object directly from the command line using the
+new env flags syntax:
+
+* ``+<key>`` sets the value of the key to ``True``.
+
+* ``+<key>:<value>`` sets the key to the given string value.
+
+So, for the following content in your fabfile:
+
+.. syntax:: python
+
+ env.config_file = 'deploy.yaml'
+ env.debug = False
+
+Running the following will set ``env.config_file`` to the new value:
+
+.. syntax:: console
+
+ $ fab <commands> +config_file:alt.yaml
+
+And the following will set ``env.debug`` to ``True``:
+
+.. syntax:: console
+
+ $ fab <commands> +debug
+
+The env flags are all set in the order given on the command line and before any
+commands are run (including the config file handling if one is specified). And
+you can, of course, specify as many env flags as you want.
+
+
+Optimisations
+-------------
+
+It won't make much of a difference, but for my own sanity I've made a bunch of
+minor optimisations to Fabric, e.g.
+
+* Removed repeated look-up of attributes within loops.
+
+* Removed repeated local imports within functions.
+
+* Removed redundant double-wrapping of functions within the ``hosts`` and
+ ``roles`` decorators.
+
+
+Colors Support
+--------------
+
+You can enable the optional colors support by setting ``env.colors``, i.e.
+
+.. syntax:: python
+
+ env.colors = True
+
+Here's a screenshot of it in action:
+
+.. raw:: html
+
+ <div class="center">
+ <a href="https://skitch.com/tav./rqge6/fabric-shell"><img
+ src="http://img.skitch.com/20110211-nep3wmpi33qb2c4a13bf7fsgja.png"
+ alt="Fabric with Colors" /></a>
+ </div>
+
+You can customise the colors by modifying the ``env.color_settings`` property.
+By default it is set to:
+
+.. syntax:: python
+
+ env.color_settings = {
+ 'abort': yellow,
+ 'error': yellow,
+ 'finish': cyan,
+ 'host_prefix': green,
+ 'prefix': red,
+ 'prompt': blue,
+ 'task': red,
+ 'warn': yellow
+ }
+
+You can find the color functions in the ``fabric.colors`` module.
+
+
+Logging Improvements
+--------------------
+
+The builtin ``puts`` and ``fastprint`` logging functions have been extended so
+that instead of having to do something like:
+
+.. syntax:: python
+
+ @task
+ def db_migrate():
+ puts(
+ "[%s] [database] migrating schemas for %s" %
+ (env.host_string, env.db_name)
+ )
+
+You can now just do:
+
+.. syntax:: python
+
+ @task
+ def db_migrate():
+ puts("migrating schemas for {db_name}", 'database')
+
+
+
+Autocompletion
+--------------
+
+`Bash completion <http://www.debian-administration.org/articles/316>`_ is one of
+those features that really helps you to be more productive. Just include the
+following in your ``~/.bashrc`` or equivalent file and you'll be able to use
+Fabric's new command completion support:
+
+.. syntax:: bash
+
+ _fab_completion() {
+ COMPREPLY=( $( \
+ COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \
+ COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
+ OPTPARSE_AUTO_COMPLETE=1 $1 ) )
+ }
+
+ complete -o default -F _fab_completion fab
+
+It completes on all available commands and command line options, e.g.
+
+.. syntax:: console
+
+ $ fab --dis<tab>
+ --disable-known-hosts --display
+
+Also, since Fabric has no way of knowing which `command line env flags`_ you
+might be using, you can specify additional autocompletion items as an
+``env.autocomplete`` list value, e.g.
+
+.. syntax:: python
+
+ env.autocomplete = ['+config_file:', '+debug']
+
+This will then make those values available for you to autocomplete, i.e.
+
+.. syntax:: console
+
+ $ fab +<tab>
+ +config_file: +debug
+
+
+Backwards Compatibility
+-----------------------
+
+All these changes should be fully backwards compatible. That is, unless you
+happen to have specified any of the new ``env`` variables like ``env.stages``,
+your existing fabfiles should run as they've always done. Do let me know if this
+is not the case...
+
+.. class:: intro-box
+
+https://github.com/tav/pylibs/tree/master/fabric
+
+
+Usage
+-----
+
+If you'd like to take advantage of these various changes, the simplest thing to
+do is to clone my `pylibs repository <https://github.com/tav/pylibs>`_ and put
+it on your ``$PYTHONPATH``, i.e.
+
+.. syntax:: console
+
+ $ git clone git://github.com/tav/pylibs.git
+
+ $ export PYTHONPATH=$PYTHONPATH:`pwd`/pylibs
+
+Then create a ``fab`` script somewhere on your ``$PATH`` with the following
+content:
+
+.. syntax:: python
+
+ #! /usr/bin/env python
+
+ from fabric.main import main
+
+ main()
+
+Make sure to make the script executable, i.e.
+
+.. syntax:: console
+
+ $ chmod +x fab
+
+And as long as you have Python 2.6+, you should be good to go...
+
+
+Next Steps
+----------
+
+I have been talking to the Fabric maintainers about merging these changes
+upstream. And so far they've been quite positive. But, as you can imagine, there
+are a number of competing ideas about what is best for Fabric's future.
+
+So if you like these features, then do leave a comment expressing your support.
+It'd really help getting these features into the next version of Fabric.
+
+-- Thanks, tav
\ No newline at end of file
diff --git a/website/css/site.css b/website/css/site.css
index 2729975..7efcf66 100644
--- a/website/css/site.css
+++ b/website/css/site.css
@@ -1,857 +1,859 @@
/*
* aaken default stylesheet -- by tav
*
*/
a {
color: #0000dd;
text-decoration: underline;
}
a:hover, a:active {
text-decoration: none;
}
a.no-underline {
text-decoration: none;
}
a.no-underline:hover {
text-decoration: underline;
}
body {
background-color: #3e3935;
background-image: url("../gfx/bg.jpg");
font-family: Baskerville, 'Baskerville old face', 'Hoefler Text', Garamond, 'Times New Roman', serif;
font-size: 18px;
margin: 0;
padding: 0;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-weight: normal !important;
clear: both;
font-size: 36px;
margin: 0;
}
h1 {
font-size: 30px;
margin: 18px 0 14px 0;
}
pre {
background-color: #fefef1;
border: 1px solid #f7a600;
border-left: 5px solid #f7a600;
color: #101010;
font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
overflow: hidden;
padding: 12px 15px 13px 12px;
margin: 20px 30px 0 20px;
-webkit-border-bottom-right-radius: 12px;
-moz-border-radius-bottomright: 12px;
border-bottom-right-radius: 12px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
}
pre:hover {
overflow: auto;
}
pre.ascii-art {
line-height: 1em;
}
pre code {
background-color: transparent;
border: 0;
padding: 0;
border: 1px solid #c00;
}
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
strong {
font-family: "museo-1", "museo-2", Verdana, Arial, sans-serif;
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 1.4em;
font-weight: normal;
}
sup {
display: none;
}
li ul {
margin-top: 10px;
}
/* sections */
.content {
clear: both;
line-height: 1.5em;
margin-bottom: 1em;
}
#intro {
background: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
float: right;
padding: 5px 10px 10px 10px;
width: 200px;
line-height: 1.5em;
}
#main {
margin: 0px auto;
text-align: left;
width: 944px;
}
#page {
background: #fff;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
float: left;
width: 640px;
padding-left: 30px;
padding-right: 35px;
padding-top: 15px;
padding-bottom: 10px;
margin-bottom: 14px;
margin-right: 10px;
}
#site-header {
margin: 12px 0 14px 0;
text-align: right;
}
#site-title {
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border: 1px solid #fff;
color: #000;
font-family: "zalamander-caps-1","zalamander-caps-2", "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 3em;
float: left;
padding: 9px 15px 0px 15px;
text-decoration: none;
}
#site-title:hover {
border: 1px solid #000;
}
.wf-inactive #site-title {
padding-top: 0px;
padding-bottom: 8px;
}
#site-links {
padding-top: 4px;
}
#site-links a {
margin-left: 8px;
padding: 4px 6px;
text-decoration: none;
color: #fff;
font-size: 20px;
}
#site-links a:hover {
color: #000;
background: #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#translation_form {
display: inline;
margin-right: 20px;
}
.follow-link {
margin: 12px 0 8px 16px;
}
/* disqus */
#dsq-global-toolbar, #dsq-sort-by, #dsq-like-tooltip {
display: none;
}
#dsq-subscribe, #dsq-footer, .dsq-item-trackback, #dsq-account-dropdown {
display: none;
}
#dsq-content h3 {
margin: 25px 0 25px 0 !important;
}
.dsq-comment-header a {
color: #2d2827;
}
/* rst classes */
.docinfo {
margin-left: 5px;
margin-top: 20px;
}
.abstract {
margin-top: 20px;
}
code, .literal {
background-color: #fefbf6;
border: 1px solid #dbd0be;
padding: 2px 4px;
font: 14px "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
}
.topic-title {
font-weight: bold;
text-align: center;
}
.note {
color: #aaa;
margin-left: 10px;
font-style: italic;
}
.attention {
background-color: #FFC3C3;
padding: 1.5em;
margin-top: 1em;
margin-bottom: 1em;
text-align: center;
}
.admonition-title {
display: none
}
.highlight {
text-align: center;
border: 1px solid #c00;
background-color: #fff;
background-color: #c00;
color: #fff;
padding: 5px;
}
/* rst error */
.system-messages {
display: none;
}
/* toc */
.contents {
padding-left: 3em;
margin: 10px;
display: none;
}
.contents.toc-only {
display: block;
padding-left: 0;
margin: 0;
}
.contents.toc-only .topic-title {
display: none;
}
/* links */
a.fn-backref {
text-decoration: none;
}
a.footnote-reference {
vertical-align: super;
text-decoration: none;
}
/* tables */
+
table.docutils {
- margin: 10px;
- border-spacing: 0px;
- border-width: 0 0 1px 1px;
- border-style: solid;
- border-color: #544554;
+ margin: 20px 30px 0 20px;
+ border-spacing: 0px;
}
+
table.docutils thead tr th {
- background-color: #ded0e8;
- color: #544554;
- padding: 5px;
- border-top: 1px solid #544554;
- border-right: 1px solid #544554;
- border-left: 0px;
- border-bottom: 0px;
+ background: #635b54;
+ color: #fff;
+ padding: 7px 10px;
+ font-weight: normal;
}
table.docutils td {
- padding: 5px;
- border-width: 1px 1px 0 0;
- border-style: solid;
- border-color: #544554;
+ padding: 7px;
+ border-bottom: 1px dashed #d6d2cf;
+}
+
+table.docutils td .literal {
+ white-space: nowrap;
+}
+
+table.docutils thead tr th:first-child {
+ text-align: right;
}
table.docutils tr td:first-child {
text-align: right;
}
table.footnote, table.citation {
- border: 0px;
- padding: 5px;
- margin: 5px;
+ border: 0px;
+ padding: 5px;
+ margin: 5px;
}
table.citation td, table.footnote td {
- border: 0px;
+ border: 0px;
}
table.docutils td p, table.footnote td p, table.citation td p {
- margin-top: 0px;
- padding-top: 0px;
+ margin-top: 0px;
+ padding-top: 0px;
}
table.footnote td.label, table.citation td.label {
- width: 12em;
- padding-right: 10px;
- text-align: right;
+ width: 12em;
+ padding-right: 10px;
+ text-align: right;
}
table.citation td.label a, table.footnote td.label a {
font-style: italic;
text-decoration: none;
color: #333;
}
p.caption {
color: #666;
font-style: italic;
margin-top: 5px;
padding-left: 5px;
text-align: center;
}
td p.first {
margin-top: 0;
}
td p.last {
margin-bottom: 0;
}
th.field-name, th.docinfo-name {
text-align: right;
padding-right: 5px;
white-space: nowrap;
}
table.field-list {
border: 0px;
}
table.field-list td {
border: 0px;
vertical-align: top;
padding: 1px;
}
/* doctest */
.doctest-output {
color: #a5504d;
}
.doctest-input {
color: #0d5d04;
}
.doctest-output {
color: #a5504d;
color: #c32528;
color: #bf5036;
}
.doctest-input {
color: #5d90cd;
color: #6a6a6a;
color: #0d5d04;
color: #27894f;
color: #00a33f;
color: #15973b;
color: #7f9a49;
color: #005d61;
color: #1d6c70;
color: #326008;
}
/* images */
img {
border: none;
vertical-align: top;
margin: 0;
padding: 0;
}
img.absmiddle {
vertical-align: middle;
}
/* lines */
hr {
noshade: noshade;
clear: both;
}
hr.clear {
clear: both;
height: 0;
width: 0;
margin: 0;
padding: 0;
color: #c00;
background-color: transparent;
border: 0px solid;
}
/* lists */
li {
margin-bottom: 10px;
}
/* utility classes */
.center {
text-align: center;
margin-top: 5px;
margin-bottom: 5px;
}
.hide {
display: none;
}
.image-caption {
font-style: italic;
text-align: right;
}
.float-left, .figure {
float: left;
padding: 5px;
margin-right: 12px;
border: 1px solid #ded0e8;
}
.figure {
width: 400px;
text-align: center;
}
.float-left-aligned {
float: left;
margin: 5px 12px 5px -30px;
}
.float-left-aligned .image-caption {
padding-top: 5px;
}
.float-right, .float-right-aligned {
float: right;
margin-left: 12px;
margin-bottom: 5px;
}
.float-right-aligned {
margin-right: -35px;
}
.float-right-aligned .image-caption {
padding-right: 5px;
}
.full-width, .full-width-lined {
clear: both;
margin-left: -30px;
margin-right: -35px;
}
.full-width pre {
margin: 0;
border-left: 0px;
border-right: 0px;
padding: 30px 35px 31px 30px;
-webkit-border-bottom-right-radius: 0px;
-moz-border-radius-bottomright: 0px;
border-bottom-right-radius: 0px;
-webkit-box-shadow: 0px 0px 0px transparent;
}
.full-width-lined {
border-bottom: 1px solid #cacaca;
border-top: 1px solid #cacaca;
margin-bottom: 20px;
margin-top: 20px;
}
.boxed {
border: 1px solid #cacaca;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
margin-top: 10px;
}
/* special */
h1.title {
display: none;
}
#abstract .topic-title {
display: none;
}
#table-of-contents .topic-title {
display: none;
}
.sidebox, .sidebox-grey {
padding: 17px 30px 17px 20px;
max-width: 180px;
float: right;
margin: 8px -35px 5px 10px;
}
.sidebox {
background-color: #dee;
border-right: 10px solid #488;
}
.sidebox-grey {
background-color: #eee;
border-right: 10px solid #888;
}
.intro-box {
clear: both;
width: 630px;
margin: 21px -35px 0 -30px;
background: #d6d2cf;
border-left: 10px solid #635b54;
padding: 15px 45px 16px 20px;
}
.intro-box a {
color: #635b54;
text-decoration: none;
background: url("../gfx/icon.link.gif") center right no-repeat;
padding-right: 17px;
margin-right: 3px;
}
.intro-box a:hover {
text-decoration: underline;
}
.double-column {
column-count: 2;
column-gap: 1.5em;
}
p.first {
display: inline;
}
/* document specific rules */
div#rationale a.external {
color: #888;
}
#ignore-this {
display: none;
}
.post-title {
clear: both;
margin-top: 1em;
margin-bottom: 2em;
border-top: 1px dashed #444;
padding-top: 1.4em;
line-height: 36px;
}
.post-link a {
color: #000;
font-family: "league-gothic-1","league-gothic-2", "Gill Sans", Verdana, Arial, sans-serif;
font-size: 36px;
font-weight: normal;
line-height: 36px;
text-decoration: none;
}
.post-footer {
margin-bottom: 9px;
}
.dulled {
color: #999;
font-style: italic;
}
.section-info {
padding-bottom: 1em;
border-bottom: 2px solid #544554;
margin-bottom: 1.5em;
margin-top: 1.2em;
}
.home-section-info {
margin-top: 1em;
text-align: right;
}
.right {
text-align: right;
}
.buffer {
margin-top: 6em;
}
.rss-entry { margin-bottom: 3em; }
.rss-entry .main, .feedburnerFeedBlock .main { font-size: 1.2em; padding: 25px; display: block; }
.feedburnerFeedBlock li {
list-style-type: none;
margin-bottom: 3em;
}
.feedburnerFeedBlock .headline {
display: none;
}
.section-header {
border-top: 3px solid #544554;
border-bottom: 3px solid #544554;
font-size: 2em;
text-align: center;
padding: 20px;
margin-bottom: 2em;
margin-top: 2em;
}
.index-link-info {
font-size: 0.8em;
color: #666;
}
.index-link-info a {
color: #666;
text-decoration: none;
}
.draft-article {
color: #ccc;
}
.if-time-permits {
border: 1px solid #ff6633;
padding: 4px;
color: #999;
}
.if-time-permits:before {
content: "IF TIME PERMITS";
background-color: #ff6633;
color: #fff;
padding: 5px;
margin-right: 3px;
margin-top: 3px;
}
a.button {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
}
a.button span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
}
a.button:active {
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.button:active span {
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
a.buttondown {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.buttondown span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
.tag-segment {
text-align: right;
}
.tag-segment span {
color: #fff;
padding: 0.5em;
font-size: 0.7em;
}
.tag-link {
text-decoration: none;
color: #000;
}
.tag {
background-color: #696969;
}
.tag-val-done {
background-color: #007f16;
background-color: #00782d;
background-color: #006400;
}
.tag-val-needsreview {
background-color: #a4ff00;
color: #000 !important;
}
.tag-val-inreview {
background-color: #3056bf;
}
.tag-val-todo {
background-color: #a60c00;
background-color: #d0006e;
background-color: #8B0000;
}
.tag-val-wip {
background-color: #a66e00;
background-color: #ff550f;
}
.tag-type-1 {
}
.tag-type-2 { /* #hashtags */
background-color: #2a4580;
background-color: #696969;
}
.tag-type-dep {
display: none;
}
.tag-type-milestone {
background-color: #00008B;
background-color: #06276f;
background-color: #a4ff00; /* nice colour! */
background-color: #002ca6;
background-color: #3056bf;
background-color: #898989;
}
.tag-type-priority {
background-color: #481254;
}
.tag-type-zuser {
background-color: #4573d5;
background-color: #696969;
}
#plan-tags a, #site-tags a {
margin-bottom: 0.7em;
}
#plan-container {
margin-top: 1.2em;
margin-bottom: 2.4em;
}
.plan-help {
font-size: 0.9em;
font-weight: bold;
text-align: right;
margin-bottom: 1.4em;
}
.retweetbutton { vertical-align: middle; display: inline; }
.retweetbutton iframe { vertical-align: middle; padding-bottom: 5px; }
#epigraph {
margin: 22px 40px;
color:#575757;
padding: 0 50px;
background: transparent url("http://cloud.github.com/downloads/tav/plexnet/gfx.blockquote.gif") no-repeat 0 0;
|
tav/oldblog
|
c3db4cc2251bafc25c2837016f816e4ea530d71f
|
Added pd icon to the unlicense article.
|
diff --git a/creative-commons-unlicense-and-reflections-of-a-public-domain-advocate.txt b/creative-commons-unlicense-and-reflections-of-a-public-domain-advocate.txt
index ae313bc..11967bd 100644
--- a/creative-commons-unlicense-and-reflections-of-a-public-domain-advocate.txt
+++ b/creative-commons-unlicense-and-reflections-of-a-public-domain-advocate.txt
@@ -1,173 +1,180 @@
---
created: 2011-01-26, 10:25
layout: post
license: Public Domain
---
======================================================================
Creative Commons Unlicense and Reflections of a Public Domain Advocate
======================================================================
+.. raw:: html
+
+ <div class="float-right">
+ <a href="http://unlicense.org"><img
+ src="http://unlicense.org/pd-icon.png" /></a>
+ </div>
+
I posted the following to the `Unlicense Google Group
<http://groups.google.com/group/unlicense>`_ earlier today and figured
that some of you might be interested in the proposed Creative Commons
Unlicense.
| Hi Arto, Mike et al.
|
| First of all, congrats for coming up with the term "Unlicense". It's
| genius! As someone who has been placing all of his work into the
| public domain for most of the last decade, I am very thankful that
| there is finally a concrete movement emerging around unlicensing.
|
| Now, if it's okay with you, I'd like to share my journey into the
| world of public domain and gradually build up to a proposal of a
| "Creative Commons Unlicense".
.. more
|
| **Reflections of a Public Domain Advocate**
|
| They got me before I'd even hit puberty. The UK Intellectual Property
| Office that is. At school they handed out leaflets on Copyright,
| Trademarks and Patents. I was mesmerised. Having already written 2
| books on music and working on various inventions, it was truly
| empowering to know that the law would protect my rights as a creator.
|
| Being able to dictate how your work is used. Being able to make money
| from the royalties generated by your work. Being able to prevent
| others from abusing your work for their own profit. It made perfect
| sense. It appealed to that primal desire for being in control.
|
| I was so in love with intellectual property that even my school notes
| had a copyright statement at the bottom of each page. This continued
| all the way till I was 17 when I started my first company. Being a
| tech startup in 1999, it wasn't too long before an inevitable
| encounter with the open source movement.
|
| As you can imagine, this was quite an experience. In fact, it's really
| nice to see some familiar faces from those times on this list: Mike
| Linksvayer (from Bitzi days) and Peter Saint-Andre (from the early
| Jabber days).
|
| It took a few months, but by the time 2000 began, I was convinced of
| the merits of open source. The copyleft nature of the GPL assuaged my
| fears of having my work exploited by others. And the success of
| projects like Linux and companies like VA Linux Systems served as
| tangible proof that sharing worked.
|
| And so I became one of those annoying free software fanatics. I am
| sorry to say that I wasted countless hours arguing on various internet
| forums about the merits of the GPL versus other licenses. But, on the
| flip side, I did acquire various proprietary initiatives and release
| them as free software.
|
| In any case, it was an uphill struggle convincing investors of the
| merits of open source. It simply did not make sense to them. Many
| refused to invest for that reason alone. And, all the while, I kept to
| my belief that a billion-dollar industry was possible by enabling
| creators to make money from sharing their works openly.
|
| And then finally, in either late 2001 or early 2002, one of my
| friends, Tavin Cole, decided to spend an entire day of his life
| questioning my stance on the GPL. To this day I am extremely grateful
| for his effort â he enlightened me on the merits of the public domain.
|
| In essence, his argument revolved around the fact that copyleft is
| merely an act of control and true freedom would be to enable people to
| do whatever they pleased with your work. He correctly identified fear
| as being a prime motivator behind my love affair with the GPL and that
| life would be a lot more pleasant without being gripped by it.
|
| With my belief in the GPL shaken, I started experimenting with the
| public domain. Python hackers seemed to public domain their work with
| a single line, so I adopted a similar practice and added a minimal
| header of the format:
::
# Released into the Public Domain by tav <tav@espians.com>
|
| This worked out quite well until 2004 when I moved to Berlin for a
| year. Here I came across various German hackers who argued that it was
| impossible to place works into the public domain due to the
| consideration of moral rights under German law.
|
| I experimented with various structures to try and resolve this issue,
| e.g. contracts between the individuals and a company based in the UK
| which would then release the intellectual property into the public
| domain, etc. But nothing was really satisfactory until Creative
| Commons released the CC0 license.
|
| It cleverly combined the public domain dedication with a fallback
| public license for jurisdictions where one can't fully public domain
| one's work. Not understanding why CC0 can't be used for code, I
| adopted the license with enthusiasm and remixed it with a grant of
| patent rights to create a Public Domain License which I've been using
| for all my work â writing, code, designs, etc.
|
| **Creative Commons Unlicense**
|
| As you can imagine, it sounded silly to be public domain-ing work
| under the Public Domain *License* â but it seemed good enough.
| However, once I heard about "Unlicense", I was smitten by its
| awesomeness and have already migrated a few projects, e.g.
|
| * https://github.com/tav/ampify
| * https://github.com/tav/git-review
|
| Now, whilst I've adopted the term wholesale, the text on `unlicense.org`_
| doesn't address a number of concerns:
|
| * It is limited to just code. Software projects also tend to have
| documentation, schemas, graphics, etc. It would be nice if the
| unlicense covered all of these.
|
| * It doesn't address moral rights in any way.
|
| * It doesn't address patent rights in any way. This becomes even more
| relevant when you're receiving patches from organisations who might
| hold relevant patents.
|
| * It doesn't provide advice on how to refer to the unlicense within
| individual files. I've taken to having the following minimal header
| instead of copying the entire text into every file:
::
# Public Domain (-) 2010-2011 The Ampify Authors.
# See the Ampify UNLICENSE file for details.
|
| * It doesn't address third party code. Putting an UNLICENSE file in
| the root of the repository without such consideration suggests that
| all the code files are in the public domain â which may not be true.
|
| In an ideal world, we'd all come together and build on CC0 and the
| Unlicense to create a *Creative Commons Unlicense* which addresses all
| of these concerns. I am not sure if this would be of interest to
| anyone else, but it is of interest to me.
|
| I've had a go at remixing the various texts into a new Unlicense:
|
| * http://ampify.it/unlicense.html
|
| Here is the raw text, including the accompanying authors file:
|
| * https://github.com/tav/ampify/blob/master/UNLICENSE
| * https://github.com/tav/ampify/blob/master/AUTHORS
|
| Now I am not a lawyer and the text needs work, but I hope it's a good
| starting point â or, at the very least, provides some idea of what I'm
| getting at.
|
| Is this of interest to any of you? Could we come together to manifest
| a Creative Commons Unlicense?
|
| Please do let me know what you think.
|
| --
| Cheers, tav
.. _unlicense.org: http://unlicense.org
|
tav/oldblog
|
0c2cb627da6d84d736710f190c26fb9e47da49ad
|
Added Creative Commons Unlicense email as a post.
|
diff --git a/creative-commons-unlicense-and-reflections-of-a-public-domain-advocate.txt b/creative-commons-unlicense-and-reflections-of-a-public-domain-advocate.txt
new file mode 100644
index 0000000..ae313bc
--- /dev/null
+++ b/creative-commons-unlicense-and-reflections-of-a-public-domain-advocate.txt
@@ -0,0 +1,173 @@
+---
+created: 2011-01-26, 10:25
+layout: post
+license: Public Domain
+---
+
+======================================================================
+Creative Commons Unlicense and Reflections of a Public Domain Advocate
+======================================================================
+
+I posted the following to the `Unlicense Google Group
+<http://groups.google.com/group/unlicense>`_ earlier today and figured
+that some of you might be interested in the proposed Creative Commons
+Unlicense.
+
+ | Hi Arto, Mike et al.
+ |
+ | First of all, congrats for coming up with the term "Unlicense". It's
+ | genius! As someone who has been placing all of his work into the
+ | public domain for most of the last decade, I am very thankful that
+ | there is finally a concrete movement emerging around unlicensing.
+ |
+ | Now, if it's okay with you, I'd like to share my journey into the
+ | world of public domain and gradually build up to a proposal of a
+ | "Creative Commons Unlicense".
+.. more
+
+ |
+ | **Reflections of a Public Domain Advocate**
+ |
+ | They got me before I'd even hit puberty. The UK Intellectual Property
+ | Office that is. At school they handed out leaflets on Copyright,
+ | Trademarks and Patents. I was mesmerised. Having already written 2
+ | books on music and working on various inventions, it was truly
+ | empowering to know that the law would protect my rights as a creator.
+ |
+ | Being able to dictate how your work is used. Being able to make money
+ | from the royalties generated by your work. Being able to prevent
+ | others from abusing your work for their own profit. It made perfect
+ | sense. It appealed to that primal desire for being in control.
+ |
+ | I was so in love with intellectual property that even my school notes
+ | had a copyright statement at the bottom of each page. This continued
+ | all the way till I was 17 when I started my first company. Being a
+ | tech startup in 1999, it wasn't too long before an inevitable
+ | encounter with the open source movement.
+ |
+ | As you can imagine, this was quite an experience. In fact, it's really
+ | nice to see some familiar faces from those times on this list: Mike
+ | Linksvayer (from Bitzi days) and Peter Saint-Andre (from the early
+ | Jabber days).
+ |
+ | It took a few months, but by the time 2000 began, I was convinced of
+ | the merits of open source. The copyleft nature of the GPL assuaged my
+ | fears of having my work exploited by others. And the success of
+ | projects like Linux and companies like VA Linux Systems served as
+ | tangible proof that sharing worked.
+ |
+ | And so I became one of those annoying free software fanatics. I am
+ | sorry to say that I wasted countless hours arguing on various internet
+ | forums about the merits of the GPL versus other licenses. But, on the
+ | flip side, I did acquire various proprietary initiatives and release
+ | them as free software.
+ |
+ | In any case, it was an uphill struggle convincing investors of the
+ | merits of open source. It simply did not make sense to them. Many
+ | refused to invest for that reason alone. And, all the while, I kept to
+ | my belief that a billion-dollar industry was possible by enabling
+ | creators to make money from sharing their works openly.
+ |
+ | And then finally, in either late 2001 or early 2002, one of my
+ | friends, Tavin Cole, decided to spend an entire day of his life
+ | questioning my stance on the GPL. To this day I am extremely grateful
+ | for his effort â he enlightened me on the merits of the public domain.
+ |
+ | In essence, his argument revolved around the fact that copyleft is
+ | merely an act of control and true freedom would be to enable people to
+ | do whatever they pleased with your work. He correctly identified fear
+ | as being a prime motivator behind my love affair with the GPL and that
+ | life would be a lot more pleasant without being gripped by it.
+ |
+ | With my belief in the GPL shaken, I started experimenting with the
+ | public domain. Python hackers seemed to public domain their work with
+ | a single line, so I adopted a similar practice and added a minimal
+ | header of the format:
+
+ ::
+
+ # Released into the Public Domain by tav <tav@espians.com>
+
+ |
+ | This worked out quite well until 2004 when I moved to Berlin for a
+ | year. Here I came across various German hackers who argued that it was
+ | impossible to place works into the public domain due to the
+ | consideration of moral rights under German law.
+ |
+ | I experimented with various structures to try and resolve this issue,
+ | e.g. contracts between the individuals and a company based in the UK
+ | which would then release the intellectual property into the public
+ | domain, etc. But nothing was really satisfactory until Creative
+ | Commons released the CC0 license.
+ |
+ | It cleverly combined the public domain dedication with a fallback
+ | public license for jurisdictions where one can't fully public domain
+ | one's work. Not understanding why CC0 can't be used for code, I
+ | adopted the license with enthusiasm and remixed it with a grant of
+ | patent rights to create a Public Domain License which I've been using
+ | for all my work â writing, code, designs, etc.
+ |
+ | **Creative Commons Unlicense**
+ |
+ | As you can imagine, it sounded silly to be public domain-ing work
+ | under the Public Domain *License* â but it seemed good enough.
+ | However, once I heard about "Unlicense", I was smitten by its
+ | awesomeness and have already migrated a few projects, e.g.
+ |
+ | * https://github.com/tav/ampify
+ | * https://github.com/tav/git-review
+ |
+ | Now, whilst I've adopted the term wholesale, the text on `unlicense.org`_
+ | doesn't address a number of concerns:
+ |
+ | * It is limited to just code. Software projects also tend to have
+ | documentation, schemas, graphics, etc. It would be nice if the
+ | unlicense covered all of these.
+ |
+ | * It doesn't address moral rights in any way.
+ |
+ | * It doesn't address patent rights in any way. This becomes even more
+ | relevant when you're receiving patches from organisations who might
+ | hold relevant patents.
+ |
+ | * It doesn't provide advice on how to refer to the unlicense within
+ | individual files. I've taken to having the following minimal header
+ | instead of copying the entire text into every file:
+
+ ::
+
+ # Public Domain (-) 2010-2011 The Ampify Authors.
+ # See the Ampify UNLICENSE file for details.
+
+ |
+ | * It doesn't address third party code. Putting an UNLICENSE file in
+ | the root of the repository without such consideration suggests that
+ | all the code files are in the public domain â which may not be true.
+ |
+ | In an ideal world, we'd all come together and build on CC0 and the
+ | Unlicense to create a *Creative Commons Unlicense* which addresses all
+ | of these concerns. I am not sure if this would be of interest to
+ | anyone else, but it is of interest to me.
+ |
+ | I've had a go at remixing the various texts into a new Unlicense:
+ |
+ | * http://ampify.it/unlicense.html
+ |
+ | Here is the raw text, including the accompanying authors file:
+ |
+ | * https://github.com/tav/ampify/blob/master/UNLICENSE
+ | * https://github.com/tav/ampify/blob/master/AUTHORS
+ |
+ | Now I am not a lawyer and the text needs work, but I hope it's a good
+ | starting point â or, at the very least, provides some idea of what I'm
+ | getting at.
+ |
+ | Is this of interest to any of you? Could we come together to manifest
+ | a Creative Commons Unlicense?
+ |
+ | Please do let me know what you think.
+ |
+ | --
+ | Cheers, tav
+
+.. _unlicense.org: http://unlicense.org
|
tav/oldblog
|
7f537d627d9b1282d817273636f6c68888b639f0
|
Credited Amma, Peter and John for Peerfund.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index d0bd2d9..6c0b4be 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,193 +1,199 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| archels | £1 |
+-----------------------------------------+---------------+
| Lauri Love | £50 |
+-----------------------------------------+---------------+
| Alex Rollin | £20 |
+-----------------------------------------+---------------+
| Josef Davies-Coates | £20 |
+-----------------------------------------+---------------+
| mattcoop | £14 |
+-----------------------------------------+---------------+
| Benjamin Degenhart | £10 |
+-----------------------------------------+---------------+
| Michael Kedzierski | £30 |
+-----------------------------------------+---------------+
| Charles Goodier | £100 |
+-----------------------------------------+---------------+
| Chris Greiner | £20 |
+-----------------------------------------+---------------+
| Tim Lossen | £100 |
+-----------------------------------------+---------------+
- | **Still Needed** | £5,335 |
+ | Thamilarasi Sivapathasundaram | £100 |
+ +-----------------------------------------+---------------+
+ | pgchamberlin | £10 |
+ +-----------------------------------------+---------------+
+ | John McCane-Whitney | £250 |
+ +-----------------------------------------+---------------+
+ | **Still Needed** | £4,975 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/espians/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
e2f3efa7a9866964e1e0a26ed8f259c07dadf0a4
|
Credited Chris Greiner and Tim Lossen for Peerfund.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index c9c5438..0ea1933 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,189 +1,193 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| archels | £1 |
+-----------------------------------------+---------------+
| Lauri Love | £50 |
+-----------------------------------------+---------------+
| Alex Rollin | £20 |
+-----------------------------------------+---------------+
| Josef Davies-Coates | £20 |
+-----------------------------------------+---------------+
| mattcoop | £14 |
+-----------------------------------------+---------------+
| Benjamin Degenhart | £10 |
+-----------------------------------------+---------------+
| Michael Kedzierski | £30 |
+-----------------------------------------+---------------+
| Charles Goodier | £100 |
+-----------------------------------------+---------------+
- | **Still Needed** | £5,455 |
+ | Chris Greiner | £20 |
+ +-----------------------------------------+---------------+
+ | Tim Lossen | £100 |
+ +-----------------------------------------+---------------+
+ | **Still Needed** | £5,335 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
65f2dfc7ac5b3d72f2d0257e79c1330860458fe5
|
Credited Charles Goodier for the Peerfund.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index f91696c..c9c5438 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,187 +1,189 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| archels | £1 |
+-----------------------------------------+---------------+
| Lauri Love | £50 |
+-----------------------------------------+---------------+
| Alex Rollin | £20 |
+-----------------------------------------+---------------+
| Josef Davies-Coates | £20 |
+-----------------------------------------+---------------+
| mattcoop | £14 |
+-----------------------------------------+---------------+
| Benjamin Degenhart | £10 |
+-----------------------------------------+---------------+
| Michael Kedzierski | £30 |
+-----------------------------------------+---------------+
- | **Still Needed** | £5,555 |
+ | Charles Goodier | £100 |
+ +-----------------------------------------+---------------+
+ | **Still Needed** | £5,455 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
eb437bf277d65a82be8a02794f638b368de79e4c
|
Credited Ycros for the Peerfund.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index f066027..f91696c 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,185 +1,187 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| archels | £1 |
+-----------------------------------------+---------------+
| Lauri Love | £50 |
+-----------------------------------------+---------------+
| Alex Rollin | £20 |
+-----------------------------------------+---------------+
| Josef Davies-Coates | £20 |
+-----------------------------------------+---------------+
| mattcoop | £14 |
+-----------------------------------------+---------------+
| Benjamin Degenhart | £10 |
+-----------------------------------------+---------------+
- | **Still Needed** | £5,585 |
+ | Michael Kedzierski | £30 |
+ +-----------------------------------------+---------------+
+ | **Still Needed** | £5,555 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
839beade211a02d3efeeb9e91705b1254ae1e2e7
|
Credited Josef, Matt and Ben for the Peerfund.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index 288e55c..f066027 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,179 +1,185 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| archels | £1 |
+-----------------------------------------+---------------+
| Lauri Love | £50 |
+-----------------------------------------+---------------+
| Alex Rollin | £20 |
+-----------------------------------------+---------------+
- | **Still Needed** | £5,629 |
+ | Josef Davies-Coates | £20 |
+ +-----------------------------------------+---------------+
+ | mattcoop | £14 |
+ +-----------------------------------------+---------------+
+ | Benjamin Degenhart | £10 |
+ +-----------------------------------------+---------------+
+ | **Still Needed** | £5,585 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
f58bf5489009cbb4e7cdd6f8c271bf2f6e6ab011
|
Ooops, forgot to update the total.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index 2b8c332..288e55c 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,179 +1,179 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| archels | £1 |
+-----------------------------------------+---------------+
| Lauri Love | £50 |
+-----------------------------------------+---------------+
| Alex Rollin | £20 |
+-----------------------------------------+---------------+
- | **Still Needed** | £5,649 |
+ | **Still Needed** | £5,629 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
b099eab51253a210a7cb0a820c5b97f0740cccec
|
Credited Alex Rollin for the Peerfund.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index 13ea8f4..2b8c332 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,177 +1,179 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| archels | £1 |
+-----------------------------------------+---------------+
| Lauri Love | £50 |
+-----------------------------------------+---------------+
+ | Alex Rollin | £20 |
+ +-----------------------------------------+---------------+
| **Still Needed** | £5,649 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
df5dd631312a349fd49904d7dad121b82cbc9dae
|
Credited Lauri Love for the Peerfund.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index 83a6df7..13ea8f4 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,175 +1,177 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| archels | £1 |
+-----------------------------------------+---------------+
- | **Still Needed** | £5,699 |
+ | Lauri Love | £50 |
+ +-----------------------------------------+---------------+
+ | **Still Needed** | £5,649 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
9f80603ae1e5665fee925769db21b770d03991a4
|
Credited archels for the peerfund.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index ba48556..83a6df7 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,173 +1,175 @@
---
created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
- | **Still Needed** | £5,700 |
+ | archels | £1 |
+ +-----------------------------------------+---------------+
+ | **Still Needed** | £5,699 |
+-----------------------------------------+---------------+
**My Work:**
.. more
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
<a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
33ed6d4543b16f1aae3d73151ff275bc17b70ee9
|
Published the peerfund article.
|
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
index 8b101f1..ba48556 100644
--- a/will-you-peerfund-my-work.txt
+++ b/will-you-peerfund-my-work.txt
@@ -1,171 +1,173 @@
---
+created: 2010-07-14, 08:34
layout: post
license: Public Domain
---
==========================
Will You Peerfund My Work?
==========================
.. raw:: html
<div class="float-right">
<a href="http://tav.espians.com"><img width="213px" height="191px"
src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
</div>
I'm looking to raise £6,000 to support myself and a `few
<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
the next 3 months so that we can launch a whole new socio-economic-technological
infrastructure.
Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
appreciated and rewarded. Thank you!
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
**The Supporters So Far:**
.. class:: borderless-table
+-----------------------------------------+---------------+
| Robert de Souza | £300 |
+-----------------------------------------+---------------+
| **Still Needed** | £5,700 |
+-----------------------------------------+---------------+
**My Work:**
+.. more
+
The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
source, decentralised application platform. I've been working on this for over
10 years and, as proof, you can see:
* The web archive for Espra -- an early attempt in 2000-2001 [`link
<http://web.archive.org/web/20010922205916/http://espra.net/>`__]
* The first public discussion with others about the idea -- September 11th 2001
[`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
* The web archive for Plex -- another attempt in 2001-2002 [`link
<http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
what context. This will be used to help overcome information overload and here's
`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
.. raw:: html
<div class="center">
<a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
/></a>
</div>
And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
searches Twitter streams according to an individual's Trust Map:
.. raw:: html
<div class="center">
- <a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
+ <a href="http://tweets.trustmaps.com"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
/></a>
</div>
Ampify will also support `Pecus
<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
as a foundation for a reputation economy. It'll enable those who share their
works to be properly rewarded, e.g. open source developers, musicians, blog
authors, youtube content creators, etc.
.. raw:: html
<div class="center">
<a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
src="http://static.ampify.it/img.presentation-sample-screen.png"
width="691px" height="518px" class="boxed"
/></a>
</div>
This will be complemented by `Amp Creds
<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
-- a global reference currency backed by Processing, Storage and Transfer --
that will hopefully enable a more stable economy than the boom-and-bust cycles
of the present one.
Ampify will also enable a new form of decentralised collaboration through the
use of the Confluence model. Here's a `MediaWiki-based prototype
<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
[`source code <http://github.com/tav/confluence>`_]:
.. raw:: html
<div class="center">
<a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
/></a>
</div>
It's taken a lot of iterations and failures to figure out what works and what
doesn't -- and I'm confident about having a working version of Ampify by
October. There's already the start of `some documentation
<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
<http://github.com/tav/ampify>`_ to follow the open development.
.. raw:: html
<div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
width="691px" height="518px" class="boxed"
/></a></div>
And, finally, your support will also enable my other `various open source
contributions <http://github.com/tav>`_ and help put on events like `Social
Startup Labs
<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
which helps tackle the issue of jobs creation by helping local communities
identify the needs and opportunities for `Social Businesses
<http://en.wikipedia.org/wiki/Social_business>`_:
.. raw:: html
<div class="center">
<a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
/></a>
</div>
Do drop by and say hello on IRC chat if you're interested in any of this work:
.. raw:: html
<div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
<form action="http://webchat.freenode.net/" method="get">
<button style="padding: 2px 6px 3px;">Click to join #esp</button>
<input type="hidden" name="channels" value="esp" />
</form>
</div>
<pre>
server: irc.freenode.net
channel: #esp
chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
</pre>
I believe my work adds real value and, with your support, I can get it to a
-stage where it could potentially make a substantially positive impact on
-society:
+stage where it could make a really positive impact:
* `Support my work with a PayPal contribution!
<https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
.. raw:: html
<div class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
Thank you.
\ No newline at end of file
|
tav/oldblog
|
7c4e1af768cd6d11eff45eedb612a4b814d0d43c
|
Added an article about peerfunding my work.
|
diff --git a/website/css/site.css b/website/css/site.css
index 2073cf0..74d12f4 100644
--- a/website/css/site.css
+++ b/website/css/site.css
@@ -491,513 +491,526 @@ h1.title {
p.first {
display: inline;
}
/* document specific rules */
div#rationale a.external {
color: #888;
}
#ignore-this {
display: none;
}
.post-title {
clear: both;
margin-top: 1em;
margin-bottom: 2em;
border-top: 1px dashed #444;
padding-top: 1.4em;
padding-bottom: 1em;
line-height: 2.3em;
}
.post-link {
margin-bottom: 0.7em;
}
.post-link a {
font-weight: normal;
color: #000;
text-decoration: none;
font-size: 2em;
}
.post-footer {
margin-bottom: 1em;
text-align: center;
}
.dulled {
color: #999;
font-style: italic;
}
.section-info {
padding-bottom: 1em;
border-bottom: 2px solid #544554;
margin-bottom: 1.5em;
margin-top: 1.2em;
}
.home-section-info {
margin-top: 1em;
text-align: right;
}
.right {
text-align: right;
}
.buffer {
margin-top: 6em;
}
.rss-entry { margin-bottom: 3em; }
.rss-entry .main, .feedburnerFeedBlock .main { font-size: 1.2em; padding: 25px; display: block; }
.feedburnerFeedBlock li {
list-style-type: none;
margin-bottom: 3em;
}
.feedburnerFeedBlock .headline {
display: none;
}
.section-header {
border-top: 3px solid #544554;
border-bottom: 3px solid #544554;
font-size: 2em;
text-align: center;
padding: 20px;
margin-bottom: 2em;
margin-top: 2em;
}
.index-link-info {
font-size: 0.8em;
color: #666;
}
.index-link-info a {
color: #666;
text-decoration: none;
}
.draft-article {
color: #ccc;
}
.friendfeed.widget {
border: 0px !important;
}
.friendfeed {
font: 13px/19px Verdana !important;
font-family: Verdana, Arial, sans-serif !important;
}
.friendfeed .entry {
padding: 0.5em !important;
}
.if-time-permits {
border: 1px solid #ff6633;
padding: 4px;
color: #999;
}
.if-time-permits:before {
content: "IF TIME PERMITS";
background-color: #ff6633;
color: #fff;
padding: 5px;
margin-right: 3px;
margin-top: 3px;
}
#translation_form {
display: inline;
}
.menu-item {
padding-left: 0.5em;
padding-right: 0.5em;
border-left: 1px solid #000;
}
.menu-item-left {
padding-left: 0.5em;
padding-right: 0.5em;
border-left: 1px solid #000;
}
.menu-item-final {
padding-left: 0.5em;
border-left: 1px solid #000;
}
.menu-item-padding {
padding-right: 0.5em;
}
.dsq-record-img {
vertical-align: middle;
text-decoration: none;
}
#dsq-content a {
text-decoration: none;
}
#dsq-comments a, #dsq-content > p a {
text-decoration: underline;
}
#dsq-comments a:hover, #dsq-content > p a:hover {
text-decoration: none;
}
a.button {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
}
a.button span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
}
a.button:active {
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.button:active span {
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
a.buttondown {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.buttondown span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
.tag-segment {
text-align: right;
}
.tag-segment span {
color: #fff;
padding: 0.5em;
font-size: 0.7em;
}
.tag-link {
text-decoration: none;
color: #000;
}
.tag {
background-color: #696969;
}
.tag-val-done {
background-color: #007f16;
background-color: #00782d;
background-color: #006400;
}
.tag-val-needsreview {
background-color: #a4ff00;
color: #000 !important;
}
.tag-val-inreview {
background-color: #3056bf;
}
.tag-val-todo {
background-color: #a60c00;
background-color: #d0006e;
background-color: #8B0000;
}
.tag-val-wip {
background-color: #a66e00;
background-color: #ff550f;
}
.tag-type-1 {
}
.tag-type-2 { /* #hashtags */
background-color: #2a4580;
background-color: #696969;
}
.tag-type-dep {
display: none;
}
.tag-type-milestone {
background-color: #00008B;
background-color: #06276f;
background-color: #a4ff00; /* nice colour! */
/* color: #000 !important; */
background-color: #002ca6;
background-color: #3056bf;
background-color: #898989;
}
.tag-type-priority {
background-color: #481254;
}
.tag-type-zuser {
background-color: #4573d5;
background-color: #696969;
}
#plan-tags a, #site-tags a {
margin-bottom: 0.7em;
}
#plan-container {
margin-top: 1.2em;
margin-bottom: 2.4em;
}
.plan-help {
font-size: 0.9em;
font-weight: bold;
text-align: right;
margin-bottom: 1.4em;
}
.retweetbutton { vertical-align: middle; display: inline; }
.retweetbutton iframe { vertical-align: middle; padding-bottom: 5px; }
#epigraph {
margin: 22px 40px;
color:#575757;
padding: 0 50px;
background: transparent url("http://cloud.github.com/downloads/tav/plexnet/gfx.blockquote.gif") no-repeat 0 0;
}
#epigraph-attribution {
text-align: right;
}
#dsq-content h3 {
margin-bottom: 1em !important;
padding: 0.4em;
font-size: 1.4em;
background-color: #544554;
color: #fff;
text-align: right;
}
#main {
width: 700px;
}
#site-header {
border-bottom: 1px dashed #444;
}
#site-logo {
float: left;
margin-right: 0.5em;
}
#site-info {
padding-top: 0.5em;
padding-bottom: 0.5em;
text-align: right;
}
#site-welcome {
font-size: 1.4em;
margin-top: 1em;
}
.article-title {
margin-top: 0.3em;
margin-bottom: 2.5em;
padding-bottom: 0.3em;
padding-top: 0.7em;
line-height: 2.3em;
}
.article-info {
font-size: 1em;
}
.additional-content-info {
float: right;
}
.attention {
background-color: #bfeeff;
}
.sidebox {
background-color: #bfeeff;
}
.more-link { display: none; }
.block-section {
border-top: 1px dashed #666;
margin-top: 20px;
padding-top: 20px;
}
/* Source code syntax highlighting */
.syntax .c { color: #919191 } /* Comment */
.syntax .cm { color: #919191 } /* Comment.Multiline */
.syntax .cp { color: #919191 } /* Comment.Preproc */
.syntax .cs { color: #919191 } /* Comment.Special */
.syntax .c1 { color: #919191 } /* Comment.Single */
.syntax .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.syntax .g { color: #101010 } /* Generic */
.syntax .gd { color: #d22323 } /* Generic.Deleted */
.syntax .ge { color: #101010; font-style: italic } /* Generic.Emph */
.syntax .gh { color: #101010 } /* Generic.Heading */
.syntax .gi { color: #589819 } /* Generic.Inserted */
.syntax .go { color: #6a6a6a } /* Generic.Output */
.syntax .gp { color: #6a6a6a } /* Generic.Prompt */
.syntax .gr { color: #d22323 } /* Generic.Error */
.syntax .gs { color: #101010 } /* Generic.Strong */
.syntax .gt { color: #d22323 } /* Generic.Traceback */
.syntax .gu { color: #101010 } /* Generic.Subheading */
.syntax .k { color: #c32528 } /* Keyword */ /* espian red */
.syntax .k { color: #ff5600 } /* Keyword */ /* orangy */
.syntax .kc { color: #ff5600 } /* Keyword.Constant */
.syntax .kd { color: #ff5600 } /* Keyword.Declaration */
.syntax .kd { color: #ff5600 } /* Keyword.Declaration */
.syntax .kn { color: #ff5600 } /* Keyword */
.syntax .kp { color: #ff5600 } /* Keyword.Pseudo */
.syntax .kr { color: #ff5600 } /* Keyword.Reserved */
.syntax .kt { color: #ff5600 } /* Keyword.Type */
.syntax .l { color: #101010 } /* Literal */
.syntax .ld { color: #101010 } /* Literal.Date */
.syntax .m { color: #3677a9 } /* Literal.Number */ /* darkish pastely blue */
.syntax .m { color: #00a33f } /* Literal.Number */ /* brightish green */
.syntax .m { color: #1550a2 } /* Literal.Number */ /* darker blue */
.syntax .m { color: #5d90cd } /* Literal.Number */ /* pastely blue */
.syntax .mf { color: #5d90cd } /* Literal.Number.Float */
.syntax .mh { color: #5d90cd } /* Literal.Number.Hex */
.syntax .mi { color: #5d90cd } /* Literal.Number.Integer */
.syntax .il { color: #5d90cd } /* Literal.Number.Integer.Long */
.syntax .mo { color: #5d90cd } /* Literal.Number.Oct */
.syntax .bp { color: #a535ae } /* Name.Builtin.Pseudo */
.syntax .n { color: #101010 } /* Name */
.syntax .na { color: #bbbbbb } /* Name.Attribute */
.syntax .nb { color: #bf78cc } /* Name.Builtin */ /* pastely purple */
.syntax .nb { color: #af956f } /* Name.Builtin */ /* pastely light brown */
.syntax .nb { color: #a535ae } /* Name.Builtin */ /* brightish pastely purple */
.syntax .nc { color: #101010 } /* Name.Class */
.syntax .nd { color: #6d8091 } /* Name.Decorator */
.syntax .ne { color: #af956f } /* Name.Exception */
.syntax .nf { color: #3677a9 } /* Name.Function */
.syntax .nf { color: #1550a2 } /* Name.Function */
.syntax .ni { color: #101010 } /* Name.Entity */
.syntax .nl { color: #101010 } /* Name.Label */
.syntax .nn { color: #101010 } /* Name.Namespace */
.syntax .nn { color: #101010 } /* Name.Namespace */
.syntax .no { color: #101010 } /* Name.Constant */
.syntax .nx { color: #101010 } /* Name.Other */
.syntax .nt { color: #6d8091 } /* Name.Tag */
.syntax .nv { color: #101010 } /* Name.Variable */
.syntax .vc { color: #101010 } /* Name.Variable.Class */
.syntax .vg { color: #101010 } /* Name.Variable.Global */
.syntax .vi { color: #101010 } /* Name.Variable.Instance */
.syntax .py { color: #101010 } /* Name.Property */
.syntax .o { color: #ff5600 } /* Operator */ /* orangy */
.syntax .o { color: #101010 } /* Operator */
.syntax .ow { color: #101010 } /* Operator.Word */
.syntax .p { color: #101010 } /* Punctuation */
.syntax .s { color: #dd1144 } /* Literal.String */ /* darkish red */
.syntax .s { color: #c32528 } /* Literal.String */ /* espian red */
.syntax .s { color: #39946a } /* Literal.String */ /* pastely greeny */
.syntax .s { color: #5d90cd } /* Literal.String */ /* pastely blue */
.syntax .s { color: #00a33f } /* Literal.String */ /* brightish green */
.syntax .sb { color: #00a33f } /* Literal.String.Backtick */
.syntax .sc { color: #00a33f } /* Literal.String.Char */
.syntax .sd { color: #00a33f } /* Literal.String.Doc */
.syntax .se { color: #00a33f } /* Literal.String.Escape */
.syntax .sh { color: #00a33f } /* Literal.String.Heredoc */
.syntax .si { color: #00a33f } /* Literal.String.Interpol */
.syntax .sr { color: #00a33f } /* Literal.String.Regex */
.syntax .ss { color: #00a33f } /* Literal.String.Symbol */
.syntax .sx { color: #00a33f } /* Literal.String.Other */
.syntax .s1 { color: #00a33f } /* Literal.String.Single */
.syntax .s2 { color: #00a33f } /* Literal.String.Double */
.syntax .w { color: #101010 } /* Text.Whitespace */
.syntax .x { color: #101010 } /* Other */
.syntax.bash .nb { color: #101010 }
.syntax.bash .nv { color: #c32528 }
.syntax.css .k { color: #606060 }
.syntax.css .nc { color: #c32528 }
.syntax.css .nf { color: #c32528 }
.syntax.css .nt { color: #c32528 }
.syntax.rst .k { color: #5d90cd }
.syntax.rst .ow { color: #5d90cd }
.syntax.rst .p { color: #5d90cd }
.syntax.yaml .l-Scalar-Plain { color: #5d90cd }
.syntax.yaml .p-Indicator { color: #101010 }
.footer-info {
border-top: 1px dotted #999;
border-bottom: 1px dotted #999;
padding: 10px 0;
}
.footer-info-block {
padding: 13px 10px 10px 17px;
+}
+
+.boxed {
+ border: 1px solid #cacaca;
+ -moz-border-radius: 5px;
+ -webkit-border-radius: 5px;
+ border-radius: 5px;
+ -webkit-box-shadow: 0px 0px 7px #cacaca;
+ margin-top: 10px;
+}
+
+table.borderless-table, .borderless-table tr, .borderless-table td {
+ border: 0px !important;
}
\ No newline at end of file
diff --git a/will-you-peerfund-my-work.txt b/will-you-peerfund-my-work.txt
new file mode 100644
index 0000000..8b101f1
--- /dev/null
+++ b/will-you-peerfund-my-work.txt
@@ -0,0 +1,171 @@
+---
+layout: post
+license: Public Domain
+---
+
+==========================
+Will You Peerfund My Work?
+==========================
+
+.. raw:: html
+
+ <div class="float-right">
+ <a href="http://tav.espians.com"><img width="213px" height="191px"
+ src="http://static.ampify.it/profile.sky-and-tav.jpg" /></a>
+ </div>
+
+I'm looking to raise £6,000 to support myself and a `few
+<http://sofiabustamante.com/>`_ `others <http://twitter.com/evangineer>`_ for
+the next 3 months so that we can launch a whole new socio-economic-technological
+infrastructure.
+
+Any contribution you can make -- £60, £300 or even £1,000 -- will be greatly
+appreciated and rewarded. Thank you!
+
+* `Support my work with a PayPal contribution!
+ <https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
+
+**The Supporters So Far:**
+
+ .. class:: borderless-table
+
+ +-----------------------------------------+---------------+
+ | Robert de Souza | £300 |
+ +-----------------------------------------+---------------+
+ | **Still Needed** | £5,700 |
+ +-----------------------------------------+---------------+
+
+**My Work:**
+
+The core of my work is about creating `Ampify <http://ampify.it>`_ -- an open
+source, decentralised application platform. I've been working on this for over
+10 years and, as proof, you can see:
+
+* The web archive for Espra -- an early attempt in 2000-2001 [`link
+ <http://web.archive.org/web/20010922205916/http://espra.net/>`__]
+
+* The first public discussion with others about the idea -- September 11th 2001
+ [`link <http://chatlogs.planetrdf.com/rdfig/2001-09-11.html#T03-17-00>`__]
+
+* The web archive for Plex -- another attempt in 2001-2002 [`link
+ <http://web.archive.org/web/20020601161948/http://plexdev.org/>`__]
+
+A key aspect of Ampify is Trust Maps -- a way of specifying who you trust and in
+what context. This will be used to help overcome information overload and here's
+`a prototype <http://www.trustmap.org>`_ that was used to explore the idea:
+
+.. raw:: html
+
+ <div class="center">
+ <a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-psqy9pswin8pahudjimcsei8p5.medium.jpg"
+ /></a>
+ </div>
+
+And, `here's another prototype <http://tweets.trustmaps.com>`_ that filters and
+searches Twitter streams according to an individual's Trust Map:
+
+.. raw:: html
+
+ <div class="center">
+ <a href="http://www.trustmap.org"><img src="http://img.skitch.com/20100714-x6qkxhr5ep41dsassuj987fwsc.medium.jpg"
+ /></a>
+ </div>
+
+Ampify will also support `Pecus
+<http://thruflo.com/2009/06/09/tav-describes-pecus.html>`_ -- which is intended
+as a foundation for a reputation economy. It'll enable those who share their
+works to be properly rewarded, e.g. open source developers, musicians, blog
+authors, youtube content creators, etc.
+
+.. raw:: html
+
+ <div class="center">
+ <a href="http://static.ampify.it/img.presentation-sample-screen.png"><img
+ src="http://static.ampify.it/img.presentation-sample-screen.png"
+ width="691px" height="518px" class="boxed"
+ /></a>
+ </div>
+
+This will be complemented by `Amp Creds
+<http://groups.google.com/group/espians/browse_thread/thread/c67452fb7d3afa9e>`_
+-- a global reference currency backed by Processing, Storage and Transfer --
+that will hopefully enable a more stable economy than the boom-and-bust cycles
+of the present one.
+
+Ampify will also enable a new form of decentralised collaboration through the
+use of the Confluence model. Here's a `MediaWiki-based prototype
+<http://socialstartuplabs.com/wiki/User:Tav>`_ that tested some of this idea
+[`source code <http://github.com/tav/confluence>`_]:
+
+.. raw:: html
+
+ <div class="center">
+ <a href="http://socialstartuplabs.com/wiki/User:Tav"><img src="http://img.skitch.com/20100714-qkm3athwabfcr6gkd786phk4ai.medium.jpg"
+ /></a>
+ </div>
+
+It's taken a lot of iterations and failures to figure out what works and what
+doesn't -- and I'm confident about having a working version of Ampify by
+October. There's already the start of `some documentation
+<http://ampify.it/planfile.html>`_ and you can `watch the GitHub repository
+<http://github.com/tav/ampify>`_ to follow the open development.
+
+.. raw:: html
+
+ <div class="center"><a href="http://static.ampify.it/img.ampify-overview.original.png"><img
+ src="http://static.ampify.it/img.ampify-overview.original.png" alt=""
+ width="691px" height="518px" class="boxed"
+ /></a></div>
+
+And, finally, your support will also enable my other `various open source
+contributions <http://github.com/tav>`_ and help put on events like `Social
+Startup Labs
+<http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010>`_ --
+which helps tackle the issue of jobs creation by helping local communities
+identify the needs and opportunities for `Social Businesses
+<http://en.wikipedia.org/wiki/Social_business>`_:
+
+.. raw:: html
+
+ <div class="center">
+ <a href="http://londoncreativelabs.squarespace.com/Social-Startup-Lab-15-06-2010"><img
+ src="http://farm5.static.flickr.com/4139/4743307216_94b6d2096b.jpg" class="boxed"
+ /></a>
+ </div>
+
+Do drop by and say hello on IRC chat if you're interested in any of this work:
+
+.. raw:: html
+
+ <div style="text-align: center; margin-top: 5px; margin-bottom: 15px">
+ <form action="http://webchat.freenode.net/" method="get">
+ <button style="padding: 2px 6px 3px;">Click to join #esp</button>
+ <input type="hidden" name="channels" value="esp" />
+ </form>
+ </div>
+
+ <pre>
+ server: irc.freenode.net
+ channel: #esp
+ chatlogs: <a href="http://irclogs.ampify.it">irclogs.ampify.it</a>
+ </pre>
+
+I believe my work adds real value and, with your support, I can get it to a
+stage where it could potentially make a substantially positive impact on
+society:
+
+* `Support my work with a PayPal contribution!
+ <https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GP9QRJAASDYJY>`_
+
+.. raw:: html
+
+ <div class="center">
+ <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
+ <input type="hidden" name="cmd" value="_s-xclick">
+ <input type="hidden" name="hosted_button_id" value="GP9QRJAASDYJY">
+ <input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
+ <img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
+ </form>
+ </div>
+
+Thank you.
\ No newline at end of file
|
tav/oldblog
|
c3f76eaa06aad326caf3531165df10537382f8ab
|
Added some margin for nested lists.
|
diff --git a/website/css/site.css b/website/css/site.css
index a146033..2073cf0 100644
--- a/website/css/site.css
+++ b/website/css/site.css
@@ -1,604 +1,608 @@
/*
* aaken default stylesheet -- by tav
*
*/
a {
color: #0000dd;
text-decoration: underline;
}
a:hover, a:active {
text-decoration: none;
}
body {
background-color: #fff;
font: 13px/19px Verdana;
font-family: Verdana, Arial, sans-serif;
margin: 0;
padding: 0;
text-align: center;
}
h1, h2, h3, h4, h5, h6 {
font-family: "Gill Sans", Verdana, Arial, sans-serif;
font-weight: normal !important;
font-size: 1.6em;
color: #0099cd;
color: #5e7c87;
margin-top: 1.5em;
margin-bottom: 1em;
clear: both;
}
h1 {
border-bottom: 1px solid #ccc;
font-size: 2em;
font-weight: bold;
padding-bottom: 0.5em;
}
h2 {
font-size: 1.6em;
padding-top: 0.2em;
}
h3 {
font-size: 1.7em;
margin-top: 2em;
}
pre {
background-color: #fff;
border: 1px solid #cacaca;
color: #101010;
font: 14px/1.4em "inconsolata-1", "inconsolata-2", Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
overflow: hidden;
padding: 7px 0 8px 7px;
margin: 10px 30px 0 30px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0px 0px 7px #cacaca;
}
pre:hover {
overflow: auto;
}
pre.ascii-art {
line-height: 1em;
}
pre code {
background-color: transparent;
border: 0;
padding: 0;
}
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
strong {
font-family: "museo-1", "museo-2", Verdana, Arial, sans-serif;
letter-spacing: 1px;
}
sup {
display: none;
}
+li ul {
+ margin-top: 10px;
+}
+
/* sections */
#content {
clear: both;
padding-left: 0px;
line-height: 1.8em;
margin-bottom: 1em;
}
#header {
background-color: #544554;
color: #fff;
}
#header h1 {
color: #fff;
}
#header h2 {
color: #fff;
line-height: 1.4em;
}
#header h1 a, #header h2 a {
color: #fff;
text-decoration: none;
}
#header h1 {
font-weight: bold;
}
#main {
text-align: left;
margin: 0px auto;
width: 810px;
}
/* rst classes */
.docinfo {
margin-left: 5px;
margin-top: 20px;
}
.abstract {
margin-top: 20px;
}
/*
.pre {
background-color: #dee;
}
.literal {
background-color: #dee;
padding: 3px;
}
*/
code, .literal {
background-color: #f0f0f0;
border: 1px solid #dadada;
padding: 1px 3px;
font-family: Monaco, "DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace;
font-size: 12px;
}
/*
.literal-block {
padding-left: 4em;
}
*/
.topic-title {
font-weight: bold;
text-align: center;
}
.note {
color: #aaa;
margin-left: 10px;
font-style: italic;
}
.attention {
background-color: #FFC3C3;
padding: 1.5em;
margin-top: 1em;
margin-bottom: 1em;
text-align: center;
}
.admonition-title {
display: none
}
.highlight {
text-align: center;
border: 1px solid #c00;
background-color: #fff;
background-color: #c00;
color: #fff;
padding: 5px;
}
/* rst error */
.system-messages {
display: none;
}
/* toc */
/*
.contents {
background-color: #fafafa;
border: 1px solid #ccc;
margin: 10px;
padding-left: 10px;
}
*/
.contents {
padding-left: 3em;
margin: 10px;
display: none;
}
/* sidebar */
.sidebar {
opacity: 0.9;
color: #e50000;
color: #0d5d04;
color: #a5504d;
background: white;
float: right;
position: absolute;
top: auto;
right: 40px;
margin: -1.5em 0.2em 0.2em 0.2em;
border: solid thin;
padding: 3px;
width: 180px;
text-align: center;
clear: both;
}
.sidebar-title {
text-decoration: underline;
text-align: center;
margin: 1px;
}
/* links */
a.fn-backref {
text-decoration: none;
}
a.footnote-reference {
vertical-align: super;
text-decoration: none;
}
/* tables */
table.docutils {
margin: 10px;
border-spacing: 0px;
border-width: 0 0 1px 1px;
border-style: solid;
border-color: #544554;
}
table.docutils thead tr th {
background-color: #ded0e8;
color: #544554;
padding: 5px;
border-top: 1px solid #544554;
border-right: 1px solid #544554;
border-left: 0px;
border-bottom: 0px;
}
table.docutils td {
padding: 5px;
border-width: 1px 1px 0 0;
border-style: solid;
border-color: #544554;
}
table.docutils tr td:first-child {
text-align: right;
}
table.footnote, table.citation {
border: 0px;
padding: 5px;
margin: 5px;
}
table.citation td, table.footnote td {
border: 0px;
}
table.docutils td p, table.footnote td p, table.citation td p {
margin-top: 0px;
padding-top: 0px;
}
table.footnote td.label, table.citation td.label {
width: 12em;
padding-right: 10px;
text-align: right;
}
table.citation td.label a, table.footnote td.label a {
font-style: italic;
text-decoration: none;
color: #333;
}
p.caption {
color: #666;
font-style: italic;
margin-top: 5px;
padding-left: 5px;
text-align: center;
}
td p.first {
margin-top: 0;
}
td p.last {
margin-bottom: 0;
}
th.field-name, th.docinfo-name {
text-align: right;
padding-right: 5px;
white-space: nowrap;
}
table.field-list {
border: 0px;
}
table.field-list td {
border: 0px;
vertical-align: top;
padding: 1px;
}
/* doctest */
.doctest-output {
color: #a5504d;
}
.doctest-input {
color: #0d5d04;
}
.doctest-output {
color: #a5504d;
color: #c32528;
}
.doctest-input {
color: #5d90cd;
color: #6a6a6a;
color: #00a33f;
color: #0d5d04;
}
/*
.doctest-block {
font-family: Monaco, "Bitstream Vera Sans Mono", "Courier New", Courier;
font-size: 1em;
}
*/
/* images */
img {
border: none;
vertical-align: top;
margin: 0;
padding: 0;
}
img.absmiddle {
vertical-align: middle;
}
/* lines */
hr {
noshade: noshade;
clear: both;
}
hr.clear {
clear: both;
height: 0;
width: 0;
margin: 0;
padding: 0;
color: #c00;
background-color: transparent;
border: 0px solid;
}
/* lists */
li {
margin-bottom: 10px;
}
/* utility classes */
.center {
text-align: center;
margin-top: 5px;
margin-bottom: 5px;
}
.hide {
display: none;
}
.float-left, .figure {
float: left;
padding: 5px;
margin-right: 12px;
border: 1px solid #ded0e8;
}
.figure {
width: 400px;
text-align: center;
}
.float-right {
float: right;
margin-left: 12px;
margin-bottom: 5px;
}
.image-caption {
font-style: italic;
text-align: right;
}
/*
border: 1px solid #ded0e8;
*/
/* special */
h1.title {
display: none;
}
#abstract .topic-title {
display: none;
}
#table-of-contents .topic-title {
display: none;
}
.sidebox {
background-color: #dee;
color: #222;
float: right;
font-size: 15px;
margin-left: 10px;
margin-top: 5px;
padding: 10px 15px;
text-align: left;
width: 175px;
}
.double-column {
column-count: 2;
column-gap: 1.5em;
}
p.first {
display: inline;
}
/* document specific rules */
div#rationale a.external {
color: #888;
}
#ignore-this {
display: none;
}
.post-title {
clear: both;
margin-top: 1em;
margin-bottom: 2em;
border-top: 1px dashed #444;
padding-top: 1.4em;
padding-bottom: 1em;
line-height: 2.3em;
}
.post-link {
margin-bottom: 0.7em;
}
.post-link a {
font-weight: normal;
color: #000;
text-decoration: none;
font-size: 2em;
}
.post-footer {
margin-bottom: 1em;
text-align: center;
}
.dulled {
color: #999;
font-style: italic;
}
.section-info {
padding-bottom: 1em;
border-bottom: 2px solid #544554;
margin-bottom: 1.5em;
margin-top: 1.2em;
}
.home-section-info {
margin-top: 1em;
text-align: right;
}
.right {
text-align: right;
}
.buffer {
margin-top: 6em;
}
.rss-entry { margin-bottom: 3em; }
.rss-entry .main, .feedburnerFeedBlock .main { font-size: 1.2em; padding: 25px; display: block; }
.feedburnerFeedBlock li {
list-style-type: none;
margin-bottom: 3em;
}
.feedburnerFeedBlock .headline {
display: none;
}
.section-header {
border-top: 3px solid #544554;
border-bottom: 3px solid #544554;
font-size: 2em;
text-align: center;
padding: 20px;
margin-bottom: 2em;
margin-top: 2em;
}
.index-link-info {
font-size: 0.8em;
color: #666;
}
.index-link-info a {
color: #666;
text-decoration: none;
}
.draft-article {
color: #ccc;
}
.friendfeed.widget {
border: 0px !important;
}
.friendfeed {
font: 13px/19px Verdana !important;
font-family: Verdana, Arial, sans-serif !important;
}
.friendfeed .entry {
padding: 0.5em !important;
}
.if-time-permits {
border: 1px solid #ff6633;
padding: 4px;
color: #999;
}
|
tav/oldblog
|
85d465afdc9ffaee73630f10e0ad6a2e421916ba
|
Saving some of the minor updates to the OAuth article.
|
diff --git a/oauth-3.0-the-sane-and-simple-way-to-do-it.txt b/oauth-3.0-the-sane-and-simple-way-to-do-it.txt
index 05c5551..d242d46 100644
--- a/oauth-3.0-the-sane-and-simple-way-to-do-it.txt
+++ b/oauth-3.0-the-sane-and-simple-way-to-do-it.txt
@@ -1,148 +1,310 @@
---
layout: post
license: Public Domain
---
===========================================
OAuth 3.0: The Sane and Simple Way To Do It
===========================================
.. raw:: html
<div class="float-right">
- <a href="http://pypy.org"><img
- src="http://pypy.org/image/pypy-logo.png" /></a>
+ <a href="http://oauth.net"><img
+ src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Oauth_logo.svg/150px-Oauth_logo.svg.png" /></a>
</div>
I'm a big fan of `OAuth <http://oauth.net/>`_ and I've done my fair share of
promoting it -- from writing various open source client libraries to
implementing services using it. However, the `OAuth 2.0 spec
<http://tools.ietf.org/html/draft-ietf-oauth-v2-08>`_ just takes the piss.
It's overly prescriptive, inconsistent and poorly written -- the worst that one
could hope for from an emerging standard. And it sucks so much that I've yet to
find a single conformant implementation by a major service provider.
Take Facebook. They boldly claim `OAuth 2.0 support
<http://developers.facebook.com/docs/authentication/>`_ and yet ignore most of
it:
* The spec states that the ``oauth_token`` parameter be used when accessing a
protected resource. Facebook use the ``access_token`` parameter name instead.
* The spec states that certain requests MUST include the client ``type`` and
``grant_type`` parameters. Facebook enforces no such requirement.
* The spec states that clients MUST be able to authenticate themselves using
both HTTP basic auth and URI query parameters. Facebook only support the
latter.
-I could go on, but I'm sure you get the picture. The irony here is that Facebook
-is actually one of the co-authors of the spec. And before anyone starts bashing
-Facebook for ignoring standards, please read `the latest draft of the spec
-<http://tools.ietf.org/html/draft-ietf-oauth-v2-08>`_ -- it should be a lot
-simpler.
+I could go on, but I'm sure you get the picture. The irony here is that `David
+Recordon <http://davidrecordon.com/>`_ from Facebook is actually one of the
+co-authors of the spec. And before anyone starts bashing Facebook for ignoring
+standards, please read `the latest draft of the spec
+<http://tools.ietf.org/html/draft-ietf-oauth-v2-08>`_ -- it is shockingly
+convoluted for such a simple thing like OAuth.
+
+.. more
As it is, what we're seeing is the emergence of incompatible and incomplete
implementations by service providers. And when even the whiz kids at GitHub have
`issues implementing OAuth 2.0
<http://support.github.com/discussions/api/28-oauth2-busy-developers-guide>`_,
it's time to re-evaluate the specification.
+Furthermore, while the spec goes on about rarely used `SAML assertions
+<http://en.wikipedia.org/wiki/Security_Assertion_Markup_Language#SAML_Assertions>`_,
+it fails to standardise for service discovery, client registration and
+management. Sites like Disqus and Ning make good use of Facebook's `Create
+Application API
+<http://wiki.developers.facebook.com/index.php/Create_Application_API>`_ -- it'd
+be nice if this was standardised!
+
+.. raw:: html
+
+ <div class="center">
+ <a href="http://wiki.developers.facebook.com/index.php/Create_Application_API"><img
+ src="http://img.skitch.com/20100629-1j8cf13m5669gg31mm86gfjc9j.png" /></a>
+ </div>
+
So, in the interest of simplifying life for developers everywhere, I hereby
-present OAuth 3.0 -- an alternative to the latest OAuth 2.0 draft. It is so
-simple that even an idiot like me could do a complete implementation in about
-100 lines of Python code:
+present OAuth 3.0 -- a more comprehensive alternative to the latest OAuth 2.0
+draft. It is so simple that even an idiot like me could do a complete
+implementation in about 200 lines of Python code:
* http://ampify.it/tentapp.html#oauth
-Anyways, let me know what you think. Especially if it can be made even simpler.
-Thanks!
+Anyways, let me know what you think -- especially if you've already experienced
+the pain of implementing OAuth. Thanks!
.. class:: block-section
**OAuth 3.0**
OAuth is a simple way for Client Applications to perform authorised actions on
behalf of a User on remote Service Providers.
-.. syntax:: coffeescript
-
- current_version: 3.0.0
-
**Service Discovery**
Service Providers announce their support for OAuth by publishing a
``/.well-known/oauth.json`` file on their website. This file lives inside the
-container directory introduced by `[RFC 5796]
+``.well-known`` directory introduced by `[RFC 5796]
<http://tools.ietf.org/html/rfc5785>`_ and is encoded in the JSON format `[RFC
4627] <http://tools.ietf.org/html/rfc4627>`_. So for a Service Provider
supporting OAuth 3.0:
.. syntax:: bash
$ curl https://www.serviceprovider.com/.well-known/oauth.json
We'd find something like:
.. syntax:: javascript
{
- "auth_endpoint": "https://www.serviceprovider.com/oauth/authorize",
- "management_endpoint": "https://www.serviceprovider.com/oauth/manage",
- "registration_endpoint": "https://www.serviceprovider.com/oauth/register",
+ "auth_endpoint": "http://www.serviceprovider.com/oauth/authorize",
+ "auth_management_endpoint": "https://www.serviceprovider.com/oauth/manage",
+ "client_terms": "http://www.serviceprovider.com/terms",
+ "client_management_endpoint": "https://www.serviceprovider.com/oauth/clients",
+ "reg_challenge": "sha-1:20:473dfb39-198e-4082-bac1-c00cb868e3c4",
+ "reg_endpoint": "https://www.serviceprovider.com/oauth/register",
"token_endpoint": "https://www.serviceprovider.com/oauth/token",
"version": "3.0.0"
}
-The JSON object could include other properties, but the following 5 string
+The JSON object could include other properties, but the following string
properties MUST be present:
-* The ``auth_endpoint`` defines the URI which Client Apps will direct a User to
- -- in order for them to authorize access.
+* The ``auth_endpoint`` defines the URL which Client Apps will direct a User to
+ -- in order for the User to authorize access.
+
+* The ``auth_management_endpoint`` defines the HTTPS URL where Users will be
+ able to manage the various applications that they have authorized.
-* The ``management_endpoint`` defines the URI to manage authorized Client Apps.
+* The ``client_terms`` defines the URL for the Service Provider's terms of use
+ and policies for Client Apps.
-* The ``registration_endpoint`` defines the URI to register Client Apps with the
- Service Provider.
+* The ``client_management_endpoint`` defines the HTTPS URL where Users will be
+ able to manage the various Client Apps that they have registered.
-* The ``token_endpoint`` defines the Token Endpoint URI which a Client App will
- communicate with -- in order to get or refresh an authorized access token.
- This MUST be a secure channel, e.g. an HTTPS URL.
+* The ``reg_challenge`` defines a hashcash challenge spec for apps to use when
+ registering clients programmatically. This MUST be of the format
+ ``<hash-algorithm>:<hashcash-bits>:<uuid>``.
+
+* The ``reg_endpoint`` defines the HTTPS URL where Client Apps will be able to
+ register with the Service Provider.
+
+* The ``token_endpoint`` defines the HTTPS URL that Client Apps will communicate
+ with -- in order to get or refresh an authorized access token.
* The ``version`` defines the `Semantic Version <http://semver.org/>`_ of the
OAuth Protocol that the Service Provider is currently supporting.
+ .. syntax:: coffeescript
+
+ current_version: "3.0.0"
+
+**API Overview**
+
+Except for HTTP redirects, all communication between Client Apps and Service
+Providers MUST take place over HTTPS connections -- this is vital for security.
+There are four OAuth-specific APIs exposed at the following Service Provider
+endpoints:
+
+* ``auth_management_endpoint``
+* ``client_management_endpoint``
+* ``reg_endpoint``
+* ``token_endpoint``
+
+They accept URL-encoded parameters via HTTP GET or POST with the
+``application/x-www-form-urlencoded`` content type and all successful calls
+return a JSON encoded response with a ``200 OK`` HTTP status code and
+``application/json`` content type.
+
+Unsuccessful calls will have either ``4xx`` or ``5xx`` HTTP status codes and
+these may or may not have JSON-encoded error responses -- this can be determined
+by looking for ``application/json`` in the ``content-type`` response header.
+
+The structure of the JSON-encoded error responses is not standardised beyond the
+required presence of an ``error`` property. This property can be of arbitrary
+type and can be accompanied by other properties, e.g.
+
+.. syntax:: javascript
+
+ {
+ "error": "The client_secret parameter was not specified.",
+ "error_type": "ValueError"
+ }
+
+Or perhaps something like:
+
+.. syntax:: javascript
+
+ {
+ "error": {
+ "type": "InvalidClientCredentials",
+ "message": "Matching client credentials could not be found."
+ }
+ }
+
+It is left up to the Service Providers to be as helpful or unhelpful as they
+desire to be with their error responses.
+
**Client Registration**
-Of the format ``<hash-algorithm>:<hashcash-bits>:<token>``, e.g.
+Client Apps register with the Service Provider via the ``reg_endpoint``. This
+could be done either manually or programmatically. Manual registration involves
+the app developer authenticating with the Service Provider and then visiting the
+``reg_endpoint`` using their browser.
+
+Alternatively, it could be done programmatically by POSTing to the
+``reg_endpoint`` which accepts the following parameters:
+
+* ``name`` -- the name of the Application being registered. [required]
+
+* ``website_url`` -- the website for the Application. [required]
+
+* ``description`` -- a brief description of the Application. [optional]
+
+* ``hashcash`` -- a valid hashcash payment for registering with the Service
+ Provider. [required]
+
+* ``redirect_url`` -- where to redirect requests.
+
+ * If the Client App will never be making OAuth requests of the ``user_agent``
+ type, then this parameter is optional.
+
+ * Otherwise, it is required and should be HTTPS.a
+
+And responds with a JSON object with the following string properties:
+
+* ``client_id`` --
+
+* ``client_secret``
+
+So, for example, if one did:
+
+.. syntax:: bash
+
+ $ curl -d 'name=Awesome%20App' -d 'url=http%3A//www.awesomeapp.com' \
+ -d 'description=This%20lets%20you%20do%20awesome%20things' \
+ -d 'hashcash=' \
+ https://www.serviceprovider.com/oauth/register
+
+Then a successful response would look something like:
.. syntax:: javascript
{
- "challenge": "sha-1:20:473dfb39-198e-4082-bac1-c00cb868e3c4"
+ "client_id": "c6cbeb7f4ede64c1615ff2d27307030f9612",
+ "client_secret": "4d1e7bd053385838838d5c2dea60b531a2c7"
}
-The following:
+The ``:client_registration`` scope.
+A data structure like the following is recommended:
.. syntax:: python
- def generate_hashcash(token, bits=20, hash=sha1):
- n = 0
- return hashcash
+ class OAuthClient(db.Model):
+ created = db.DateTimeProperty()
+ name = db.StringProperty()
+ description = db.TextProperty()
+ website = db.StringProperty()
+ redirect = db.StringProperty()
+ owner = db.StringProperty(default='@anonymous')
+ secret = db.StringProperty()
+
+And, for the love of the Gods of SGML, please escape the angle brackets and
+related characters when displaying client-provided data to end users, e.g.
+
+.. syntax:: python
+
+ def escape(s)
+ return s.replace("&", "&").replace("<", "<").replace(
+ ">", ">").replace('"', """)
+
+
+**App Request**
+
+.. syntax:: python
+
+ def authorize(
+ client_id, redirect_uri, scope, state=None, request_type='application'
+ ) -> HTTPRedirect
+
+
+
+Scopes beginning with ``:`` are for use by the OAuth-protocol related API calls.
+Two have already been defined:
+
+* ``:auth_management```
+* ``:client_management```
+* ``:client_registration``
+
+Service Providers MUST not define such colon-prefixed scopes for their own use
+as they're reserved for future versions of the OAuth protocol.
+
+**User Agent**
+
+And:
+
+.. syntax:: javascript
+
+ var randomString = (Math.random() * 0x100000000).toString(16);
+ document.cookie = 'expectedState=' + randomString;
A timing-independent string comparison mechanism should be used so as to avoid
`timing attacks
<http://rdist.root.org/2009/05/28/timing-attack-in-google-keyczar-library/>`_:
.. syntax:: python
def constant_time_string_compare(s1, s2, ord=ord):
- """Return whether two strings are equal -- without being a timing oracle."""
+ """Return whether two strings are equal."""
if len(s1) != len(s2):
return False
total = 0
for x, y in zip(s1, s2):
total |= ord(x) ^ ord(y)
return total == 0
|
tav/oldblog
|
c171153e9a429f52026701d10717d6cc5bfcd22b
|
Fixed the logical awesome image.
|
diff --git a/4-features-to-make-github-an-awesome-platform.txt b/4-features-to-make-github-an-awesome-platform.txt
index b89599a..d303149 100644
--- a/4-features-to-make-github-an-awesome-platform.txt
+++ b/4-features-to-make-github-an-awesome-platform.txt
@@ -1,205 +1,205 @@
---
created: 2010-04-07, 07:27
layout: post
license: Public Domain
---
=============================================
4 Features To Make GitHub An Awesome Platform
=============================================
.. raw:: html
<div class="float-right">
<a href="http://github.com"><img
- src="http://logicalawesome.com/logical_awesome.jpg"
+ src="http://img.skitch.com/20100628-t3uk9g8baf27y6rjpgigkk88bj.jpg"
width="375px" height="300px" /></a>
</div>
I love `GitHub <http://github.com>`_. They make it fun and easy to get involved
with open source projects!
By recognising `coding as a social endeavour
<http://www.espians.com/getting-started-with-git.html>`_, they've possibly even
changed the very nature of open source development.
But as great as they are, there's not much of a "GitHub ecosystem". In
comparison to say Twitter apps, the number of GitHub apps are few and far
between.
Wouldn't it be great if we could build our own apps like wikis on top of GitHub
repositories?
Perhaps someone would create a peer-to-peer publishing platform or perhaps a web
app which stores plain text data in public repos instead of in opaque databases?
I believe GitHub has the potential to become a truly awesome platform. They
already have a `decent API <http://develop.github.com/>`_ -- imagine what would
be possible if it supported the following features:
.. more
.. raw:: html
<hr class="clear" />
* **API to Update The Repository via HTTP**
Back in 2008, I managed to get my girlfriend to use GitHub. The poor girl
heroically struggled through with Git on the command line before eventually
giving up after a few months.
The fact is, most people are more comfortable using web apps than with command
line tools. It'd be awesome to let them benefit from Git without having to
expose them to the command line.
It'd also be nice for developers if GitHub exposed functionality to modify
files in a repository over HTTP instead of having to resort to libraries like
`grit <http://grit.rubyforge.org/>`_ and `dulwich
<http://github.com/jelmer/dulwich>`_. This would make it much easier to
develop web apps leveraging Git.
GitHub already has support for editing files from the web browser by POST-ing
to ``/:user/:repo/tree-save/:branch/:path`` -- it'd be cool if they could
just expose this via an API:
.. syntax:: text
/tree/save/:user/:repo/:branch/:path
This should take 6 parameters and return the new commit ID:
.. syntax:: text
parents => The IDs of the parent commits [optional]
data => The updated content for the specified path
mode => The new mode for the blob [defaults to 100644]
message => The commit message
committer => The committer [defaults to the authenticated user]
author => The commit author [defaults to the committer]
There should be a complementary API for deleting files:
.. syntax:: text
/tree/remove/:user/:repo/:branch/:path
And, most importantly, an API for creating new files with the same parameters
as ``/tree/save``:
.. syntax:: text
/tree/add/:user/:repo/:branch/:path
It would be nice to have a utility API call for renaming files too:
.. syntax:: text
/tree/rename/:user/:repo/:branch/:path
Which would only have to specify 5 parameters:
.. syntax:: text
parent => The ID of the parent commit [optional]
new_path => The new path for the blob at :path
message => The commit message
committer => The committer [defaults to the authenticated user]
author => The commit author [defaults to the committer]
All the above API calls should result in the ``:branch`` ref being updated to
point to the new commit ID and create a new ref where the branch didn't
previously exist.
* **API to Access Compare Views**
GitHub has wicked support for doing code reviews via what they call `compare
views <http://github.com/blog/612-introducing-github-compare-view>`_. This
feature allows one to see the commits, diffs and comments between any 2 refs.
You have to see it in action to realise how awesome this is:
http://github.com/jquery/jquery/compare/omgrequire
Unfortunately, this feature is not exposed via the API in any way. It would be
very cool to be able to access it:
.. syntax:: text
/compare/:user/:repo/[:startRef...]:endRef
That should return the commits, diffs and comments for the commit range. That
is, everything necessary to recreate the GitHub compare view.
* **API to Manage Service Hooks**
GitHub already supports extension via `post-receive hooks
<http://help.github.com/post-receive-hooks/>`_. This allows you to register
URLs as `web hooks <http://webhooks.pbworks.com/>`_ for any repository. GitHub
will POST to these URLs with JSON data whenever someone does a ``git push`` to
the repository.
It makes it very easy to do things in response to changes to your
repositories. I've already found it very useful for everything from triggering
build slaves to notifying IRC channels via `gitbot.py
<http://github.com/tav/scripts/blob/master/gitbot.py>`_ -- which in turn even
triggers regeneration of this blog!
Unfortunately it's a real pain to get users to edit their service hooks. It'd
be great if applications could do this on a user's behalf. The API could be
extended to list all service hooks:
.. syntax:: text
/repos/hooks/:user/:repo
It should be very easy to add and remove hooks:
.. syntax:: text
/repos/hooks/:user/:repo/add
/repos/hooks/:user/:repo/remove
Which would take a single POST-ed parameter:
.. syntax:: text
url => The post-receive URL
This tiny feature would make it a lot more attractive for application
developers as it would make building apps integrated with GitHub very easy!!
* **A Way to Pay for API Use**
GitHub currently specifies `API limits
<http://develop.github.com/p/general.html#limitations>`_ of 60 requests per
minute. This works out as a generous 86,400 requests/day per user. But as an
application developer I'd rather not be limited. In fact, seeing as GitHub
already has my billing details, I'd be quite happy to pay something like $20
per million requests -- which should more than cover the bandwidth costs.
I'm quite confident that interesting applications could be built using the API
which would lead to productivity increases which would more than make up for
the cost. To facilitate this, billing would need to be enabled and the
`authentication <http://develop.github.com/p/general.html>`_ extended with:
.. syntax:: text
api_key => The API key for the developer
signature => The signature for the API request
The ``signature`` would be derived by HMAC-ing the request parameters with a
shared ``api_secret_key`` corresponding to the ``api_key``. This would be used
to bypass limits and bill for the API requests whereas the existing ``login``
and ``token`` parameters would be used for the authentication.
Given GitHub's `impressive infrastructure
<http://github.com/blog/530-how-we-made-github-fast>`_ and talent, it should be
relatively easy for them to add these 4 small features. But like any group of
hackers, they need to be convinced that it'd be worthwhile adding these
features.
Perhaps you could ask them for these features? Perhaps you could leave a comment
with what kind of awesome apps you would create with these features in place? Or
perhaps just follow me on GitHub: `github.com/tav <http://github.com/tav>`_.
In any case, let me know what you think. Thanks!
\ No newline at end of file
|
tav/oldblog
|
673986d8340495264fc5b5bed73a660a990558fe
|
Added a follow me footer to the blog posts.
|
diff --git a/_layouts/post.genshi b/_layouts/post.genshi
index a3d641f..773bb44 100644
--- a/_layouts/post.genshi
+++ b/_layouts/post.genshi
@@ -1,79 +1,94 @@
---
layout: site
license: Public Domain
---
<div xmlns:py="http://genshi.edgewall.org/">
<?python
from time import time
from operator import lt
from posixpath import splitext
from urllib import urlencode
STATIC = 'http://cloud.github.com/downloads/tav/plexnet'
page_url = disqus_url = 'http://tav.espians.com/' + __name__
if defined('created') and lt(created[:7], "2009-07"):
disqus_url = 'http://www.asktav.com/' + __name__
MONTHS = [
'Zero Month',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
?>
<div class="article-nav">
</div>
<div class="article-title">
<div class="post-link"><a href="${__name__}">${Markup(title)}</a></div>
<div class="additional-content-info">
<!-- <script language="javascript" type="text/javascript">
SHARETHIS.addEntry({
title:"${page_title.replace('"', r'\"')}",
url:'${page_url}',
}, {button:true});
</script>| --><a href="#disqus_thread" rel="disqus:${disqus_url}">Add a Comment</a>
<script type="text/javascript">
tweetmeme_url = '${page_url}';
tweetmeme_source = 'tav';
tweetmeme_service = 'bit.ly';
tweetmeme_style = 'compact';
</script>
| <div class="retweetbutton">
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
</div>
<div class="article-info">
» by <a href="http://tav.espians.com">tav</a><span py:if="defined('created')"> on <span class="post-date">${MONTHS[int(created[5:7])]} ${int(created[8:10])}, ${created[:4]} @ <a href="http://github.com/tav/blog/commits/master/${splitext(__name__)[0]}.txt">${created[-5:]}</a></span></span> <a href="http://creativecommons.org/publicdomain/zero/1.0/"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Cc-pd.svg/64px-Cc-pd.svg.png" width="20px" height="20px" alt="Public Domain" class="absmiddle" /></a>
</div>
</div>
<div py:if="not defined('created')" class="attention">
This is an early draft. Many sections are incomplete. A lot more is being written.
</div>
<div id="content">
<div py:content="Markup(content)"></div>
</div>
<br /><hr class="clear" />
+<div class="footer-info">
+ <a class="float-right" href="http://twitter.com/tav"><img
+ src="http://a3.twimg.com/profile_images/463199849/gfx.espra.profile.tav_bigger.jpg"
+ /></a>
+ If you found this article interesting, then do:
+ <div class="footer-info-block">
+ <a href="http://feeds.feedburner.com/asktav" rel="alternate"
+ type="application/rss+xml" title="Subscribe to the Asktav Blog"><img
+ src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png" /></a> <a
+ href="http://feeds.feedburner.com/asktav" rel="alternate"
+ type="application/rss+xml" title="Subscribe to the Asktav Blog">Subscribe to this Blog</a> <a href="http://twitter.com/tav" title="Follow @tav on Twitter"><img src="http://cloud.github.com/downloads/tav/plexnet/gfx.icon.twitter.png" /></a> <a href="http://twitter.com/tav" title="Follow @tav on Twitter">Follow me on Twitter</a> <a href="http://github.com/tav" title="Follow @tav on GitHub"><img src="http://cloud.github.com/downloads/tav/plexnet/gfx.icon.github.png" /></a> <a href="http://github.com/tav" title="Follow @tav on GitHub">Follow me on GitHub</a>
+ </div>
+ <div style="text-align: right;">— Cheers, tav.</div>
+ <hr class="clear" />
+</div>
<div class="article-nav" style="margin-bottom: 1.5em;">
<script type="text/javascript">
ARTICLE_NAME = '${__name__}';
</script>
<script type="text/javascript" src="index.js?${int(time()/4)}" />
</div>
<div id="disqus-comments-section">
<script type="text/javascript">
disqus_url = "${disqus_url}";
disqus_title = "${Markup(title)}";
</script>
<div id="disqus_thread"></div><script type="text/javascript"
src="http://disqus.com/forums/${site_nick}/embed.js"></script><noscript><a
href="http://${site_nick}.disqus.com/?${urlencode({'url': disqus_url})}">View the forum
thread.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">Comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
<div><br /><br /></div>
</div>
diff --git a/_layouts/site.genshi b/_layouts/site.genshi
index 77c5368..098713c 100644
--- a/_layouts/site.genshi
+++ b/_layouts/site.genshi
@@ -1,178 +1,178 @@
---
license: Public Domain
---
<!DOCTYPE html>
<html xmlns:py="http://genshi.edgewall.org/">
<?python
STATIC = 'http://cloud.github.com/downloads/tav/plexnet'
page_url = 'http://tav.espians.com/' + __name__
?>
<head>
<title>${Markup(site_title)}<py:if test="defined('title')"> » ${Markup(title)}</py:if></title>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<meta name="tweetmeme-title" content="${Markup(title)}" />
<!-- disable some internet explorer features -->
<meta http-equiv="imagetoolbar" content="no" />
<meta name="MSSmartTagsPreventParsing" content="true" />
<!-- meta elements (search engines) -->
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<!-- meta elements (page data) -->
<meta name="author" content="${site_author}" />
<meta name="description" content="${site_description}" />
<meta name="copyright" content="This work has been placed into the Public Domain." />
<meta name="document-rating" content="general" />
<meta http-equiv="content-language" content="en" />
<link rel="icon" type="image/png" href="${STATIC}/gfx.aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
- href="http://feeds2.feedburner.com/${site_nick}" />
+ href="http://feeds.feedburner.com/${site_nick}" />
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="css/site.css" />
<style type="text/css" media="print">
/* @import url("${STATIC}/css.print.css"); */
#ignore-this { display: none; }
</style>
<style type="text/css">
.ascii-art .literal-block {
line-height: 1em !important;
}
.cmd-line {
background-color: #000;
color: #fff;
padding: 5px;
margin-left: 2em;
margin-right: 2em;
}
.cmd-ps1 {
color: #999;
}
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
</style>
<![endif]-->
<!-- javascript -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" />
<script type="text/javascript">
GOOGLE_ANALYTICS_CODE = "${site_analytics_code}";
DISQUS_FORUM = '${site_nick}';
PAGE_URI = '${page_url}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
</script>
<script type="text/javascript" src="http://use.typekit.com/hdt8sni.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="${STATIC}/js.init.js" />
<!-- <script type="text/javascript"
src="http://w.sharethis.com/button/sharethis.js#tabs=web%2Cpost%2Cemail&charset=utf-8&style=rotate&publisher=65b4c59a-e069-4896-84b4-7d8d7dce2b77&headerbg=%230099cd&linkfg=%230099cd"></script> -->
</head>
<body>
<div id="main">
<div id="site-header">
<div id="site-info">
<a href="/" title="Asktav: A Blog by Tav"><img
id="site-logo" src="${STATIC}/gfx.logo.asktav.png" alt="Aaken Logo" width="64px" height="64px" /></a><form id="translation_form" class="menu-item-padding"><select id="lang_select" onchange="dotranslate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form><a href="/" class="menu-item"
title="${site_title}">Asktav Home</a><a href="archive.html" class="menu-item"
title="Site Index">Archives</a><a class="menu-item"
title="About Tav"
href="about-${site_author.lower()}.html">About
${site_author.title()}</a><a class="menu-item-final"
href="http://twitter.com/tav" title="Follow @tav" style="margin-right: 5px;"><img
src="${STATIC}/gfx.icon.twitter.png" alt="Follow @tav on Twitter"
class="absmiddle" /></a><a href="http://friendfeed.com/tav" style="margin-right: 5px;"
title="Follow tav on FriendFeed"><img src="${STATIC}/gfx.icon.friendfeed.png"
alt="FriendFeed" class="absmiddle" /></a><a
style="margin-right: 5px;"
href="http://github.com/tav" title="Follow tav on GitHub"><img
src="${STATIC}/gfx.icon.github.png" alt="GitHub" class="absmiddle"
/></a><a style="margin-right: 5px;"
href="http://www.facebook.com/asktav"
title="Follow Tav on Facebook"><img src="${STATIC}/gfx.icon.facebook.gif"
alt="Facebook" class="absmiddle" /></a><a
- href="http://feeds2.feedburner.com/${site_nick}" rel="alternate"
+ href="http://feeds.feedburner.com/${site_nick}" rel="alternate"
type="application/rss+xml" title="Subscribe to the RSS Feed"><img
alt="RSS Feed" class="absmiddle"
src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png"
/></a><div
style="margin-top: 7px; font-family: Monaco,Courier New;"></div>
<hr class="clear" />
</div>
</div>
<div>${Markup(content)}</div>
</div>
</body>
</html>
diff --git a/website/css/site.css b/website/css/site.css
index 78f9fc0..a146033 100644
--- a/website/css/site.css
+++ b/website/css/site.css
@@ -479,512 +479,521 @@ h1.title {
width: 175px;
}
.double-column {
column-count: 2;
column-gap: 1.5em;
}
p.first {
display: inline;
}
/* document specific rules */
div#rationale a.external {
color: #888;
}
#ignore-this {
display: none;
}
.post-title {
clear: both;
margin-top: 1em;
margin-bottom: 2em;
border-top: 1px dashed #444;
padding-top: 1.4em;
padding-bottom: 1em;
line-height: 2.3em;
}
.post-link {
margin-bottom: 0.7em;
}
.post-link a {
font-weight: normal;
color: #000;
text-decoration: none;
font-size: 2em;
}
.post-footer {
margin-bottom: 1em;
text-align: center;
}
.dulled {
color: #999;
font-style: italic;
}
.section-info {
padding-bottom: 1em;
border-bottom: 2px solid #544554;
margin-bottom: 1.5em;
margin-top: 1.2em;
}
.home-section-info {
margin-top: 1em;
text-align: right;
}
.right {
text-align: right;
}
.buffer {
margin-top: 6em;
}
.rss-entry { margin-bottom: 3em; }
.rss-entry .main, .feedburnerFeedBlock .main { font-size: 1.2em; padding: 25px; display: block; }
.feedburnerFeedBlock li {
list-style-type: none;
margin-bottom: 3em;
}
.feedburnerFeedBlock .headline {
display: none;
}
.section-header {
border-top: 3px solid #544554;
border-bottom: 3px solid #544554;
font-size: 2em;
text-align: center;
padding: 20px;
margin-bottom: 2em;
margin-top: 2em;
}
.index-link-info {
font-size: 0.8em;
color: #666;
}
.index-link-info a {
color: #666;
text-decoration: none;
}
.draft-article {
color: #ccc;
}
.friendfeed.widget {
border: 0px !important;
}
.friendfeed {
font: 13px/19px Verdana !important;
font-family: Verdana, Arial, sans-serif !important;
}
.friendfeed .entry {
padding: 0.5em !important;
}
.if-time-permits {
border: 1px solid #ff6633;
padding: 4px;
color: #999;
}
.if-time-permits:before {
content: "IF TIME PERMITS";
background-color: #ff6633;
color: #fff;
padding: 5px;
margin-right: 3px;
margin-top: 3px;
}
#translation_form {
display: inline;
}
.menu-item {
padding-left: 0.5em;
padding-right: 0.5em;
border-left: 1px solid #000;
}
.menu-item-left {
padding-left: 0.5em;
padding-right: 0.5em;
border-left: 1px solid #000;
}
.menu-item-final {
padding-left: 0.5em;
border-left: 1px solid #000;
}
.menu-item-padding {
padding-right: 0.5em;
}
.dsq-record-img {
vertical-align: middle;
text-decoration: none;
}
#dsq-content a {
text-decoration: none;
}
#dsq-comments a, #dsq-content > p a {
text-decoration: underline;
}
#dsq-comments a:hover, #dsq-content > p a:hover {
text-decoration: none;
}
a.button {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
}
a.button span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
}
a.button:active {
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.button:active span {
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
a.buttondown {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_a.gif') no-repeat scroll top right;
color: #444;
display: block;
float: left;
font: normal 12px arial, sans-serif;
height: 24px;
margin-right: 6px;
padding-right: 18px; /* sliding doors padding */
text-decoration: none;
background-position: bottom right;
color: #000;
outline: none; /* hide dotted outline in Firefox */
}
a.buttondown span {
background: transparent url('http://cloud.github.com/downloads/tav/plexnet/gfx.bg_button_span.gif') no-repeat;
display: block;
line-height: 14px;
padding: 5px 0 5px 18px;
background-position: bottom left;
padding: 6px 0 4px 18px; /* push text down 1px */
}
.tag-segment {
text-align: right;
}
.tag-segment span {
color: #fff;
padding: 0.5em;
font-size: 0.7em;
}
.tag-link {
text-decoration: none;
color: #000;
}
.tag {
background-color: #696969;
}
.tag-val-done {
background-color: #007f16;
background-color: #00782d;
background-color: #006400;
}
.tag-val-needsreview {
background-color: #a4ff00;
color: #000 !important;
}
.tag-val-inreview {
background-color: #3056bf;
}
.tag-val-todo {
background-color: #a60c00;
background-color: #d0006e;
background-color: #8B0000;
}
.tag-val-wip {
background-color: #a66e00;
background-color: #ff550f;
}
.tag-type-1 {
}
.tag-type-2 { /* #hashtags */
background-color: #2a4580;
background-color: #696969;
}
.tag-type-dep {
display: none;
}
.tag-type-milestone {
background-color: #00008B;
background-color: #06276f;
background-color: #a4ff00; /* nice colour! */
/* color: #000 !important; */
background-color: #002ca6;
background-color: #3056bf;
background-color: #898989;
}
.tag-type-priority {
background-color: #481254;
}
.tag-type-zuser {
background-color: #4573d5;
background-color: #696969;
}
#plan-tags a, #site-tags a {
margin-bottom: 0.7em;
}
#plan-container {
margin-top: 1.2em;
margin-bottom: 2.4em;
}
.plan-help {
font-size: 0.9em;
font-weight: bold;
text-align: right;
margin-bottom: 1.4em;
}
.retweetbutton { vertical-align: middle; display: inline; }
.retweetbutton iframe { vertical-align: middle; padding-bottom: 5px; }
#epigraph {
margin: 22px 40px;
color:#575757;
padding: 0 50px;
background: transparent url("http://cloud.github.com/downloads/tav/plexnet/gfx.blockquote.gif") no-repeat 0 0;
}
#epigraph-attribution {
text-align: right;
}
#dsq-content h3 {
margin-bottom: 1em !important;
padding: 0.4em;
font-size: 1.4em;
background-color: #544554;
color: #fff;
text-align: right;
}
#main {
width: 700px;
}
#site-header {
border-bottom: 1px dashed #444;
}
#site-logo {
float: left;
margin-right: 0.5em;
}
#site-info {
padding-top: 0.5em;
padding-bottom: 0.5em;
text-align: right;
}
#site-welcome {
font-size: 1.4em;
margin-top: 1em;
}
.article-title {
margin-top: 0.3em;
margin-bottom: 2.5em;
padding-bottom: 0.3em;
padding-top: 0.7em;
line-height: 2.3em;
}
.article-info {
font-size: 1em;
}
.additional-content-info {
float: right;
}
.attention {
background-color: #bfeeff;
}
.sidebox {
background-color: #bfeeff;
}
.more-link { display: none; }
.block-section {
border-top: 1px dashed #666;
margin-top: 20px;
padding-top: 20px;
}
/* Source code syntax highlighting */
.syntax .c { color: #919191 } /* Comment */
.syntax .cm { color: #919191 } /* Comment.Multiline */
.syntax .cp { color: #919191 } /* Comment.Preproc */
.syntax .cs { color: #919191 } /* Comment.Special */
.syntax .c1 { color: #919191 } /* Comment.Single */
.syntax .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.syntax .g { color: #101010 } /* Generic */
.syntax .gd { color: #d22323 } /* Generic.Deleted */
.syntax .ge { color: #101010; font-style: italic } /* Generic.Emph */
.syntax .gh { color: #101010 } /* Generic.Heading */
.syntax .gi { color: #589819 } /* Generic.Inserted */
.syntax .go { color: #6a6a6a } /* Generic.Output */
.syntax .gp { color: #6a6a6a } /* Generic.Prompt */
.syntax .gr { color: #d22323 } /* Generic.Error */
.syntax .gs { color: #101010 } /* Generic.Strong */
.syntax .gt { color: #d22323 } /* Generic.Traceback */
.syntax .gu { color: #101010 } /* Generic.Subheading */
.syntax .k { color: #c32528 } /* Keyword */ /* espian red */
.syntax .k { color: #ff5600 } /* Keyword */ /* orangy */
.syntax .kc { color: #ff5600 } /* Keyword.Constant */
.syntax .kd { color: #ff5600 } /* Keyword.Declaration */
.syntax .kd { color: #ff5600 } /* Keyword.Declaration */
.syntax .kn { color: #ff5600 } /* Keyword */
.syntax .kp { color: #ff5600 } /* Keyword.Pseudo */
.syntax .kr { color: #ff5600 } /* Keyword.Reserved */
.syntax .kt { color: #ff5600 } /* Keyword.Type */
.syntax .l { color: #101010 } /* Literal */
.syntax .ld { color: #101010 } /* Literal.Date */
.syntax .m { color: #3677a9 } /* Literal.Number */ /* darkish pastely blue */
.syntax .m { color: #00a33f } /* Literal.Number */ /* brightish green */
.syntax .m { color: #1550a2 } /* Literal.Number */ /* darker blue */
.syntax .m { color: #5d90cd } /* Literal.Number */ /* pastely blue */
.syntax .mf { color: #5d90cd } /* Literal.Number.Float */
.syntax .mh { color: #5d90cd } /* Literal.Number.Hex */
.syntax .mi { color: #5d90cd } /* Literal.Number.Integer */
.syntax .il { color: #5d90cd } /* Literal.Number.Integer.Long */
.syntax .mo { color: #5d90cd } /* Literal.Number.Oct */
.syntax .bp { color: #a535ae } /* Name.Builtin.Pseudo */
.syntax .n { color: #101010 } /* Name */
.syntax .na { color: #bbbbbb } /* Name.Attribute */
.syntax .nb { color: #bf78cc } /* Name.Builtin */ /* pastely purple */
.syntax .nb { color: #af956f } /* Name.Builtin */ /* pastely light brown */
.syntax .nb { color: #a535ae } /* Name.Builtin */ /* brightish pastely purple */
.syntax .nc { color: #101010 } /* Name.Class */
.syntax .nd { color: #6d8091 } /* Name.Decorator */
.syntax .ne { color: #af956f } /* Name.Exception */
.syntax .nf { color: #3677a9 } /* Name.Function */
.syntax .nf { color: #1550a2 } /* Name.Function */
.syntax .ni { color: #101010 } /* Name.Entity */
.syntax .nl { color: #101010 } /* Name.Label */
.syntax .nn { color: #101010 } /* Name.Namespace */
.syntax .nn { color: #101010 } /* Name.Namespace */
.syntax .no { color: #101010 } /* Name.Constant */
.syntax .nx { color: #101010 } /* Name.Other */
.syntax .nt { color: #6d8091 } /* Name.Tag */
.syntax .nv { color: #101010 } /* Name.Variable */
.syntax .vc { color: #101010 } /* Name.Variable.Class */
.syntax .vg { color: #101010 } /* Name.Variable.Global */
.syntax .vi { color: #101010 } /* Name.Variable.Instance */
.syntax .py { color: #101010 } /* Name.Property */
.syntax .o { color: #ff5600 } /* Operator */ /* orangy */
.syntax .o { color: #101010 } /* Operator */
.syntax .ow { color: #101010 } /* Operator.Word */
.syntax .p { color: #101010 } /* Punctuation */
.syntax .s { color: #dd1144 } /* Literal.String */ /* darkish red */
.syntax .s { color: #c32528 } /* Literal.String */ /* espian red */
.syntax .s { color: #39946a } /* Literal.String */ /* pastely greeny */
.syntax .s { color: #5d90cd } /* Literal.String */ /* pastely blue */
.syntax .s { color: #00a33f } /* Literal.String */ /* brightish green */
.syntax .sb { color: #00a33f } /* Literal.String.Backtick */
.syntax .sc { color: #00a33f } /* Literal.String.Char */
.syntax .sd { color: #00a33f } /* Literal.String.Doc */
.syntax .se { color: #00a33f } /* Literal.String.Escape */
.syntax .sh { color: #00a33f } /* Literal.String.Heredoc */
.syntax .si { color: #00a33f } /* Literal.String.Interpol */
.syntax .sr { color: #00a33f } /* Literal.String.Regex */
.syntax .ss { color: #00a33f } /* Literal.String.Symbol */
.syntax .sx { color: #00a33f } /* Literal.String.Other */
.syntax .s1 { color: #00a33f } /* Literal.String.Single */
.syntax .s2 { color: #00a33f } /* Literal.String.Double */
.syntax .w { color: #101010 } /* Text.Whitespace */
.syntax .x { color: #101010 } /* Other */
.syntax.bash .nb { color: #101010 }
.syntax.bash .nv { color: #c32528 }
.syntax.css .k { color: #606060 }
.syntax.css .nc { color: #c32528 }
.syntax.css .nf { color: #c32528 }
.syntax.css .nt { color: #c32528 }
.syntax.rst .k { color: #5d90cd }
.syntax.rst .ow { color: #5d90cd }
.syntax.rst .p { color: #5d90cd }
.syntax.yaml .l-Scalar-Plain { color: #5d90cd }
.syntax.yaml .p-Indicator { color: #101010 }
+.footer-info {
+ border-top: 1px dotted #999;
+ border-bottom: 1px dotted #999;
+ padding: 10px 0;
+}
+
+.footer-info-block {
+ padding: 13px 10px 10px 17px;
+}
\ No newline at end of file
|
tav/oldblog
|
a1569b26e3284a62bdea884c21e5c66c64ad96c7
|
Added the start of the OAuth 3.0 article.
|
diff --git a/oauth-3.0-the-sane-and-simple-way-to-do-it.txt b/oauth-3.0-the-sane-and-simple-way-to-do-it.txt
new file mode 100644
index 0000000..05c5551
--- /dev/null
+++ b/oauth-3.0-the-sane-and-simple-way-to-do-it.txt
@@ -0,0 +1,148 @@
+---
+layout: post
+license: Public Domain
+---
+
+===========================================
+OAuth 3.0: The Sane and Simple Way To Do It
+===========================================
+
+.. raw:: html
+
+ <div class="float-right">
+ <a href="http://pypy.org"><img
+ src="http://pypy.org/image/pypy-logo.png" /></a>
+ </div>
+
+I'm a big fan of `OAuth <http://oauth.net/>`_ and I've done my fair share of
+promoting it -- from writing various open source client libraries to
+implementing services using it. However, the `OAuth 2.0 spec
+<http://tools.ietf.org/html/draft-ietf-oauth-v2-08>`_ just takes the piss.
+
+It's overly prescriptive, inconsistent and poorly written -- the worst that one
+could hope for from an emerging standard. And it sucks so much that I've yet to
+find a single conformant implementation by a major service provider.
+
+Take Facebook. They boldly claim `OAuth 2.0 support
+<http://developers.facebook.com/docs/authentication/>`_ and yet ignore most of
+it:
+
+* The spec states that the ``oauth_token`` parameter be used when accessing a
+ protected resource. Facebook use the ``access_token`` parameter name instead.
+
+* The spec states that certain requests MUST include the client ``type`` and
+ ``grant_type`` parameters. Facebook enforces no such requirement.
+
+* The spec states that clients MUST be able to authenticate themselves using
+ both HTTP basic auth and URI query parameters. Facebook only support the
+ latter.
+
+I could go on, but I'm sure you get the picture. The irony here is that Facebook
+is actually one of the co-authors of the spec. And before anyone starts bashing
+Facebook for ignoring standards, please read `the latest draft of the spec
+<http://tools.ietf.org/html/draft-ietf-oauth-v2-08>`_ -- it should be a lot
+simpler.
+
+As it is, what we're seeing is the emergence of incompatible and incomplete
+implementations by service providers. And when even the whiz kids at GitHub have
+`issues implementing OAuth 2.0
+<http://support.github.com/discussions/api/28-oauth2-busy-developers-guide>`_,
+it's time to re-evaluate the specification.
+
+So, in the interest of simplifying life for developers everywhere, I hereby
+present OAuth 3.0 -- an alternative to the latest OAuth 2.0 draft. It is so
+simple that even an idiot like me could do a complete implementation in about
+100 lines of Python code:
+
+* http://ampify.it/tentapp.html#oauth
+
+Anyways, let me know what you think. Especially if it can be made even simpler.
+Thanks!
+
+.. class:: block-section
+
+**OAuth 3.0**
+
+OAuth is a simple way for Client Applications to perform authorised actions on
+behalf of a User on remote Service Providers.
+
+.. syntax:: coffeescript
+
+ current_version: 3.0.0
+
+**Service Discovery**
+
+Service Providers announce their support for OAuth by publishing a
+``/.well-known/oauth.json`` file on their website. This file lives inside the
+container directory introduced by `[RFC 5796]
+<http://tools.ietf.org/html/rfc5785>`_ and is encoded in the JSON format `[RFC
+4627] <http://tools.ietf.org/html/rfc4627>`_. So for a Service Provider
+supporting OAuth 3.0:
+
+.. syntax:: bash
+
+ $ curl https://www.serviceprovider.com/.well-known/oauth.json
+
+We'd find something like:
+
+.. syntax:: javascript
+
+ {
+ "auth_endpoint": "https://www.serviceprovider.com/oauth/authorize",
+ "management_endpoint": "https://www.serviceprovider.com/oauth/manage",
+ "registration_endpoint": "https://www.serviceprovider.com/oauth/register",
+ "token_endpoint": "https://www.serviceprovider.com/oauth/token",
+ "version": "3.0.0"
+ }
+
+The JSON object could include other properties, but the following 5 string
+properties MUST be present:
+
+* The ``auth_endpoint`` defines the URI which Client Apps will direct a User to
+ -- in order for them to authorize access.
+
+* The ``management_endpoint`` defines the URI to manage authorized Client Apps.
+
+* The ``registration_endpoint`` defines the URI to register Client Apps with the
+ Service Provider.
+
+* The ``token_endpoint`` defines the Token Endpoint URI which a Client App will
+ communicate with -- in order to get or refresh an authorized access token.
+ This MUST be a secure channel, e.g. an HTTPS URL.
+
+* The ``version`` defines the `Semantic Version <http://semver.org/>`_ of the
+ OAuth Protocol that the Service Provider is currently supporting.
+
+**Client Registration**
+
+Of the format ``<hash-algorithm>:<hashcash-bits>:<token>``, e.g.
+
+.. syntax:: javascript
+
+ {
+ "challenge": "sha-1:20:473dfb39-198e-4082-bac1-c00cb868e3c4"
+ }
+
+The following:
+
+.. syntax:: python
+
+ def generate_hashcash(token, bits=20, hash=sha1):
+ n = 0
+ return hashcash
+
+A timing-independent string comparison mechanism should be used so as to avoid
+`timing attacks
+<http://rdist.root.org/2009/05/28/timing-attack-in-google-keyczar-library/>`_:
+
+.. syntax:: python
+
+ def constant_time_string_compare(s1, s2, ord=ord):
+ """Return whether two strings are equal -- without being a timing oracle."""
+
+ if len(s1) != len(s2):
+ return False
+ total = 0
+ for x, y in zip(s1, s2):
+ total |= ord(x) ^ ord(y)
+ return total == 0
|
tav/oldblog
|
77638037a88992a7d3ee469ceb83251afe6e3406
|
Wrote a post asking about interest in the pypy toolchain.
|
diff --git a/anyone-interested-in-articles-on-using-pypy-to-create-new-languages.txt b/anyone-interested-in-articles-on-using-pypy-to-create-new-languages.txt
new file mode 100644
index 0000000..914192b
--- /dev/null
+++ b/anyone-interested-in-articles-on-using-pypy-to-create-new-languages.txt
@@ -0,0 +1,94 @@
+---
+created: 2010-06-02, 10:05
+layout: post
+license: Public Domain
+---
+
+====================================================================
+Anyone Interested in Articles on Using PyPy to Create New Languages?
+====================================================================
+
+.. raw:: html
+
+ <div class="float-right">
+ <a href="http://pypy.org"><img
+ src="http://pypy.org/image/pypy-logo.png" /></a>
+ </div>
+
+`PyPy <http://pypy.org>`_ is famous as an alternative Python implementation. But
+it is also an impressive toolchain for creating your own programming languages
+-- you get features like garbage collection, JIT and even `WebKit integration
+<http://github.com/tav/ampify/tree/master/src/webkit_bridge/>`_ for free.
+
+Unfortunately, despite the toolchain being the bulk of the `PyPy code
+<http://github.com/tav/pypy>`_, it's not given much love. So, in an effort to
+convince fellow hackers to use PyPy, I'll be giving `a talk
+<http://www.oscon.com/oscon2010/public/schedule/detail/15487>`_ at the `Emerging
+Languages Camp <http://emerginglangs.com/>`_ at `OSCON
+<http://www.oscon.com/oscon2010/public/schedule/detail/15487>`_ (see below for
+the abstract).
+
+I'd also like to help bring more understanding of the toolchain to the wider
+hacker world and so am considering writing a series of tutorials on this blog.
+Unfortunately, I'm also a lazy bastard and don't want to waste time if no-one is
+interested ;p
+
+So this is your chance -- let me know in either the comments below or on `HN
+<http://news.ycombinator.com>`_/`Reddit
+<http://www.reddit.com/r/programming/>`_, if you'd be interested in such blog
+posts. Thanks!
+
+.. more
+
+.. raw:: html
+
+ <br />
+
+--------------------------------------------------------------------------------
+
+ **Create Your Own Programming Language in 20 Minutes using PyPy**
+
+ Creating your own dynamic language can be a messy, painful affair. Instead
+ of focusing on the features that make your language unique, you have to
+ waste a lot of time dealing with secondary issues like cross-platform
+ support, garbage collection and just-in-time compilation.
+
+ The `PyPy Translation Toolchain
+ <http://codespeak.net/pypy/dist/pypy/doc/translation.html>`_ â which has
+ already been successfully used to build alternative Python and Scheme
+ interpreters â can save you from all of this hassle. This talk will show how
+ easy it can be to create your own language by taking advantage of the
+ benefits that PyPy offers:
+
+ * `JIT <http://codespeak.net/pypy/dist/pypy/doc/jit/overview.html>`_ â
+ thanks to the state-of-the-art just-in-time compilation, your language
+ could be dynamic and still be competitive with lower-level languages in
+ terms of speed.
+
+ * `Garbage collection
+ <http://codespeak.net/pypy/dist/pypy/doc/garbage_collection.html>`_ â
+ select from the half dozen already implemented and tested strategies for
+ use by your language.
+
+ * `Sandboxing capability
+ <http://codespeak.net/pypy/dist/pypy/doc/sandbox.html>`_ â secure your
+ interpreter so that untrusted code can be safely run on all platforms,
+ whether it be a browser or an App Engine like service.
+
+ * `Unicode <http://www.unicode.org/standard/standard.html>`_ â your language
+ can be fully unicode-aware and you don't even have to know how case
+ folding works in different locales.
+
+ * `Stackless transformation
+ <http://codespeak.net/pypy/dist/pypy/doc/translation.html#the-stackless-transform>`_
+ â easily add support for your language to be massively concurrent.
+
+ * `Cross-platform
+ <http://codespeak.net/pypy/dist/pypy/doc/translation.html#the-c-back-end>`_
+ â have your interpreter run on a number of different backends, whether it
+ be native or on top of the CLI (.NET/Mono) or the JVM (Java).
+
+ * `WebKit bridge
+ <http://github.com/tav/ampify/tree/master/src/webkit_bridge/>`_ â create
+ browsers which can natively load scripts in your language via script tags
+ and even access the DOM, just like JavaScript!
|
tav/oldblog
|
8232e5bb860db329ed62df38fe484d4fe4e170dc
|
Upped Mamading's pecu allocation for recent awesomeness.
|
diff --git a/pecu-allocations-by-tav.txt b/pecu-allocations-by-tav.txt
index 652b997..528d46e 100644
--- a/pecu-allocations-by-tav.txt
+++ b/pecu-allocations-by-tav.txt
@@ -1,551 +1,551 @@
---
created: 2009-03-15, 10:14
layout: post
license: Public Domain
---
=======================
Pecu Allocations by Tav
=======================
.. image:: http://cloud.github.com/downloads/tav/plexnet/gfx.aaken.png
:class: float-right
Hundreds of people have -- knowingly or not -- had a *direct* impact on my
work/vision. Their belief, inspiration, energy, encouragement, suggestions,
criticisms, support (both emotional and financial), tasty treats and hard work
has been phenomenal!
I'd like to reward them with some life-time tav-branded `pecu allocations
<http://www.thruflo.com/2009/06/09/tav-describes-pecus.html>`_.
Since I'm not making any pecu payouts at the moment, they're not worth much yet
-- but I hope one day that those who've helped me will feel the gratitude =)
See below for the full list of `pecu
<http://www.thruflo.com/2009/06/09/tav-describes-pecus.html>`_ allocations.
.. more
The following individuals have put in a lot to make my vision a reality and I'd
like to reward them with **200,000** pecus each:
.. class:: double-column
* Alex Tomkins
* Brian Deegan
* Chris Macrae
* Cris Pearson
* Daniel Biddle
* Danny Bruder
* David Pinto
* Inderpaul Johar
* James Arthur (+200,000)
* Jeffry Archambeault
* John McCane-Whitney
* Liliana Avrushin
* Luke Graybill
-* Mamading Ceesay (+50,000)
+* Mamading Ceesay (+100,000)
* Martyn Hurt
* Matthieu Rey-Grange
* Mathew Ryden (+100,000)
* Nadine Gahr
* Nathan Staab
* Narmatha Murugananda
* Navaratnam Para
* Nicholas Midgley
* Ãyvind Selbek (+200,000)
* Sofia Bustamante
* Sean B. Palmer (+100,000)
* Stefan Plantikow
* Tim Jenks
* Tiziano Cirillo
* Tom Salfield
* Yan Minagawa
The following beautiful creatures have helped at various critical junctures or
laid key foundations. For this they get **20,000** pecus each:
.. class:: double-column
* Aaron Swartz
* Adam Langley
* Ade Thomas
* Adnan Hadzi
* Alex Greiner
* Alex Pappajohn
* Allen Short
* Andreas Dietrich
* Andrew Kenneth Milton
* Anne Biggs
* Anne Helene Wirstad
* Anette Hvolbæk
* Bryce Wilcox-O'Hearn
* Charles Goodier
* Chris Wood
* Claire Assis
* David Bovill
* Derek Richards
* Eric Hopper
* Eric Wahlforss
* Erik Möller
* Erol Ziya
* Ephraim Spiro
* Fenton Whelan
* Fergus Doyle
* Gary Alexander
* Gloria Charles
* Guido van Rossum
* Guilhem Buzenet
* Howard Rheingold
* Itamar Shtull-Trauring
* Jacob Everist
* Jan Ludewig
* Jill Lundquist
* Jim Carrico
* Jo Walsh
* Joe Short
* Joerg Baach
* John Hurliman
* Josef Davies-Coates
* Henri Cattan
* Henry Hicks
* Ka Ho Chan
* Karin Kylander
* Karina Arthur
* Katie Miller
* Kisiyane Roberts
* Laura Tov
* Lesley Donna Williams
* Lucie Rey-Grange
* Maciej Fijalkowski
* Mark Poole
* Maria Glauser
* Maria Chatzichristodoulou
* Matthew Sellwood
* Matthew Skinner
* Mayra Graybill
* Mia Bittar
* Mohan Selladurai
* Neythal (Sri Lanka)
* Nolan Darilek
* Olga Zueva
* Paul Böhm
* Phillip J. Eby
* Pierre-Antoine Tetard
* Ricky Cousins
* Salim Virani
* Saritah (Sarah Louise Newman ?)
* Saul Albert
* Shalabh Chaturvedi
* Simeon Scott
* Simon Michael
* Simon Fox
* Simon Reynolds
* Stephan Karpischek
* Steve Alexander
* Suhanya Babu
* Tavin Cole
* Thamilarasi Siva
* Tim Berners-Lee
* Tom Owen-Smith
* Vanda Petanjek
* Xiao Xuan Guo
These lovely supporters get **2,000** pecus each:
.. Ana Sandra Ruiz Entrecanales
.. class:: double-column
* Adam Burns
* Adam Karpierz (Poland)
* Adam Perfect
* Adam Wern
* Adir Tov
* Agathe Pouget-Abadie
* Al Tepper
* Alan Wagenberg
* Alex Bustamante
* Alexander Wait (USA)
* Alice Fung
* Andreas Kotes
* Andreas Schwarz
* Andrius Kulikauskas
* Andy Dawkins
* Andy McKay
* Andrew M. Kuchling
* Andrew McCormick
* Angela Beesley Starling
* Anna Gordon-Walker
* Anna Rothkopf
* Annalisa Fagan
* Anne Doyle
* Anselm Hook
* Ante Pavlov
* Arani Siva
* Ash Gerrish
* Ashley Siple
* Auro Tom Foxtrot
* Azra Gül
* Beatrice Wessolowski
* Ben Pirt
* Ben Swartz
* Benjamin Geer
* Benny "Curus" Amorsen
* Bernard Lietaer
* Blake Ludwig
* Boian Rodriguez Nikiforov
* Bram Cohen
* Brandon Wiley
* Bree Morrison
* Brenton Bills
* Brian Coughlan
* Briony "Misadventure" (UK)
* Callum Beith
* Candie Duncan
* Carl Ballard Swanson
* Carl Friedrich Bolz
* Céline Seger
* Chai Mason
* Charley Quinton
* Chris Cook
* Chris Davis
* Chris Heaton
* Chris McDonough
* Chris Withers
* Christoffer Hvolbaek
* Christopher Satterthwaite
* Christopher Schmidt
* Clara Maguire
* Cory Doctorow
* Craig Hubley
* Cyndi Rhoades
* Damiano VukotiÄ
* Dan Brickley
* Daniel Harris
* Daniel Magnoff
* Dante-Gabryell Monson
* David Bausola
* David Cozens
* David Goodger
* David Mertz
* David Midgley
* David Mills
* David Saxby
* Darran Edmundson
* Darren Platt
* Debra Bourne (UK)
* Dharushana Muthulingam
* Dermot ? (UK)
* Dimitris Savvaidis
* Dominik Webb
* Donatella Bernstein
* Dorothee Olivereau
* Dmytri Kleiner
* Earle Martin
* Edward Saperia
* Eléonore De Prunelé
* Elisabet Sahtouris
* Elkin Gordon Atwell
* Elmar Geese
* Emma Wigley
* Emmanuel Baidoo
* Erik Stewart
* Fabian Kyrielis
* Farhan Rehman
* Femi Longe
* Felicity Wood
* Felix Iskwei
* Florence David
* Francesca Cerletti (UK)
* Francesca Romana Giordano
* Gabe Wachob
* Gabrielle Hamm
* Gareth Strangemore-Jones
* Gary Poster
* Gaurav Pophaly
* Gavin Starks
* Gemma Youlia Dillon
* Geoff Jones
* Geoffry Arias
* George Nicholaides
* Gerry Gleason
* Giles Mason
* Glyph Lefkowitz
* Gordon Mohr
* Grant Stapleton
* Greg Timms
* Gregor J. Rothfuss
* Guy Kawasaki
* Hannah Harris
* Harriet Harris
* Heather Wilkinson
* Helen Aldritch
* Henry Bowen
* Holly Lloyd
* Holly Porter
* Ian Clarke
* Ian Hogarth
* Ida Norheim-Hagtun
* Igor Tojcic
* Ilze Black
* Inge Rochette
* James Binns
* James Cox (UK)
* James Howison (Australia)
* James Hurrell
* James McKay (Switzerland)
* James Stevens
* James Sutherland
* James Wallace
* Jan-Klaas Kollhof
* Jane Moyses
* Javier Candeira
* Jeannie Cool
* Jeremie Miller
* Jessica Bridges-Palmer
* Jim Ley
* Jimmy Wales
* Joanna O'Donnell
* Joe Geldart (UK)
* Joey DeVilla
* John Bywater
* John Cassidy
* John Lea
* John "Sayke" ?
* Joi Ito
* Jon Bootland
* Jonathan Robinson
* Joni Davis ?
* Jose Esquer
* Joseph O'Kelly (UK)
* Joy Green
* Juan Pablo Rico
* Jubin Zawar
* Judith Martin
* Julia Forster
* Jurgen Braam
* Justin OâShaughnessy (UK)
* Ka-Ping Yee
* Kapil Thangavelu
* Karen Hessels
* Katerina Tselou
* Katja Strøm Cappelen
* Kath Short
* Katie Keegan
* Katie Prescott
* Katy Marks
* Kelly Teamey
* Ken Manheimer
* Kevin Hemenway
* Kevin Marks
* Kiran Jonnalagadda
* Kiyoto Kanda
* Lanchanie Dias Gunawardena
* Laura Scheffler
* Lauri Love
* Leon Rocha
* Lena Nalbach
* Leslie Vuchot
* Lewis Hart
* Libby Miller
* Lion Kimbro
* Lisa Colaco
* Lord Kimo
* Lottie Child
* Lucas Gonzalez
* Luke Francl
* Luke Kenneth Casson Leighton
* Luke Nicholson
* Luke Robinson
* Lynton Currill Kim-Wai Pepper
* Magnolia Slimm
* Manuel Sauer
* Maor Bar-Ziv
* Marco Herry
* Mark Brown
* Mark Chaplin
* Mark Hodge
* Mark S. Miller
* Markus Quarta
* Marguerite Smith
* Marshall Burns
* Martin Peck
* Mary Fee
* Matt Cooperrider
* Matthew Devney
* Mattis Manzel
* Mayra Vivo Torres
* Meghan Benton
* Meera Shah
* Menka Parekh
* Michael Linton
* Michael Maranda
* Michael Sparks
* Michel Bauwens
* Mike Linksvayer
* Mikey Weinkove
* Mitchell Jacobs
* Molly Webb
* Moraan Gilad
* Mostofa Zaman
* Navindu Katugampola
* Nathalie Follen
* Nick Hart-Williams
* Nick Ierodiaconou
* Nick Szabo
* Nicolas David
* Niels Boeing (Germany)
* Nils Toedtmann
* Nisha Patel
* Nishant Shah
* Noa Harvey
* Noah Slater
* Oliver Morrison
* Oliver Sylvester-Bradley
* Oz Mose
* Pamela McLean
* Paola Desiderio
* Paolo "xerox" Martini (UK)
* Pascale Scheurer
* Patrick Andrews
* Patrick Yiu
* Paul Everitt
* Paul Harrison
* Paul Mutton (UK)
* Paul Pesach
* Paul Robinett
* Peri Urban
* Pete Brownwell
* Petit-Pigeard Clotilde
* Phil G
* Phil Harris
* Piccia Neri
* Pietro Speroni di Fenizio
* \R. David Murray
* Rama Gheerawo
* Raph Levien
* Rasmacone Boothe
* Rasmus Tenbergen
* Rastko ?
* Ray Murray
* Raymond Hettinger
* Rayhan Omar
* Rebecca Harding
* Reem Martin
* Riccarda Zezza
* Rob Lord
* Robert De Souza
* Robert Kaye
* Robert Knowles
* Robin Upton
* Rodney Shakespeare
* Rohit Khare
* Roman Nosov
* Ron Briefel
* Ricardo Niederberger Cabral
* Richard Ford
* Richard Nelson
* Richard "coldfyre" Nicholas (USA)
* Roger Dingledine
* Romek Szczesniak
* Ross Evans (UK)
* Rufus Pollock
* Salim Fadhley (UK)
* Sam Brown
* Sam Geall
* Sam Joseph
* Sara Kiran
* Selas Mene
* Servane Mouazan
* Shahid Choudhry
* Shane Hughes
* Simon Bartlet
* Simon Persoff
* Simon Rawles
* Sonia Ali
* Sophie ? (Austria)
* Sophie Le Barbier
* Stan Rey-Grange
* Stayce Kavanaugh
* Stefan Baker
* Steffi Dayalan
* Stella Boeva
* Stephan Dohrn
* Stephen Wilmot
* Steve Jenson
* Steve Peake
* Steven Starr
* Su Nandy
* Suresh Fernando
* Suw Charman
* Sunir Shah
* Sym Von LynX
* Tamsin Lejeune
* Tanis Taylor
* Tansy E Huws
* Tess Ashwin
* Tim Wacker (USA)
* Tom D. Harry (UK)
* Tom Heiser
* Tom Longson
* Tom Williams
* Tommy Hutchinson
* Tommy Teillaud
* Toni Prug
* Toni Sola
* Tony Cook
* Tyler Eaves
* Ushani Suresh
* Veeral ?
* William Wardlaw-Rogers
* Wayne Siron
* Wes Felter
* Wybo Wiersma
* Zoe Young
And, finally, whilst I'm not currently making any pecu allocations to them, I
feel deeply indebted to these visionaries, musicians, coders and writers:
.. class:: double-column
* \A. R. Rahman
* Alan Kay
* Asian Dub Foundation
* Au Revoir Simone
* Bruce Sterling
* Buckminster Fuller (passed away)
* Daft Punk
* David Lynch
* Douglas Engelbart
* Fernando Perez
* India Arie
* Jeff Buckley (passed away)
* Kim Stanley Robinson
* Lawrence Lessig
* M.I.A.
* Mahatma Gandhi (passed away)
* Manu Chao
* Marc Stiegler
* Mark Pilgrim
* Marlena Shaw
* Massive Attack
* Michael Franti
* Muhammad Yunus
* Neal Stephenson
* Nouvelle Vague
* P.M.
* Paul Graham
* Peter Norvig
* Portishead
* Ray Charles (passed away)
* Ray Ozzie
* Richard P. Gabriel
* Tanya Stephens
* Ted Nelson
* Tim Peters
* Vannevar Bush (passed away)
* Vint Cerf
Thank you all!
\ No newline at end of file
|
tav/oldblog
|
86fe0fd1a7ac6cc0867ecb0bd3003b81d7b94270
|
Inlined the link.
|
diff --git a/4-features-to-make-github-an-awesome-platform.txt b/4-features-to-make-github-an-awesome-platform.txt
index 22dfb05..b89599a 100644
--- a/4-features-to-make-github-an-awesome-platform.txt
+++ b/4-features-to-make-github-an-awesome-platform.txt
@@ -1,207 +1,205 @@
---
created: 2010-04-07, 07:27
layout: post
license: Public Domain
---
=============================================
4 Features To Make GitHub An Awesome Platform
=============================================
.. raw:: html
<div class="float-right">
<a href="http://github.com"><img
src="http://logicalawesome.com/logical_awesome.jpg"
width="375px" height="300px" /></a>
</div>
I love `GitHub <http://github.com>`_. They make it fun and easy to get involved
with open source projects!
By recognising `coding as a social endeavour
<http://www.espians.com/getting-started-with-git.html>`_, they've possibly even
changed the very nature of open source development.
But as great as they are, there's not much of a "GitHub ecosystem". In
comparison to say Twitter apps, the number of GitHub apps are few and far
between.
Wouldn't it be great if we could build our own apps like wikis on top of GitHub
repositories?
Perhaps someone would create a peer-to-peer publishing platform or perhaps a web
app which stores plain text data in public repos instead of in opaque databases?
I believe GitHub has the potential to become a truly awesome platform. They
already have a `decent API <http://develop.github.com/>`_ -- imagine what would
be possible if it supported the following features:
.. more
.. raw:: html
<hr class="clear" />
* **API to Update The Repository via HTTP**
Back in 2008, I managed to get my girlfriend to use GitHub. The poor girl
heroically struggled through with Git on the command line before eventually
giving up after a few months.
The fact is, most people are more comfortable using web apps than with command
line tools. It'd be awesome to let them benefit from Git without having to
expose them to the command line.
It'd also be nice for developers if GitHub exposed functionality to modify
files in a repository over HTTP instead of having to resort to libraries like
`grit <http://grit.rubyforge.org/>`_ and `dulwich
<http://github.com/jelmer/dulwich>`_. This would make it much easier to
develop web apps leveraging Git.
GitHub already has support for editing files from the web browser by POST-ing
to ``/:user/:repo/tree-save/:branch/:path`` -- it'd be cool if they could
just expose this via an API:
.. syntax:: text
/tree/save/:user/:repo/:branch/:path
This should take 6 parameters and return the new commit ID:
.. syntax:: text
parents => The IDs of the parent commits [optional]
data => The updated content for the specified path
mode => The new mode for the blob [defaults to 100644]
message => The commit message
committer => The committer [defaults to the authenticated user]
author => The commit author [defaults to the committer]
There should be a complementary API for deleting files:
.. syntax:: text
/tree/remove/:user/:repo/:branch/:path
And, most importantly, an API for creating new files with the same parameters
as ``/tree/save``:
.. syntax:: text
/tree/add/:user/:repo/:branch/:path
It would be nice to have a utility API call for renaming files too:
.. syntax:: text
/tree/rename/:user/:repo/:branch/:path
Which would only have to specify 5 parameters:
.. syntax:: text
parent => The ID of the parent commit [optional]
new_path => The new path for the blob at :path
message => The commit message
committer => The committer [defaults to the authenticated user]
author => The commit author [defaults to the committer]
All the above API calls should result in the ``:branch`` ref being updated to
point to the new commit ID and create a new ref where the branch didn't
previously exist.
* **API to Access Compare Views**
GitHub has wicked support for doing code reviews via what they call `compare
views <http://github.com/blog/612-introducing-github-compare-view>`_. This
feature allows one to see the commits, diffs and comments between any 2 refs.
You have to see it in action to realise how awesome this is:
http://github.com/jquery/jquery/compare/omgrequire
Unfortunately, this feature is not exposed via the API in any way. It would be
very cool to be able to access it:
.. syntax:: text
/compare/:user/:repo/[:startRef...]:endRef
That should return the commits, diffs and comments for the commit range. That
is, everything necessary to recreate the GitHub compare view.
* **API to Manage Service Hooks**
GitHub already supports extension via `post-receive hooks
<http://help.github.com/post-receive-hooks/>`_. This allows you to register
URLs as `web hooks <http://webhooks.pbworks.com/>`_ for any repository. GitHub
will POST to these URLs with JSON data whenever someone does a ``git push`` to
the repository.
It makes it very easy to do things in response to changes to your
repositories. I've already found it very useful for everything from triggering
build slaves to notifying IRC channels via `gitbot.py
<http://github.com/tav/scripts/blob/master/gitbot.py>`_ -- which in turn even
triggers regeneration of this blog!
Unfortunately it's a real pain to get users to edit their service hooks. It'd
be great if applications could do this on a user's behalf. The API could be
extended to list all service hooks:
.. syntax:: text
/repos/hooks/:user/:repo
It should be very easy to add and remove hooks:
.. syntax:: text
/repos/hooks/:user/:repo/add
/repos/hooks/:user/:repo/remove
Which would take a single POST-ed parameter:
.. syntax:: text
url => The post-receive URL
This tiny feature would make it a lot more attractive for application
developers as it would make building apps integrated with GitHub very easy!!
* **A Way to Pay for API Use**
GitHub currently specifies `API limits
<http://develop.github.com/p/general.html#limitations>`_ of 60 requests per
minute. This works out as a generous 86,400 requests/day per user. But as an
application developer I'd rather not be limited. In fact, seeing as GitHub
already has my billing details, I'd be quite happy to pay something like $20
per million requests -- which should more than cover the bandwidth costs.
I'm quite confident that interesting applications could be built using the API
which would lead to productivity increases which would more than make up for
the cost. To facilitate this, billing would need to be enabled and the
`authentication <http://develop.github.com/p/general.html>`_ extended with:
.. syntax:: text
api_key => The API key for the developer
signature => The signature for the API request
The ``signature`` would be derived by HMAC-ing the request parameters with a
shared ``api_secret_key`` corresponding to the ``api_key``. This would be used
to bypass limits and bill for the API requests whereas the existing ``login``
and ``token`` parameters would be used for the authentication.
Given GitHub's `impressive infrastructure
<http://github.com/blog/530-how-we-made-github-fast>`_ and talent, it should be
relatively easy for them to add these 4 small features. But like any group of
hackers, they need to be convinced that it'd be worthwhile adding these
features.
Perhaps you could ask them for these features? Perhaps you could leave a comment
with what kind of awesome apps you would create with these features in place? Or
-just follow me on GitHub:
-
-* http://github.com/tav
+perhaps just follow me on GitHub: `github.com/tav <http://github.com/tav>`_.
In any case, let me know what you think. Thanks!
\ No newline at end of file
|
tav/oldblog
|
c159d0b217a309ea75fdf6b0a76098fa4d957174
|
Added ref to GitHub repo in the article.
|
diff --git a/4-features-to-make-github-an-awesome-platform.txt b/4-features-to-make-github-an-awesome-platform.txt
index 16b1cd5..22dfb05 100644
--- a/4-features-to-make-github-an-awesome-platform.txt
+++ b/4-features-to-make-github-an-awesome-platform.txt
@@ -1,204 +1,207 @@
---
created: 2010-04-07, 07:27
layout: post
license: Public Domain
---
=============================================
4 Features To Make GitHub An Awesome Platform
=============================================
.. raw:: html
<div class="float-right">
<a href="http://github.com"><img
src="http://logicalawesome.com/logical_awesome.jpg"
width="375px" height="300px" /></a>
</div>
I love `GitHub <http://github.com>`_. They make it fun and easy to get involved
with open source projects!
By recognising `coding as a social endeavour
<http://www.espians.com/getting-started-with-git.html>`_, they've possibly even
changed the very nature of open source development.
But as great as they are, there's not much of a "GitHub ecosystem". In
comparison to say Twitter apps, the number of GitHub apps are few and far
between.
Wouldn't it be great if we could build our own apps like wikis on top of GitHub
repositories?
Perhaps someone would create a peer-to-peer publishing platform or perhaps a web
app which stores plain text data in public repos instead of in opaque databases?
I believe GitHub has the potential to become a truly awesome platform. They
already have a `decent API <http://develop.github.com/>`_ -- imagine what would
be possible if it supported the following features:
.. more
.. raw:: html
<hr class="clear" />
* **API to Update The Repository via HTTP**
Back in 2008, I managed to get my girlfriend to use GitHub. The poor girl
heroically struggled through with Git on the command line before eventually
giving up after a few months.
The fact is, most people are more comfortable using web apps than with command
line tools. It'd be awesome to let them benefit from Git without having to
expose them to the command line.
It'd also be nice for developers if GitHub exposed functionality to modify
files in a repository over HTTP instead of having to resort to libraries like
`grit <http://grit.rubyforge.org/>`_ and `dulwich
<http://github.com/jelmer/dulwich>`_. This would make it much easier to
develop web apps leveraging Git.
GitHub already has support for editing files from the web browser by POST-ing
to ``/:user/:repo/tree-save/:branch/:path`` -- it'd be cool if they could
just expose this via an API:
.. syntax:: text
/tree/save/:user/:repo/:branch/:path
This should take 6 parameters and return the new commit ID:
.. syntax:: text
parents => The IDs of the parent commits [optional]
data => The updated content for the specified path
mode => The new mode for the blob [defaults to 100644]
message => The commit message
committer => The committer [defaults to the authenticated user]
author => The commit author [defaults to the committer]
There should be a complementary API for deleting files:
.. syntax:: text
/tree/remove/:user/:repo/:branch/:path
And, most importantly, an API for creating new files with the same parameters
as ``/tree/save``:
.. syntax:: text
/tree/add/:user/:repo/:branch/:path
It would be nice to have a utility API call for renaming files too:
.. syntax:: text
/tree/rename/:user/:repo/:branch/:path
Which would only have to specify 5 parameters:
.. syntax:: text
parent => The ID of the parent commit [optional]
new_path => The new path for the blob at :path
message => The commit message
committer => The committer [defaults to the authenticated user]
author => The commit author [defaults to the committer]
All the above API calls should result in the ``:branch`` ref being updated to
point to the new commit ID and create a new ref where the branch didn't
previously exist.
* **API to Access Compare Views**
GitHub has wicked support for doing code reviews via what they call `compare
views <http://github.com/blog/612-introducing-github-compare-view>`_. This
feature allows one to see the commits, diffs and comments between any 2 refs.
You have to see it in action to realise how awesome this is:
http://github.com/jquery/jquery/compare/omgrequire
Unfortunately, this feature is not exposed via the API in any way. It would be
very cool to be able to access it:
.. syntax:: text
/compare/:user/:repo/[:startRef...]:endRef
That should return the commits, diffs and comments for the commit range. That
is, everything necessary to recreate the GitHub compare view.
* **API to Manage Service Hooks**
GitHub already supports extension via `post-receive hooks
<http://help.github.com/post-receive-hooks/>`_. This allows you to register
URLs as `web hooks <http://webhooks.pbworks.com/>`_ for any repository. GitHub
will POST to these URLs with JSON data whenever someone does a ``git push`` to
the repository.
It makes it very easy to do things in response to changes to your
repositories. I've already found it very useful for everything from triggering
build slaves to notifying IRC channels via `gitbot.py
<http://github.com/tav/scripts/blob/master/gitbot.py>`_ -- which in turn even
triggers regeneration of this blog!
Unfortunately it's a real pain to get users to edit their service hooks. It'd
be great if applications could do this on a user's behalf. The API could be
extended to list all service hooks:
.. syntax:: text
/repos/hooks/:user/:repo
It should be very easy to add and remove hooks:
.. syntax:: text
/repos/hooks/:user/:repo/add
/repos/hooks/:user/:repo/remove
Which would take a single POST-ed parameter:
.. syntax:: text
url => The post-receive URL
This tiny feature would make it a lot more attractive for application
developers as it would make building apps integrated with GitHub very easy!!
* **A Way to Pay for API Use**
GitHub currently specifies `API limits
<http://develop.github.com/p/general.html#limitations>`_ of 60 requests per
minute. This works out as a generous 86,400 requests/day per user. But as an
application developer I'd rather not be limited. In fact, seeing as GitHub
already has my billing details, I'd be quite happy to pay something like $20
per million requests -- which should more than cover the bandwidth costs.
I'm quite confident that interesting applications could be built using the API
which would lead to productivity increases which would more than make up for
the cost. To facilitate this, billing would need to be enabled and the
`authentication <http://develop.github.com/p/general.html>`_ extended with:
.. syntax:: text
api_key => The API key for the developer
signature => The signature for the API request
The ``signature`` would be derived by HMAC-ing the request parameters with a
shared ``api_secret_key`` corresponding to the ``api_key``. This would be used
to bypass limits and bill for the API requests whereas the existing ``login``
and ``token`` parameters would be used for the authentication.
Given GitHub's `impressive infrastructure
<http://github.com/blog/530-how-we-made-github-fast>`_ and talent, it should be
relatively easy for them to add these 4 small features. But like any group of
hackers, they need to be convinced that it'd be worthwhile adding these
features.
Perhaps you could ask them for these features? Perhaps you could leave a comment
-with what kind of awesome apps you would create with these features in place?
+with what kind of awesome apps you would create with these features in place? Or
+just follow me on GitHub:
+
+* http://github.com/tav
In any case, let me know what you think. Thanks!
\ No newline at end of file
|
tav/oldblog
|
a65ee3164157eac3700b20eb4d9c4243c9d27e4f
|
Wrote an article on features to make GitHub awesome.
|
diff --git a/4-features-to-make-github-an-awesome-platform.txt b/4-features-to-make-github-an-awesome-platform.txt
new file mode 100644
index 0000000..16b1cd5
--- /dev/null
+++ b/4-features-to-make-github-an-awesome-platform.txt
@@ -0,0 +1,204 @@
+---
+created: 2010-04-07, 07:27
+layout: post
+license: Public Domain
+---
+
+=============================================
+4 Features To Make GitHub An Awesome Platform
+=============================================
+
+.. raw:: html
+
+ <div class="float-right">
+ <a href="http://github.com"><img
+ src="http://logicalawesome.com/logical_awesome.jpg"
+ width="375px" height="300px" /></a>
+ </div>
+
+I love `GitHub <http://github.com>`_. They make it fun and easy to get involved
+with open source projects!
+
+By recognising `coding as a social endeavour
+<http://www.espians.com/getting-started-with-git.html>`_, they've possibly even
+changed the very nature of open source development.
+
+But as great as they are, there's not much of a "GitHub ecosystem". In
+comparison to say Twitter apps, the number of GitHub apps are few and far
+between.
+
+Wouldn't it be great if we could build our own apps like wikis on top of GitHub
+repositories?
+
+Perhaps someone would create a peer-to-peer publishing platform or perhaps a web
+app which stores plain text data in public repos instead of in opaque databases?
+
+I believe GitHub has the potential to become a truly awesome platform. They
+already have a `decent API <http://develop.github.com/>`_ -- imagine what would
+be possible if it supported the following features:
+
+.. more
+
+.. raw:: html
+
+ <hr class="clear" />
+
+* **API to Update The Repository via HTTP**
+
+ Back in 2008, I managed to get my girlfriend to use GitHub. The poor girl
+ heroically struggled through with Git on the command line before eventually
+ giving up after a few months.
+
+ The fact is, most people are more comfortable using web apps than with command
+ line tools. It'd be awesome to let them benefit from Git without having to
+ expose them to the command line.
+
+ It'd also be nice for developers if GitHub exposed functionality to modify
+ files in a repository over HTTP instead of having to resort to libraries like
+ `grit <http://grit.rubyforge.org/>`_ and `dulwich
+ <http://github.com/jelmer/dulwich>`_. This would make it much easier to
+ develop web apps leveraging Git.
+
+ GitHub already has support for editing files from the web browser by POST-ing
+ to ``/:user/:repo/tree-save/:branch/:path`` -- it'd be cool if they could
+ just expose this via an API:
+
+ .. syntax:: text
+
+ /tree/save/:user/:repo/:branch/:path
+
+ This should take 6 parameters and return the new commit ID:
+
+ .. syntax:: text
+
+ parents => The IDs of the parent commits [optional]
+ data => The updated content for the specified path
+ mode => The new mode for the blob [defaults to 100644]
+ message => The commit message
+ committer => The committer [defaults to the authenticated user]
+ author => The commit author [defaults to the committer]
+
+ There should be a complementary API for deleting files:
+
+ .. syntax:: text
+
+ /tree/remove/:user/:repo/:branch/:path
+
+ And, most importantly, an API for creating new files with the same parameters
+ as ``/tree/save``:
+
+ .. syntax:: text
+
+ /tree/add/:user/:repo/:branch/:path
+
+ It would be nice to have a utility API call for renaming files too:
+
+ .. syntax:: text
+
+ /tree/rename/:user/:repo/:branch/:path
+
+ Which would only have to specify 5 parameters:
+
+ .. syntax:: text
+
+ parent => The ID of the parent commit [optional]
+ new_path => The new path for the blob at :path
+ message => The commit message
+ committer => The committer [defaults to the authenticated user]
+ author => The commit author [defaults to the committer]
+
+ All the above API calls should result in the ``:branch`` ref being updated to
+ point to the new commit ID and create a new ref where the branch didn't
+ previously exist.
+
+* **API to Access Compare Views**
+
+ GitHub has wicked support for doing code reviews via what they call `compare
+ views <http://github.com/blog/612-introducing-github-compare-view>`_. This
+ feature allows one to see the commits, diffs and comments between any 2 refs.
+ You have to see it in action to realise how awesome this is:
+
+ http://github.com/jquery/jquery/compare/omgrequire
+
+ Unfortunately, this feature is not exposed via the API in any way. It would be
+ very cool to be able to access it:
+
+ .. syntax:: text
+
+ /compare/:user/:repo/[:startRef...]:endRef
+
+ That should return the commits, diffs and comments for the commit range. That
+ is, everything necessary to recreate the GitHub compare view.
+
+* **API to Manage Service Hooks**
+
+ GitHub already supports extension via `post-receive hooks
+ <http://help.github.com/post-receive-hooks/>`_. This allows you to register
+ URLs as `web hooks <http://webhooks.pbworks.com/>`_ for any repository. GitHub
+ will POST to these URLs with JSON data whenever someone does a ``git push`` to
+ the repository.
+
+ It makes it very easy to do things in response to changes to your
+ repositories. I've already found it very useful for everything from triggering
+ build slaves to notifying IRC channels via `gitbot.py
+ <http://github.com/tav/scripts/blob/master/gitbot.py>`_ -- which in turn even
+ triggers regeneration of this blog!
+
+ Unfortunately it's a real pain to get users to edit their service hooks. It'd
+ be great if applications could do this on a user's behalf. The API could be
+ extended to list all service hooks:
+
+ .. syntax:: text
+
+ /repos/hooks/:user/:repo
+
+ It should be very easy to add and remove hooks:
+
+ .. syntax:: text
+
+ /repos/hooks/:user/:repo/add
+ /repos/hooks/:user/:repo/remove
+
+ Which would take a single POST-ed parameter:
+
+ .. syntax:: text
+
+ url => The post-receive URL
+
+ This tiny feature would make it a lot more attractive for application
+ developers as it would make building apps integrated with GitHub very easy!!
+
+* **A Way to Pay for API Use**
+
+ GitHub currently specifies `API limits
+ <http://develop.github.com/p/general.html#limitations>`_ of 60 requests per
+ minute. This works out as a generous 86,400 requests/day per user. But as an
+ application developer I'd rather not be limited. In fact, seeing as GitHub
+ already has my billing details, I'd be quite happy to pay something like $20
+ per million requests -- which should more than cover the bandwidth costs.
+
+ I'm quite confident that interesting applications could be built using the API
+ which would lead to productivity increases which would more than make up for
+ the cost. To facilitate this, billing would need to be enabled and the
+ `authentication <http://develop.github.com/p/general.html>`_ extended with:
+
+ .. syntax:: text
+
+ api_key => The API key for the developer
+ signature => The signature for the API request
+
+ The ``signature`` would be derived by HMAC-ing the request parameters with a
+ shared ``api_secret_key`` corresponding to the ``api_key``. This would be used
+ to bypass limits and bill for the API requests whereas the existing ``login``
+ and ``token`` parameters would be used for the authentication.
+
+Given GitHub's `impressive infrastructure
+<http://github.com/blog/530-how-we-made-github-fast>`_ and talent, it should be
+relatively easy for them to add these 4 small features. But like any group of
+hackers, they need to be convinced that it'd be worthwhile adding these
+features.
+
+Perhaps you could ask them for these features? Perhaps you could leave a comment
+with what kind of awesome apps you would create with these features in place?
+
+In any case, let me know what you think. Thanks!
\ No newline at end of file
|
tav/oldblog
|
34110c425d6c5f685933d1183ade99218d278883
|
Trying out lloogg.com real-time log viewer support.
|
diff --git a/website/main.genshi b/website/main.genshi
index 481af58..e040c48 100644
--- a/website/main.genshi
+++ b/website/main.genshi
@@ -1,270 +1,276 @@
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/">
<?python
from time import time
from operator import lt
from urllib import urlencode
STATIC = 'http://cloud.github.com/downloads/tav/plexnet'
info = defined('info') and info or {}
author_info = authors.get(site_author_nick)
author = author_info[1]
version = info.get('x-version', '')
copyright = info.get('copyright', 'This work has been placed into the public domain')
description = info.get('subtitle', site_description)
subtitle = info.get('subtitle')
page_title = info.get('title') or info.get('__title__') or site_description
page_url = disqus_url = 'http://tav.espians.com' + '/' + info.get('__name__', 'index') + '.html'
if info.get('x-created') and lt(info['x-created'][1:8], "2009-07"):
disqus_url = 'http://www.asktav.com' + '/' + info.get('__name__', 'index') + '.html'
if info.get('__type__') == 'py':
description = info.get('title')
#if description:
# page_title = "%s (%s)" % (description, info.get('__title__'))
#else:
# page_title = "Source Package: %s" % info.get('__title__')
page_title = "Source Package: %s" % info.get('__title__')
MONTHS = [
'Zero Month',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
?>
<head>
<title><py:if test="not info.get('title')">${Markup(site_title)} » </py:if>${Markup(page_title)}</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<meta name="tweetmeme-title" content="${page_title}" />
<!-- disable some internet explorer features -->
<meta http-equiv="imagetoolbar" content="no" />
<meta name="MSSmartTagsPreventParsing" content="true" />
<!-- meta elements (search engines) -->
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<!-- meta elements (page data) -->
<meta name="author" content="${author}" />
<meta name="description" content="${description}" />
<meta name="version" content="${version}" />
<meta name="copyright" content="${copyright}" />
<meta name="document-rating" content="general" />
<meta http-equiv="content-language" content="en" />
<meta name="verify-v1" content="aLcMPDDmDYvgufTDcJiiCOgPt/FOooMmGHiPj64BMbU=" />
<link rel="icon" type="image/png" href="${STATIC}/gfx.aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds2.feedburner.com/${site_nick}" />
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="${STATIC}/css.screen.css?v=2" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="${STATIC}/css.${site_nick}.css?v=2" />
<style type="text/css" media="print">
/* @import url("${STATIC}/css.print.css"); */
#ignore-this { display: none; }
</style>
<style type="text/css">
.ascii-art .literal-block {
line-height: 1em !important;
}
.cmd-line {
background-color: #000;
color: #fff;
padding: 5px;
margin-left: 2em;
margin-right: 2em;
}
.cmd-ps1 {
color: #999;
}
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
</style>
<![endif]-->
<!-- javascript -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" />
<script type="text/javascript">
GOOGLE_ANALYTICS_CODE = "${site_analytics_code}";
DISQUS_FORUM = '${site_nick}';
PAGE_URI = '${page_url}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
</script>
<script type="text/javascript" src="${STATIC}/js.init.js" />
<!-- <script type="text/javascript"
src="http://w.sharethis.com/button/sharethis.js#tabs=web%2Cpost%2Cemail&charset=utf-8&style=rotate&publisher=65b4c59a-e069-4896-84b4-7d8d7dce2b77&headerbg=%230099cd&linkfg=%230099cd"></script> -->
</head>
<body>
<div id="main">
<div id="site-header">
<div id="site-info">
<a href="/" title="Asktav: A Blog by Tav"><img
id="site-logo" src="${STATIC}/gfx.logo.asktav.png" alt="Aaken Logo" width="64px" height="64px" /></a><form id="translation_form" class="menu-item-padding"><select id="lang_select" onchange="dotranslate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form><a href="/" class="menu-item"
title="${site_title}">Asktav Home</a><a href="archive.html" class="menu-item"
title="Site Index">Archives</a><a class="menu-item"
title="About Tav"
href="about-${site_author.lower()}.html">About
${site_author.title()}</a><a class="menu-item-final"
href="http://twitter.com/tav" title="Follow @tav" style="margin-right: 5px;"><img
src="${STATIC}/gfx.icon.twitter.png" alt="Follow @tav on Twitter"
class="absmiddle" /></a><a href="http://friendfeed.com/tav" style="margin-right: 5px;"
title="Follow tav on FriendFeed"><img src="${STATIC}/gfx.icon.friendfeed.png"
alt="FriendFeed" class="absmiddle" /></a><a
style="margin-right: 5px;"
href="http://github.com/tav" title="Follow tav on GitHub"><img
src="${STATIC}/gfx.icon.github.png" alt="GitHub" class="absmiddle"
/></a><a style="margin-right: 5px;"
href="http://www.facebook.com/asktav"
title="Follow Tav on Facebook"><img src="${STATIC}/gfx.icon.facebook.gif"
alt="Facebook" class="absmiddle" /></a><a
href="http://feeds2.feedburner.com/${site_nick}" rel="alternate"
type="application/rss+xml" title="Subscribe to the RSS Feed"><img
alt="RSS Feed" class="absmiddle"
src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png"
/></a><div
style="margin-top: 7px; font-family: Monaco,Courier New;"></div>
<hr class="clear" />
</div>
</div>
<div py:if="defined('content')">
<div class="article-nav">
</div>
<div class="article-title">
<div class="post-link"><a href="${info['__name__']}.html">${Markup(page_title)}</a></div>
<div class="additional-content-info">
<!-- <script language="javascript" type="text/javascript">
SHARETHIS.addEntry({
title:"${page_title.replace('"', r'\"')}",
url:'${page_url}',
}, {button:true});
</script>| --><a href="#disqus_thread" rel="disqus:${disqus_url}">Add a Comment</a>
<script type="text/javascript">
tweetmeme_url = '${page_url}';
tweetmeme_source = 'tav';
tweetmeme_service = 'bit.ly';
tweetmeme_style = 'compact';
</script>
| <div class="retweetbutton">
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
</div>
<div class="article-info">
» by <a href="http://tav.espians.com">tav</a><span py:if="info.get('x-created')"> on <span py:with="created=info['x-created']" class="post-date">${MONTHS[int(created[6:8])]} ${int(created[9:11])}, ${created[1:5]} @ <a href="http://github.com/tav/blog/commits/master/${info['__name__']}.txt">${created[-6:-1]}</a></span></span> <a href="http://creativecommons.org/publicdomain/zero/1.0/"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Cc-pd.svg/64px-Cc-pd.svg.png" width="20px" height="20px" alt="Public Domain" class="absmiddle" /></a>
<!--
last updated
<span py:with="created=info['__updated__']">
${created.strftime('%H:%M')}, ${created.strftime('%d %B %Y').lower()}
</span>
-->
</div>
</div>
<div py:if="not info.get('x-created') and not info.get('__type__') == 'py'" class="attention">
This is an early draft. Many sections are incomplete. A lot more is being written.
</div>
<div id="content">
<div py:content="Markup(content)"></div>
</div>
<br /><hr class="clear" />
<div class="article-nav" style="margin-bottom: 1.5em;">
<script type="text/javascript">
ARTICLE_NAME = '${info['__name__']}';
</script>
<script type="text/javascript" src="index.js?${int(time()/4)}" />
</div>
<div id="disqus-comments-section">
<script type="text/javascript">
disqus_url = "${disqus_url}";
disqus_title = "${Markup(page_title)}";
</script>
<div id="disqus_thread"></div><script type="text/javascript"
src="http://disqus.com/forums/${site_nick}/embed.js"></script><noscript><a
href="http://${site_nick}.disqus.com/?${urlencode({'url': disqus_url})}">View the forum
thread.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">Comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
</div>
<div py:if="defined('alternative_content')">
${Markup(alternative_content)}
</div>
<div><br /><br /></div>
</div>
+<script type="text/javascript">
+lloogg_clientid = "1910200a6155a16";
+</script>
+<script type="text/javascript" src="http://lloogg.com/l.js?c=1910200a6155a16">
+</script>
+
</body>
</html>
|
tav/oldblog
|
ced32c9df5406cb90125f7fc27af83be7d905522
|
Changed 'computer science' to 'computing' after valid feedback on HN.
|
diff --git a/ciao-python-hola-go.txt b/ciao-python-hola-go.txt
index cc62359..2611650 100644
--- a/ciao-python-hola-go.txt
+++ b/ciao-python-hola-go.txt
@@ -1,225 +1,225 @@
=====================
Ciao Python, Hola Go!
=====================
:X-Created: [2009-11-25, 15:27]
.. raw:: html
<div class="float-right">
<a href="http://golang.org" title="Go Programming Language"><img
src="http://cloud.github.com/downloads/tav/plexnet/gfx.logo.go.black.png"
alt="Go" /></a>
</div>
This is the first in a series of articles in which I'll document my move away
from Python and the adventures encountered in using `Go <http://golang.org>`_ to
build the `Plexnet <http://www.espians.com/plexnet.html>`_, an "internet
operating system".
My love affair with Python began in early 2000 when I `discovered Zwiki
<http://zwiki.org/Tav>`_. And despite brief flings with other languages --
Alice, E, Erlang, Lisp, Lua, Objective-C, OCaml, Oz, PowerShell, Ruby, Scheme,
Smalltalk -- I've always returned to the sexiness of Python and the ubiquity of
Javascript.
However, in recent times, I've found Python sadly lacking on a number of fronts,
e.g.
.. more
1. **Abysmal multi-core support.**
The `multiprocessing <http://docs.python.org/library/multiprocessing.html>`_
module is a joke and if it were not for the `ugly Prolog-inspired syntax
<http://damienkatz.net/2008/03/what_sucks_abou.html>`_, I'd have switched to
Erlang long ago.
2. **Fragmented networking support.**
`Twisted <http://twistedmatrix.com/>`_ is great, but forces you into callback
hell. `Eventlet <http://eventlet.net/>`_ and friends make good use of
`greenlets <http://codespeak.net/py/0.9.2/greenlet.html>`_ but still can't
make use of those spare cores on my servers -- `Spawning
<http://pypi.python.org/pypi/Spawning>`_ helps though. The kqueue/epoll
support in the standard library were, until relatively recently, `broken
<http://bugs.python.org/issue5910>`_ or non-existent. At least `pyev
<http://code.google.com/p/pyev/>`_ is cool, but there aren't any decent
frameworks built on it!
3. **Difficult to secure.**
Want to build your own App Engine like service? Good luck securing Python!
It's possible, but we, the open source community, have yet to deliver. Mark
Seaborn has done some great work getting `Python onto Native Client
<http://lackingrhoticity.blogspot.com/2009/06/python-standard-library-in-native.html>`_
but you'd still need to port all your C Extensions over. PyPy has a great
`sandbox <http://codespeak.net/pypy/dist/pypy/doc/sandbox.html>`_, but you
can't use newer Python features nor those C Extensions and, to boot, the
networking support sucks.
4. **Painful to optimise.**
Until `PyPy's JIT
<http://codespeak.net/pypy/trunk/pypy/doc/jit/overview.html>`_ or `Unladen
Swallow <http://code.google.com/p/unladen-swallow/>`_ lands, the main way to
optimise that slow running Python function is to write C extensions. This is
a pain filled process. `Cython <http://www.cython.org/>`_ definitely makes it
easier, but you then have to deal with figuring out the limitations of
Cython's syntax!
Now, until last week, I'd just put up with all the problems and waited for `PyPy
<http://codespeak.net/pypy/dist/pypy/doc/>`_ to mature. And when `Go
<http://golang.org/>`__ -- the shiny, new programming language from Google --
came along, I took a brief look and then dismissed it forthwith.
Sure, it looked like a nice programming language. And, sure, the guys behind it
-had made some of the biggest contributions to computer science to date,
-including: UNIX, regular expressions, Plan 9 and even UTF-8! But I still didn't
-see the point in switching to Go as my primary language.
+had made some of the biggest contributions to computing to date, including:
+UNIX, regular expressions, Plan 9 and even UTF-8! But I still didn't see the
+point in switching to Go as my primary language.
But then, a few days ago, whilst reading this `wonderful rant
<http://www.xent.com/pipermail/fork/Week-of-Mon-20091109/054578.html>`_ by Jeff
Bone on the poor state of today's programming languages, `@evangineer
<http://twitter.com/evangineer>`_ pointed out that Go had rudimentary support
for `Native Client <http://code.google.com/p/nativeclient/>`_!
And within 24 hours, I was a Go convert. Now don't get me wrong, Python and I
will always be good friends, but there's just no competing with Go. Why?
1. **Native Client (NaCl) support.**
`NaCl <http://code.google.com/p/nativeclient/>`_, like its distant cousin
`Vx32 <http://pdos.csail.mit.edu/~baford/vm/>`_, allows one to safely execute
untrusted "native code", e.g. C code. It's one of the coolest open source
projects to come out of Google!
The most interesting application of such technology is of course as a way to
allow for dynamic loading of browser extensions, e.g. `Native Client in
Google Chrome
<http://code.google.com/p/nativeclient/wiki/NativeClientInGoogleChrome>`_.
This is useful 'cos, despite the crazy speeds of `V8
<http://code.google.com/p/v8/>`_, you really don't want to be writing the
`metaverse <http://en.wikipedia.org/wiki/Metaverse>`_ in Javascript!
Now, for those of you who might think that this is a return to to the world
of crap that was ActiveX and Java applets, I'll explain later how NaCl can be
very much in the spirit of the Open Web. However, first let me explain why we
shouldn't necessarily be too enamoured with Javascript:
* **Javascript has no security model.** If you were to do a client-side
mashup between say your banking application and a photo application, there
is nothing stopping the photo app from having fun with your financial data.
`Caja <http://code.google.com/p/google-caja/>`_ is definitely amazing work
in this regard, but requires apps to run within containers which most
aren't geared to do -- not to mention the performance hit. `ES5
<http://www.ecma-international.org/publications/files/drafts/tc39-2009-050.pdf>`_
will make life a little better in this regard, but that's still a while off...
* **Javascript has no decent concurrency model.** Single-threaded execution
was fine when all we were doing were image replacements on mouseover, but
today's web apps could really do with some form of concurrency model.
The best we could seemingly come up with is the piece of crap that are `Web
Workers <http://dev.w3.org/html5/workers/>`_ in HTML5. And `Flapjax
<http://www.flapjax-lang.org/>`_, while it manages to bring functional
reactivity to the browser, sadly ignores the whole issue of security.
So it was in this context that we (Espians) worked on things like the
`webkit_bridge
<http://github.com/tav/plexnet/tree/master/source/client/webkit_bridge/>`_ --
to act as an interface between the browser's DOM and a PyPy-based interpreter
providing a safe, concurrent, `object-capability
<http://en.wikipedia.org/wiki/Object-capability_model>`_ based language
called λscript.
But, as my friend Ade would say, Go + NaCl offers a more attractive path of
least resistance! Google are already putting resources behind Chrome, Go and
NaCl -- there's no real reason (technical or otherwise) to duplicate the
work! All we need to do is focus on implementing λscript using Go!
And since people could create apps and services using Go itself, λscript can
be a very minimal layer between the various NaCl processes -- even less work!
Now as to how this could be done in the spirit of the Open Web, consider
this:
* NaCl binaries are bloated beasts. It makes sense instead to come up with a
source based packaging structure similar to ebuilds/setuptools/&c. for apps
and services -- these can then be compiled by the client thanks to the
super-fast compilation feature of Go! So we can have "view source" *and*
secure apps!
Now, we are still a while away from the any of this happening and the NaCl
support within Go `is
<http://github.com/tav/go/tree/master/src/pkg/exp/nacl/>`_ `very
<http://github.com/tav/go/blob/master/src/pkg/syscall/asm_nacl_386.s>`_
`experimental <http://github.com/tav/go/blob/master/src/all-nacl.bash>`_, but
I'm sure it'll improve in time -- especially given the following point.
2. **Google backing.**
Corporate sponsorship tend to make projects worse off -- but with the various
Chrome, NaCl and Go projects, Google have really put together great teams and
resourced them well. And there are lots of Google fanboys who will happily
contribute their time to such projects too -- making them even better!
3. **Go is a decent language.**
Despite seemingly having ignored most of the advances in computer science in
the last 20 years, Go is surprisingly a fun language to code in. The standard
library packages are an impressive start. And you can definitely feel the
influence of Python.
However, runtime performance is an issue for the moment -- there are enough
micro-benchmarks showing Python to be more performant in certain contexts.
This will change though, as:
a) The packages in the standard library are worked on. There are a lot of low
hanging optimisations to make here. A `recent commit
<http://github.com/tav/go/commit/5e0e8e35d5df2533fc7beff9feecbe56333c164e>`_
improved the regexp package by a factor of 3-20x!
b) The compilers are worked on. Right now, ``gccgo`` is more performant at
runtime but lacks various features, whilst the ``6g`` series has more
features and compiles faster. At some point, the various compilers will
meet in some form, yielding more performant code all round.
c) The new garbage collector is worked on. The current one is rather naive
but as I understand it, they already have a much more performant one in
the works.
The syntax makes a pleasant compromise between C and Python. The
documentation system is excellent -- and the testing framework shows promise.
The only thing I miss in this regard is having some equivalent to `doctest
<http://docs.python.org/library/doctest.html>`_ -- this should be possible
once ``pkg/exp/eval`` for the Go interpreter matures though.
Of course, goroutines rock! Who can say no to a typed-variant of the
`Ï-calculus <http://en.wikipedia.org/wiki/Pi_calculus>`_? Not to mention
being able to write code like ``go fuck_yourself()`` ;p
But the real fun is with the interfaces -- Python's `duck-typing
<http://en.wikipedia.org/wiki/Duck_typing>`_ brought to a statically typed
language! Who'd have thought? It really is quite brilliant -- at least it
will be once a few decent patterns emerge and are adopted. Until then I
expect people to do all kinds of crazy things with them.
The only thing I (and seemingly a lot of others) really miss is having first
class containers which can handle generic data types like with Python's
``list``, ``dict``, &c. This is possible in Go right now, but you have to
unbox them everytime which I'd rather not be doing...
I've also seen a lot of people complain about the lack of exception handling
in Go. I'm not sure what those people are talking about. Go has excellent
exception handling. The "comma, ok" pattern is elegant enough and the
``defer`` statement provides a very good equivalent to the usual
``try/finally`` and some of the ``with`` patterns in Python.
In any case, I hope I make a reasonable case for why moving to Go might be
worthwhile. Over the coming weeks, I'll continue this by documenting my
adventures in the land of Go.
If you'd like to follow along, `keep posted by following me
<http://twitter.com/tav>`_ on Twitter and let me know what you think in the
comments below. Thanks!
\ No newline at end of file
|
tav/oldblog
|
1017a0eb13247478b632e039d77b995b1d0d0085
|
Adding a .. more to the latest article to truncate it on the blog frontpage.
|
diff --git a/twitter-golang-list-go-mirror-on-github.txt b/twitter-golang-list-go-mirror-on-github.txt
index 60c4a78..489c101 100644
--- a/twitter-golang-list-go-mirror-on-github.txt
+++ b/twitter-golang-list-go-mirror-on-github.txt
@@ -1,66 +1,68 @@
=========================================
Twitter #golang List, Go Mirror on GitHub
=========================================
:X-Created: [2009-11-26, 17:24]
.. raw:: html
<div class="float-right">
<a href="http://github.com/tav/go" title="Go Mirror on GitHub"><img
src="http://img.skitch.com/20091126-feabbk2hfpdyqgcmg1jhiqsd4h.png"
alt="Go Mirror on GitHub" width="275px" height="348px" /></a>
</div>
I've started a Twitter List of those in the community working on the Go
language, libraries, apps or articles:
* http://twitter.com/tav/golang
You should `follow it <http://twitter.com/tav/golang>`_ to keep track of the
fast-moving developments and let me know -- either in the comments or via `@tav
<http://twitter.com/tav>`_ -- if I should add you to the list.
And, oh, could we all please normalise on using the ``#golang`` hashtag please?
The ``#go`` hashtag is used for too many other things -- including `that game
<http://en.wikipedia.org/wiki/Go_(game)>`_ that some of us love.
I've also started to maintain a `Git mirror of the Go repository
<http://github.com/tav/go>`_ on GitHub. You should `watch it
<http://github.com/tav/go>`_ to stay informed of changes to the Go language.
Now, as I explain in the `getting started with git
<http://www.espians.com/getting-started-with-git.html>`_ article, I consider Git
and Mercurial to be pretty equivalent. The only reason I prefer Git is due to
the wonderful service that is `GitHub <http://github.com>`_.
+.. more
+
Not only does it offer a far better social experience, but it's interface is
much better than what Google Code or `bitbucket <http://bitbucket.org/>`_
currently offer. Now, to get started with using the Git mirror, just do:
.. raw:: html
<pre class="cmd-line">
<span class="cmd-ps1">$</span> git clone git://github.com/tav/go.git
</pre>
You can then follow the normal `installation instructions
<http://golang.org/doc/install.html>`_ to set the environment variables and then
run ``./all.bash`` inside ``$GOROOT/src``.
Note that by default, the master branch will be checked out -- if you'd rather
not be on the cutting edge, then check out the ``release`` tag using:
.. raw:: html
<pre class="cmd-line">
<span class="cmd-ps1">$</span> git checkout release
</pre>
Besides being able to track the language developments using GitHub, the main
advantage of the Git mirror is that you can now use it as a ``git submodule``
within your own repositories!
This is the main reason I setup the mirror -- using the wonderful `hg-git plugin
<http://hg-git.github.com/>`_ by Scott -- but I hope it proves useful to some of
you too. Let me know if it does!
\ No newline at end of file
|
tav/oldblog
|
859ef51cc1ef2daa6d26b4f694b787f3bb3acd62
|
Twitter #golang List and Go Mirror on GitHub article.
|
diff --git a/twitter-golang-list-go-mirror-on-github.txt b/twitter-golang-list-go-mirror-on-github.txt
new file mode 100644
index 0000000..60c4a78
--- /dev/null
+++ b/twitter-golang-list-go-mirror-on-github.txt
@@ -0,0 +1,66 @@
+=========================================
+Twitter #golang List, Go Mirror on GitHub
+=========================================
+
+:X-Created: [2009-11-26, 17:24]
+
+.. raw:: html
+
+ <div class="float-right">
+ <a href="http://github.com/tav/go" title="Go Mirror on GitHub"><img
+ src="http://img.skitch.com/20091126-feabbk2hfpdyqgcmg1jhiqsd4h.png"
+ alt="Go Mirror on GitHub" width="275px" height="348px" /></a>
+ </div>
+
+I've started a Twitter List of those in the community working on the Go
+language, libraries, apps or articles:
+
+* http://twitter.com/tav/golang
+
+You should `follow it <http://twitter.com/tav/golang>`_ to keep track of the
+fast-moving developments and let me know -- either in the comments or via `@tav
+<http://twitter.com/tav>`_ -- if I should add you to the list.
+
+And, oh, could we all please normalise on using the ``#golang`` hashtag please?
+The ``#go`` hashtag is used for too many other things -- including `that game
+<http://en.wikipedia.org/wiki/Go_(game)>`_ that some of us love.
+
+I've also started to maintain a `Git mirror of the Go repository
+<http://github.com/tav/go>`_ on GitHub. You should `watch it
+<http://github.com/tav/go>`_ to stay informed of changes to the Go language.
+
+Now, as I explain in the `getting started with git
+<http://www.espians.com/getting-started-with-git.html>`_ article, I consider Git
+and Mercurial to be pretty equivalent. The only reason I prefer Git is due to
+the wonderful service that is `GitHub <http://github.com>`_.
+
+Not only does it offer a far better social experience, but it's interface is
+much better than what Google Code or `bitbucket <http://bitbucket.org/>`_
+currently offer. Now, to get started with using the Git mirror, just do:
+
+.. raw:: html
+
+ <pre class="cmd-line">
+ <span class="cmd-ps1">$</span> git clone git://github.com/tav/go.git
+ </pre>
+
+You can then follow the normal `installation instructions
+<http://golang.org/doc/install.html>`_ to set the environment variables and then
+run ``./all.bash`` inside ``$GOROOT/src``.
+
+Note that by default, the master branch will be checked out -- if you'd rather
+not be on the cutting edge, then check out the ``release`` tag using:
+
+.. raw:: html
+
+ <pre class="cmd-line">
+ <span class="cmd-ps1">$</span> git checkout release
+ </pre>
+
+Besides being able to track the language developments using GitHub, the main
+advantage of the Git mirror is that you can now use it as a ``git submodule``
+within your own repositories!
+
+This is the main reason I setup the mirror -- using the wonderful `hg-git plugin
+<http://hg-git.github.com/>`_ by Scott -- but I hope it proves useful to some of
+you too. Let me know if it does!
\ No newline at end of file
diff --git a/website/main.genshi b/website/main.genshi
index 80cc5a4..481af58 100644
--- a/website/main.genshi
+++ b/website/main.genshi
@@ -1,255 +1,270 @@
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/">
<?python
from time import time
from operator import lt
from urllib import urlencode
STATIC = 'http://cloud.github.com/downloads/tav/plexnet'
info = defined('info') and info or {}
author_info = authors.get(site_author_nick)
author = author_info[1]
version = info.get('x-version', '')
copyright = info.get('copyright', 'This work has been placed into the public domain')
description = info.get('subtitle', site_description)
subtitle = info.get('subtitle')
page_title = info.get('title') or info.get('__title__') or site_description
page_url = disqus_url = 'http://tav.espians.com' + '/' + info.get('__name__', 'index') + '.html'
if info.get('x-created') and lt(info['x-created'][1:8], "2009-07"):
disqus_url = 'http://www.asktav.com' + '/' + info.get('__name__', 'index') + '.html'
if info.get('__type__') == 'py':
description = info.get('title')
#if description:
# page_title = "%s (%s)" % (description, info.get('__title__'))
#else:
# page_title = "Source Package: %s" % info.get('__title__')
page_title = "Source Package: %s" % info.get('__title__')
MONTHS = [
'Zero Month',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
?>
<head>
<title><py:if test="not info.get('title')">${Markup(site_title)} » </py:if>${Markup(page_title)}</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<meta name="tweetmeme-title" content="${page_title}" />
<!-- disable some internet explorer features -->
<meta http-equiv="imagetoolbar" content="no" />
<meta name="MSSmartTagsPreventParsing" content="true" />
<!-- meta elements (search engines) -->
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<!-- meta elements (page data) -->
<meta name="author" content="${author}" />
<meta name="description" content="${description}" />
<meta name="version" content="${version}" />
<meta name="copyright" content="${copyright}" />
<meta name="document-rating" content="general" />
<meta http-equiv="content-language" content="en" />
<meta name="verify-v1" content="aLcMPDDmDYvgufTDcJiiCOgPt/FOooMmGHiPj64BMbU=" />
<link rel="icon" type="image/png" href="${STATIC}/gfx.aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds2.feedburner.com/${site_nick}" />
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="${STATIC}/css.screen.css?v=2" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="${STATIC}/css.${site_nick}.css?v=2" />
<style type="text/css" media="print">
/* @import url("${STATIC}/css.print.css"); */
#ignore-this { display: none; }
</style>
+ <style type="text/css">
+ .ascii-art .literal-block {
+ line-height: 1em !important;
+ }
+ .cmd-line {
+ background-color: #000;
+ color: #fff;
+ padding: 5px;
+ margin-left: 2em;
+ margin-right: 2em;
+ }
+ .cmd-ps1 {
+ color: #999;
+ }
+ </style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
</style>
<![endif]-->
<!-- javascript -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" />
<script type="text/javascript">
GOOGLE_ANALYTICS_CODE = "${site_analytics_code}";
DISQUS_FORUM = '${site_nick}';
PAGE_URI = '${page_url}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
</script>
<script type="text/javascript" src="${STATIC}/js.init.js" />
<!-- <script type="text/javascript"
src="http://w.sharethis.com/button/sharethis.js#tabs=web%2Cpost%2Cemail&charset=utf-8&style=rotate&publisher=65b4c59a-e069-4896-84b4-7d8d7dce2b77&headerbg=%230099cd&linkfg=%230099cd"></script> -->
</head>
<body>
<div id="main">
<div id="site-header">
<div id="site-info">
<a href="/" title="Asktav: A Blog by Tav"><img
id="site-logo" src="${STATIC}/gfx.logo.asktav.png" alt="Aaken Logo" width="64px" height="64px" /></a><form id="translation_form" class="menu-item-padding"><select id="lang_select" onchange="dotranslate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form><a href="/" class="menu-item"
title="${site_title}">Asktav Home</a><a href="archive.html" class="menu-item"
title="Site Index">Archives</a><a class="menu-item"
title="About Tav"
href="about-${site_author.lower()}.html">About
${site_author.title()}</a><a class="menu-item-final"
href="http://twitter.com/tav" title="Follow @tav" style="margin-right: 5px;"><img
src="${STATIC}/gfx.icon.twitter.png" alt="Follow @tav on Twitter"
class="absmiddle" /></a><a href="http://friendfeed.com/tav" style="margin-right: 5px;"
title="Follow tav on FriendFeed"><img src="${STATIC}/gfx.icon.friendfeed.png"
alt="FriendFeed" class="absmiddle" /></a><a
style="margin-right: 5px;"
href="http://github.com/tav" title="Follow tav on GitHub"><img
src="${STATIC}/gfx.icon.github.png" alt="GitHub" class="absmiddle"
/></a><a style="margin-right: 5px;"
href="http://www.facebook.com/asktav"
title="Follow Tav on Facebook"><img src="${STATIC}/gfx.icon.facebook.gif"
alt="Facebook" class="absmiddle" /></a><a
href="http://feeds2.feedburner.com/${site_nick}" rel="alternate"
type="application/rss+xml" title="Subscribe to the RSS Feed"><img
alt="RSS Feed" class="absmiddle"
src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png"
/></a><div
style="margin-top: 7px; font-family: Monaco,Courier New;"></div>
<hr class="clear" />
</div>
</div>
<div py:if="defined('content')">
<div class="article-nav">
</div>
<div class="article-title">
<div class="post-link"><a href="${info['__name__']}.html">${Markup(page_title)}</a></div>
<div class="additional-content-info">
<!-- <script language="javascript" type="text/javascript">
SHARETHIS.addEntry({
title:"${page_title.replace('"', r'\"')}",
url:'${page_url}',
}, {button:true});
</script>| --><a href="#disqus_thread" rel="disqus:${disqus_url}">Add a Comment</a>
<script type="text/javascript">
tweetmeme_url = '${page_url}';
tweetmeme_source = 'tav';
tweetmeme_service = 'bit.ly';
tweetmeme_style = 'compact';
</script>
| <div class="retweetbutton">
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
</div>
<div class="article-info">
» by <a href="http://tav.espians.com">tav</a><span py:if="info.get('x-created')"> on <span py:with="created=info['x-created']" class="post-date">${MONTHS[int(created[6:8])]} ${int(created[9:11])}, ${created[1:5]} @ <a href="http://github.com/tav/blog/commits/master/${info['__name__']}.txt">${created[-6:-1]}</a></span></span> <a href="http://creativecommons.org/publicdomain/zero/1.0/"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Cc-pd.svg/64px-Cc-pd.svg.png" width="20px" height="20px" alt="Public Domain" class="absmiddle" /></a>
<!--
last updated
<span py:with="created=info['__updated__']">
${created.strftime('%H:%M')}, ${created.strftime('%d %B %Y').lower()}
</span>
-->
</div>
</div>
<div py:if="not info.get('x-created') and not info.get('__type__') == 'py'" class="attention">
This is an early draft. Many sections are incomplete. A lot more is being written.
</div>
<div id="content">
<div py:content="Markup(content)"></div>
</div>
<br /><hr class="clear" />
<div class="article-nav" style="margin-bottom: 1.5em;">
<script type="text/javascript">
ARTICLE_NAME = '${info['__name__']}';
</script>
<script type="text/javascript" src="index.js?${int(time()/4)}" />
</div>
<div id="disqus-comments-section">
<script type="text/javascript">
disqus_url = "${disqus_url}";
disqus_title = "${Markup(page_title)}";
</script>
<div id="disqus_thread"></div><script type="text/javascript"
src="http://disqus.com/forums/${site_nick}/embed.js"></script><noscript><a
href="http://${site_nick}.disqus.com/?${urlencode({'url': disqus_url})}">View the forum
thread.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">Comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
</div>
<div py:if="defined('alternative_content')">
${Markup(alternative_content)}
</div>
<div><br /><br /></div>
</div>
</body>
</html>
|
tav/oldblog
|
ddbce170c71a1fc93531232b4349c20c19a34fb3
|
Ciao Python, Hola Go article.
|
diff --git a/ciao-python-hola-go.txt b/ciao-python-hola-go.txt
new file mode 100644
index 0000000..cc62359
--- /dev/null
+++ b/ciao-python-hola-go.txt
@@ -0,0 +1,225 @@
+=====================
+Ciao Python, Hola Go!
+=====================
+
+:X-Created: [2009-11-25, 15:27]
+
+.. raw:: html
+
+ <div class="float-right">
+ <a href="http://golang.org" title="Go Programming Language"><img
+ src="http://cloud.github.com/downloads/tav/plexnet/gfx.logo.go.black.png"
+ alt="Go" /></a>
+ </div>
+
+This is the first in a series of articles in which I'll document my move away
+from Python and the adventures encountered in using `Go <http://golang.org>`_ to
+build the `Plexnet <http://www.espians.com/plexnet.html>`_, an "internet
+operating system".
+
+My love affair with Python began in early 2000 when I `discovered Zwiki
+<http://zwiki.org/Tav>`_. And despite brief flings with other languages --
+Alice, E, Erlang, Lisp, Lua, Objective-C, OCaml, Oz, PowerShell, Ruby, Scheme,
+Smalltalk -- I've always returned to the sexiness of Python and the ubiquity of
+Javascript.
+
+However, in recent times, I've found Python sadly lacking on a number of fronts,
+e.g.
+
+.. more
+
+1. **Abysmal multi-core support.**
+
+ The `multiprocessing <http://docs.python.org/library/multiprocessing.html>`_
+ module is a joke and if it were not for the `ugly Prolog-inspired syntax
+ <http://damienkatz.net/2008/03/what_sucks_abou.html>`_, I'd have switched to
+ Erlang long ago.
+
+2. **Fragmented networking support.**
+
+ `Twisted <http://twistedmatrix.com/>`_ is great, but forces you into callback
+ hell. `Eventlet <http://eventlet.net/>`_ and friends make good use of
+ `greenlets <http://codespeak.net/py/0.9.2/greenlet.html>`_ but still can't
+ make use of those spare cores on my servers -- `Spawning
+ <http://pypi.python.org/pypi/Spawning>`_ helps though. The kqueue/epoll
+ support in the standard library were, until relatively recently, `broken
+ <http://bugs.python.org/issue5910>`_ or non-existent. At least `pyev
+ <http://code.google.com/p/pyev/>`_ is cool, but there aren't any decent
+ frameworks built on it!
+
+3. **Difficult to secure.**
+
+ Want to build your own App Engine like service? Good luck securing Python!
+ It's possible, but we, the open source community, have yet to deliver. Mark
+ Seaborn has done some great work getting `Python onto Native Client
+ <http://lackingrhoticity.blogspot.com/2009/06/python-standard-library-in-native.html>`_
+ but you'd still need to port all your C Extensions over. PyPy has a great
+ `sandbox <http://codespeak.net/pypy/dist/pypy/doc/sandbox.html>`_, but you
+ can't use newer Python features nor those C Extensions and, to boot, the
+ networking support sucks.
+
+4. **Painful to optimise.**
+
+ Until `PyPy's JIT
+ <http://codespeak.net/pypy/trunk/pypy/doc/jit/overview.html>`_ or `Unladen
+ Swallow <http://code.google.com/p/unladen-swallow/>`_ lands, the main way to
+ optimise that slow running Python function is to write C extensions. This is
+ a pain filled process. `Cython <http://www.cython.org/>`_ definitely makes it
+ easier, but you then have to deal with figuring out the limitations of
+ Cython's syntax!
+
+Now, until last week, I'd just put up with all the problems and waited for `PyPy
+<http://codespeak.net/pypy/dist/pypy/doc/>`_ to mature. And when `Go
+<http://golang.org/>`__ -- the shiny, new programming language from Google --
+came along, I took a brief look and then dismissed it forthwith.
+
+Sure, it looked like a nice programming language. And, sure, the guys behind it
+had made some of the biggest contributions to computer science to date,
+including: UNIX, regular expressions, Plan 9 and even UTF-8! But I still didn't
+see the point in switching to Go as my primary language.
+
+But then, a few days ago, whilst reading this `wonderful rant
+<http://www.xent.com/pipermail/fork/Week-of-Mon-20091109/054578.html>`_ by Jeff
+Bone on the poor state of today's programming languages, `@evangineer
+<http://twitter.com/evangineer>`_ pointed out that Go had rudimentary support
+for `Native Client <http://code.google.com/p/nativeclient/>`_!
+
+And within 24 hours, I was a Go convert. Now don't get me wrong, Python and I
+will always be good friends, but there's just no competing with Go. Why?
+
+1. **Native Client (NaCl) support.**
+
+ `NaCl <http://code.google.com/p/nativeclient/>`_, like its distant cousin
+ `Vx32 <http://pdos.csail.mit.edu/~baford/vm/>`_, allows one to safely execute
+ untrusted "native code", e.g. C code. It's one of the coolest open source
+ projects to come out of Google!
+
+ The most interesting application of such technology is of course as a way to
+ allow for dynamic loading of browser extensions, e.g. `Native Client in
+ Google Chrome
+ <http://code.google.com/p/nativeclient/wiki/NativeClientInGoogleChrome>`_.
+ This is useful 'cos, despite the crazy speeds of `V8
+ <http://code.google.com/p/v8/>`_, you really don't want to be writing the
+ `metaverse <http://en.wikipedia.org/wiki/Metaverse>`_ in Javascript!
+
+ Now, for those of you who might think that this is a return to to the world
+ of crap that was ActiveX and Java applets, I'll explain later how NaCl can be
+ very much in the spirit of the Open Web. However, first let me explain why we
+ shouldn't necessarily be too enamoured with Javascript:
+
+ * **Javascript has no security model.** If you were to do a client-side
+ mashup between say your banking application and a photo application, there
+ is nothing stopping the photo app from having fun with your financial data.
+
+ `Caja <http://code.google.com/p/google-caja/>`_ is definitely amazing work
+ in this regard, but requires apps to run within containers which most
+ aren't geared to do -- not to mention the performance hit. `ES5
+ <http://www.ecma-international.org/publications/files/drafts/tc39-2009-050.pdf>`_
+ will make life a little better in this regard, but that's still a while off...
+
+ * **Javascript has no decent concurrency model.** Single-threaded execution
+ was fine when all we were doing were image replacements on mouseover, but
+ today's web apps could really do with some form of concurrency model.
+
+ The best we could seemingly come up with is the piece of crap that are `Web
+ Workers <http://dev.w3.org/html5/workers/>`_ in HTML5. And `Flapjax
+ <http://www.flapjax-lang.org/>`_, while it manages to bring functional
+ reactivity to the browser, sadly ignores the whole issue of security.
+
+ So it was in this context that we (Espians) worked on things like the
+ `webkit_bridge
+ <http://github.com/tav/plexnet/tree/master/source/client/webkit_bridge/>`_ --
+ to act as an interface between the browser's DOM and a PyPy-based interpreter
+ providing a safe, concurrent, `object-capability
+ <http://en.wikipedia.org/wiki/Object-capability_model>`_ based language
+ called λscript.
+
+ But, as my friend Ade would say, Go + NaCl offers a more attractive path of
+ least resistance! Google are already putting resources behind Chrome, Go and
+ NaCl -- there's no real reason (technical or otherwise) to duplicate the
+ work! All we need to do is focus on implementing λscript using Go!
+
+ And since people could create apps and services using Go itself, λscript can
+ be a very minimal layer between the various NaCl processes -- even less work!
+ Now as to how this could be done in the spirit of the Open Web, consider
+ this:
+
+ * NaCl binaries are bloated beasts. It makes sense instead to come up with a
+ source based packaging structure similar to ebuilds/setuptools/&c. for apps
+ and services -- these can then be compiled by the client thanks to the
+ super-fast compilation feature of Go! So we can have "view source" *and*
+ secure apps!
+
+ Now, we are still a while away from the any of this happening and the NaCl
+ support within Go `is
+ <http://github.com/tav/go/tree/master/src/pkg/exp/nacl/>`_ `very
+ <http://github.com/tav/go/blob/master/src/pkg/syscall/asm_nacl_386.s>`_
+ `experimental <http://github.com/tav/go/blob/master/src/all-nacl.bash>`_, but
+ I'm sure it'll improve in time -- especially given the following point.
+
+2. **Google backing.**
+
+ Corporate sponsorship tend to make projects worse off -- but with the various
+ Chrome, NaCl and Go projects, Google have really put together great teams and
+ resourced them well. And there are lots of Google fanboys who will happily
+ contribute their time to such projects too -- making them even better!
+
+3. **Go is a decent language.**
+
+ Despite seemingly having ignored most of the advances in computer science in
+ the last 20 years, Go is surprisingly a fun language to code in. The standard
+ library packages are an impressive start. And you can definitely feel the
+ influence of Python.
+
+ However, runtime performance is an issue for the moment -- there are enough
+ micro-benchmarks showing Python to be more performant in certain contexts.
+ This will change though, as:
+
+ a) The packages in the standard library are worked on. There are a lot of low
+ hanging optimisations to make here. A `recent commit
+ <http://github.com/tav/go/commit/5e0e8e35d5df2533fc7beff9feecbe56333c164e>`_
+ improved the regexp package by a factor of 3-20x!
+
+ b) The compilers are worked on. Right now, ``gccgo`` is more performant at
+ runtime but lacks various features, whilst the ``6g`` series has more
+ features and compiles faster. At some point, the various compilers will
+ meet in some form, yielding more performant code all round.
+
+ c) The new garbage collector is worked on. The current one is rather naive
+ but as I understand it, they already have a much more performant one in
+ the works.
+
+ The syntax makes a pleasant compromise between C and Python. The
+ documentation system is excellent -- and the testing framework shows promise.
+ The only thing I miss in this regard is having some equivalent to `doctest
+ <http://docs.python.org/library/doctest.html>`_ -- this should be possible
+ once ``pkg/exp/eval`` for the Go interpreter matures though.
+
+ Of course, goroutines rock! Who can say no to a typed-variant of the
+ `Ï-calculus <http://en.wikipedia.org/wiki/Pi_calculus>`_? Not to mention
+ being able to write code like ``go fuck_yourself()`` ;p
+
+ But the real fun is with the interfaces -- Python's `duck-typing
+ <http://en.wikipedia.org/wiki/Duck_typing>`_ brought to a statically typed
+ language! Who'd have thought? It really is quite brilliant -- at least it
+ will be once a few decent patterns emerge and are adopted. Until then I
+ expect people to do all kinds of crazy things with them.
+
+ The only thing I (and seemingly a lot of others) really miss is having first
+ class containers which can handle generic data types like with Python's
+ ``list``, ``dict``, &c. This is possible in Go right now, but you have to
+ unbox them everytime which I'd rather not be doing...
+
+ I've also seen a lot of people complain about the lack of exception handling
+ in Go. I'm not sure what those people are talking about. Go has excellent
+ exception handling. The "comma, ok" pattern is elegant enough and the
+ ``defer`` statement provides a very good equivalent to the usual
+ ``try/finally`` and some of the ``with`` patterns in Python.
+
+In any case, I hope I make a reasonable case for why moving to Go might be
+worthwhile. Over the coming weeks, I'll continue this by documenting my
+adventures in the land of Go.
+
+If you'd like to follow along, `keep posted by following me
+<http://twitter.com/tav>`_ on Twitter and let me know what you think in the
+comments below. Thanks!
\ No newline at end of file
|
tav/oldblog
|
ffba31d3f1034c36ad820c83dd41f73b9a3614a1
|
Decided to go to media ecologies after all.
|
diff --git a/media-ecologies-and-postindustrial-production.txt b/media-ecologies-and-postindustrial-production.txt
index 53bd38a..0ed0ac9 100644
--- a/media-ecologies-and-postindustrial-production.txt
+++ b/media-ecologies-and-postindustrial-production.txt
@@ -1,36 +1,33 @@
=============================================
Media Ecologies And Postindustrial Production
=============================================
:X-Created: [2009-09-20, 20:17]
.. raw:: html
<div class="float-right" style="margin-bottom: 20px;">
<a href="http://www.espach.salford.ac.uk/sssi/p2p/"><img width="340px" height="512px"
src="http://cloud.github.com/downloads/tav/plexnet/gfx.poster.media-ecologies.small.png"
/></a>
</div>
-[**Update**: unfortunately, I won't be able to make it to the event -- I still
-recommend that everyone interested should go though!]
-
Myself and other crazy visionaries will be speaking in Manchester on the 3rd of
November for the `Media Ecologies Workshop
<http://www.espach.salford.ac.uk/sssi/p2p/>`_.
Put together by `Phoebe Moore
<http://www.espach.salford.ac.uk/page/Phoebe_Moore>`_, it promises to be a rare
gathering of various pioneering efforts -- from those working on collaborative
platforms to `distributed manufacturing
<http://www.espach.salford.ac.uk/sssi/p2p/programme.html>`_ efforts.
Sadly it's only a one day event -- so if anyone wants to organise a follow-up
event for the next day, it'd certainly be very welcome!
Some of the speakers like the illustrious `Michel Bauwens
<http://www.google.com/search?q=michel+bauwens>`_ of the `P2P Foundation
<http://blog.p2pfoundation.net/>`_ will be coming over from distant lands and
it'd be a shame to only get a day of their time.
In any case, I hope that you can come to Manchester for the event -- it's free!
\ No newline at end of file
|
tav/oldblog
|
fd17f2bd841532ed8b478db8bba073d6202a5f5e
|
Commenting out Ana Sandra's pecu allocation and updating non-attendance of media ecologies.
|
diff --git a/media-ecologies-and-postindustrial-production.txt b/media-ecologies-and-postindustrial-production.txt
index 0ed0ac9..53bd38a 100644
--- a/media-ecologies-and-postindustrial-production.txt
+++ b/media-ecologies-and-postindustrial-production.txt
@@ -1,33 +1,36 @@
=============================================
Media Ecologies And Postindustrial Production
=============================================
:X-Created: [2009-09-20, 20:17]
.. raw:: html
<div class="float-right" style="margin-bottom: 20px;">
<a href="http://www.espach.salford.ac.uk/sssi/p2p/"><img width="340px" height="512px"
src="http://cloud.github.com/downloads/tav/plexnet/gfx.poster.media-ecologies.small.png"
/></a>
</div>
+[**Update**: unfortunately, I won't be able to make it to the event -- I still
+recommend that everyone interested should go though!]
+
Myself and other crazy visionaries will be speaking in Manchester on the 3rd of
November for the `Media Ecologies Workshop
<http://www.espach.salford.ac.uk/sssi/p2p/>`_.
Put together by `Phoebe Moore
<http://www.espach.salford.ac.uk/page/Phoebe_Moore>`_, it promises to be a rare
gathering of various pioneering efforts -- from those working on collaborative
platforms to `distributed manufacturing
<http://www.espach.salford.ac.uk/sssi/p2p/programme.html>`_ efforts.
Sadly it's only a one day event -- so if anyone wants to organise a follow-up
event for the next day, it'd certainly be very welcome!
Some of the speakers like the illustrious `Michel Bauwens
<http://www.google.com/search?q=michel+bauwens>`_ of the `P2P Foundation
<http://blog.p2pfoundation.net/>`_ will be coming over from distant lands and
it'd be a shame to only get a day of their time.
In any case, I hope that you can come to Manchester for the event -- it's free!
\ No newline at end of file
diff --git a/pecu-allocations-by-tav.txt b/pecu-allocations-by-tav.txt
index d1b9d3f..8b4f9f1 100644
--- a/pecu-allocations-by-tav.txt
+++ b/pecu-allocations-by-tav.txt
@@ -1,546 +1,547 @@
=======================
Pecu Allocations by Tav
=======================
:X-Created: [2009-03-15, 10:14]
.. image:: http://cloud.github.com/downloads/tav/plexnet/gfx.aaken.png
:class: float-right
Hundreds of people have -- knowingly or not -- had a *direct* impact on my
work/vision. Their belief, inspiration, energy, encouragement, suggestions,
criticisms, support (both emotional and financial), tasty treats and hard work
has been phenomenal!
I'd like to reward them with some life-time tav-branded `pecu allocations
<http://www.thruflo.com/2009/06/09/tav-describes-pecus.html>`_.
Since I'm not making any pecu payouts at the moment, they're not worth much yet
-- but I hope one day that those who've helped me will feel the gratitude =)
See below for the full list of `pecu
<http://www.thruflo.com/2009/06/09/tav-describes-pecus.html>`_ allocations.
.. more
The following individuals have put in a lot to make my vision a reality and I'd
like to reward them with **200,000** pecus each:
.. class:: double-column
* Alex Tomkins
* Brian Deegan
* Chris Macrae
* Cris Pearson
* Daniel Biddle
* Danny Bruder
* David Pinto
* Inderpaul Johar
* James Arthur (+200,000)
* Jeffry Archambeault
* John McCane-Whitney
* Liliana Avrushin
* Luke Graybill
* Mamading Ceesay (+50,000)
* Martyn Hurt
* Matthieu Rey-Grange
* Mathew Ryden (+100,000)
* Nadine Gahr
* Nathan Staab
* Narmatha Murugananda
* Navaratnam Para
* Nicholas Midgley
* Ãyvind Selbek (+200,000)
* Sofia Bustamante
* Sean B. Palmer (+100,000)
* Stefan Plantikow
* Tim Jenks
* Tiziano Cirillo
* Tom Salfield
* Yan Minagawa
The following beautiful creatures have helped at various critical junctures or
laid key foundations. For this they get **20,000** pecus each:
.. class:: double-column
* Aaron Swartz
* Adam Langley
* Ade Thomas
* Adnan Hadzi
* Alex Greiner
* Alex Pappajohn
* Allen Short
* Andreas Dietrich
* Andrew Kenneth Milton
* Anne Biggs
* Anne Helene Wirstad
* Anette Hvolbæk
* Bryce Wilcox-O'Hearn
* Charles Goodier
* Chris Wood
* Claire Assis
* David Bovill
* Derek Richards
* Eric Hopper
* Eric Wahlforss
* Erik Möller
* Erol Ziya
* Ephraim Spiro
* Fenton Whelan
* Fergus Doyle
* Gary Alexander
* Gloria Charles
* Guido van Rossum
* Guilhem Buzenet
* Howard Rheingold
* Itamar Shtull-Trauring
* Jacob Everist
* Jan Ludewig
* Jill Lundquist
* Jim Carrico
* Jo Walsh
* Joe Short
* Joerg Baach
* John Hurliman
* Josef Davies-Coates
* Henri Cattan
* Henry Hicks
* Ka Ho Chan
* Karin Kylander
* Karina Arthur
* Katie Miller
* Kisiyane Roberts
* Laura Tov
* Lesley Donna Williams
* Lucie Rey-Grange
* Maciej Fijalkowski
* Mark Poole
* Maria Glauser
* Maria Chatzichristodoulou
* Matthew Sellwood
* Matthew Skinner
* Mayra Graybill
* Mia Bittar
* Mohan Selladurai
* Neythal (Sri Lanka)
* Nolan Darilek
* Olga Zueva
* Paul Böhm
* Phillip J. Eby
* Pierre-Antoine Tetard
* Ricky Cousins
* Salim Virani
* Saritah (Sarah Louise Newman ?)
* Saul Albert
* Shalabh Chaturvedi
* Simeon Scott
* Simon Michael
* Simon Fox
* Simon Reynolds
* Stephan Karpischek
* Steve Alexander
* Suhanya Babu
* Tavin Cole
* Thamilarasi Siva
* Tim Berners-Lee
* Tom Owen-Smith
* Vanda Petanjek
* Xiao Xuan Guo
These lovely supporters get **2,000** pecus each:
+.. Ana Sandra Ruiz Entrecanales
+
.. class:: double-column
* Adam Burns
* Adam Karpierz (Poland)
* Adam Perfect
* Adam Wern
* Adir Tov
* Agathe Pouget-Abadie
* Al Tepper
* Alan Wagenberg
* Alex Bustamante
* Alexander Wait (USA)
* Alice Fung
-* Ana Sandra Ruiz Entrecanales
* Andreas Kotes
* Andreas Schwarz
* Andrius Kulikauskas
* Andy Dawkins
* Andy McKay
* Andrew M. Kuchling
* Andrew McCormick
* Angela Beesley Starling
* Anna Gordon-Walker
* Anna Rothkopf
* Annalisa Fagan
* Anne Doyle
* Anselm Hook
* Ante Pavlov
* Arani Siva
* Ash Gerrish
* Ashley Siple
* Auro Tom Foxtrot
* Azra Gül
* Beatrice Wessolowski
* Ben Pirt
* Ben Swartz
* Benjamin Geer
* Benny "Curus" Amorsen
* Bernard Lietaer
* Blake Ludwig
* Boian Rodriguez Nikiforov
* Bram Cohen
* Brandon Wiley
* Bree Morrison
* Brenton Bills
* Brian Coughlan
* Briony "Misadventure" (UK)
* Callum Beith
* Candie Duncan
* Carl Ballard Swanson
* Carl Friedrich Bolz
* Céline Seger
* Chai Mason
* Charley Quinton
* Chris Cook
* Chris Davis
* Chris Heaton
* Chris McDonough
* Chris Withers
* Christoffer Hvolbaek
* Christopher Satterthwaite
* Christopher Schmidt
* Clara Maguire
* Cory Doctorow
* Craig Hubley
* Cyndi Rhoades
* Damiano VukotiÄ
* Dan Brickley
* Daniel Harris
* Daniel Magnoff
* Dante-Gabryell Monson
* David Bausola
* David Cozens
* David Goodger
* David Mertz
* David Midgley
* David Mills
* David Saxby
* Darran Edmundson
* Darren Platt
* Debra Bourne (UK)
* Dharushana Muthulingam
* Dermot ? (UK)
* Dimitris Savvaidis
* Dominik Webb
* Donatella Bernstein
* Dorothee Olivereau
* Dmytri Kleiner
* Earle Martin
* Edward Saperia
* Eléonore De Prunelé
* Elisabet Sahtouris
* Elkin Gordon Atwell
* Elmar Geese
* Emma Wigley
* Emmanuel Baidoo
* Erik Stewart
* Fabian Kyrielis
* Farhan Rehman
* Femi Longe
* Felicity Wood
* Felix Iskwei
* Florence David
* Francesca Cerletti (UK)
* Francesca Romana Giordano
* Gabe Wachob
* Gabrielle Hamm
* Gareth Strangemore-Jones
* Gary Poster
* Gaurav Pophaly
* Gavin Starks
* Gemma Youlia Dillon
* Geoff Jones
* Geoffry Arias
* George Nicholaides
* Gerry Gleason
* Giles Mason
* Glyph Lefkowitz
* Gordon Mohr
* Grant Stapleton
* Greg Timms
* Gregor J. Rothfuss
* Guy Kawasaki
* Hannah Harris
* Harriet Harris
* Heather Wilkinson
* Helen Aldritch
* Henry Bowen
* Holly Lloyd
* Holly Porter
* Ian Clarke
* Ian Hogarth
* Ida Norheim-Hagtun
* Igor Tojcic
* Ilze Black
* Inge Rochette
* James Binns
* James Cox (UK)
* James Howison (Australia)
* James Hurrell
* James McKay (Switzerland)
* James Stevens
* James Sutherland
* James Wallace
* Jan-Klaas Kollhof
* Jane Moyses
* Javier Candeira
* Jeannie Cool
* Jeremie Miller
* Jessica Bridges-Palmer
* Jim Ley
* Jimmy Wales
* Joanna O'Donnell
* Joe Geldart (UK)
* Joey DeVilla
* John Bywater
* John Cassidy
* John Lea
* John "Sayke" ?
* Joi Ito
* Jon Bootland
* Jonathan Robinson
* Joni Davis ?
* Jose Esquer
* Joseph O'Kelly (UK)
* Joy Green
* Juan Pablo Rico
* Jubin Zawar
* Judith Martin
* Julia Forster
* Jurgen Braam
* Justin OâShaughnessy (UK)
* Ka-Ping Yee
* Kapil Thangavelu
* Karen Hessels
* Katerina Tselou
* Katja Strøm Cappelen
* Kath Short
* Katie Keegan
* Katie Prescott
* Katy Marks
* Kelly Teamey
* Ken Manheimer
* Kevin Hemenway
* Kevin Marks
* Kiran Jonnalagadda
* Kiyoto Kanda
* Lanchanie Dias Gunawardena
* Laura Scheffler
* Lauri Love
* Leon Rocha
* Lena Nalbach
* Leslie Vuchot
* Lewis Hart
* Libby Miller
* Lion Kimbro
* Lisa Colaco
* Lord Kimo
* Lottie Child
* Lucas Gonzalez
* Luke Francl
* Luke Kenneth Casson Leighton
* Luke Nicholson
* Luke Robinson
* Lynton Currill Kim-Wai Pepper
* Magnolia Slimm
* Manuel Sauer
* Maor Bar-Ziv
* Marco Herry
* Mark Brown
* Mark Chaplin
* Mark Hodge
* Mark S. Miller
* Markus Quarta
* Marguerite Smith
* Marshall Burns
* Martin Peck
* Mary Fee
* Matt Cooperrider
* Matthew Devney
* Mattis Manzel
* Mayra Vivo Torres
* Meghan Benton
* Meera Shah
* Menka Parekh
* Michael Linton
* Michael Maranda
* Michael Sparks
* Michel Bauwens
* Mike Linksvayer
* Mikey Weinkove
* Mitchell Jacobs
* Molly Webb
* Moraan Gilad
* Mostofa Zaman
* Navindu Katugampola
* Nathalie Follen
* Nick Hart-Williams
* Nick Ierodiaconou
* Nick Szabo
* Nicolas David
* Niels Boeing (Germany)
* Nils Toedtmann
* Nisha Patel
* Nishant Shah
* Noa Harvey
* Noah Slater
* Oliver Morrison
* Oliver Sylvester-Bradley
* Oz Mose
* Pamela McLean
* Paola Desiderio
* Paolo "xerox" Martini (UK)
* Pascale Scheurer
* Patrick Andrews
* Patrick Yiu
* Paul Everitt
* Paul Harrison
* Paul Mutton (UK)
* Paul Pesach
* Paul Robinett
* Peri Urban
* Pete Brownwell
* Petit-Pigeard Clotilde
* Phil G
* Phil Harris
* Piccia Neri
* Pietro Speroni di Fenizio
* \R. David Murray
* Rama Gheerawo
* Raph Levien
* Rasmacone Boothe
* Rasmus Tenbergen
* Rastko ?
* Ray Murray
* Raymond Hettinger
* Rayhan Omar
* Rebecca Harding
* Reem Martin
* Riccarda Zezza
* Rob Lord
* Robert De Souza
* Robert Kaye
* Robert Knowles
* Robin Upton
* Rodney Shakespeare
* Rohit Khare
* Roman Nosov
* Ron Briefel
* Ricardo Niederberger Cabral
* Richard Ford
* Richard Nelson
* Richard "coldfyre" Nicholas (USA)
* Roger Dingledine
* Romek Szczesniak
* Ross Evans (UK)
* Rufus Pollock
* Salim Fadhley (UK)
* Sam Brown
* Sam Geall
* Sam Joseph
* Sara Kiran
* Selas Mene
* Servane Mouazan
* Shahid Choudhry
* Shane Hughes
* Simon Bartlet
* Simon Persoff
* Simon Rawles
* Sonia Ali
* Sophie ? (Austria)
* Sophie Le Barbier
* Stan Rey-Grange
* Stayce Kavanaugh
* Stefan Baker
* Steffi Dayalan
* Stella Boeva
* Stephan Dohrn
* Stephen Wilmot
* Steve Jenson
* Steve Peake
* Steven Starr
* Su Nandy
* Suresh Fernando
* Suw Charman
* Sunir Shah
* Sym Von LynX
* Tamsin Lejeune
* Tanis Taylor
* Tansy E Huws
* Tess Ashwin
* Tim Wacker (USA)
* Tom D. Harry (UK)
* Tom Heiser
* Tom Longson
* Tom Williams
* Tommy Hutchinson
* Tommy Teillaud
* Toni Prug
* Toni Sola
* Tony Cook
* Tyler Eaves
* Ushani Suresh
* Veeral ?
* William Wardlaw-Rogers
* Wayne Siron
* Wes Felter
* Wybo Wiersma
* Zoe Young
And, finally, whilst I'm not currently making any pecu allocations to them, I
feel deeply indebted to these visionaries, musicians, coders and writers:
.. class:: double-column
* \A. R. Rahman
* Alan Kay
* Asian Dub Foundation
* Au Revoir Simone
* Bruce Sterling
* Buckminster Fuller (passed away)
* Daft Punk
* David Lynch
* Douglas Engelbart
* Fernando Perez
* India Arie
* Jeff Buckley (passed away)
* Kim Stanley Robinson
* Lawrence Lessig
* M.I.A.
* Mahatma Gandhi (passed away)
* Manu Chao
* Marc Stiegler
* Mark Pilgrim
* Marlena Shaw
* Massive Attack
* Michael Franti
* Muhammad Yunus
* Neal Stephenson
* Nouvelle Vague
* P.M.
* Paul Graham
* Peter Norvig
* Portishead
* Ray Charles (passed away)
* Ray Ozzie
* Richard P. Gabriel
* Tanya Stephens
* Ted Nelson
* Tim Peters
* Vannevar Bush (passed away)
* Vint Cerf
Thank you all!
\ No newline at end of file
|
tav/oldblog
|
4e0f920e6248bccd057570b006958c7d6f0518fa
|
Updating the poster image for the Media Ecologies workshop.
|
diff --git a/media-ecologies-and-postindustrial-production.txt b/media-ecologies-and-postindustrial-production.txt
index bf6e9fa..0ed0ac9 100644
--- a/media-ecologies-and-postindustrial-production.txt
+++ b/media-ecologies-and-postindustrial-production.txt
@@ -1,33 +1,33 @@
=============================================
Media Ecologies And Postindustrial Production
=============================================
:X-Created: [2009-09-20, 20:17]
.. raw:: html
<div class="float-right" style="margin-bottom: 20px;">
<a href="http://www.espach.salford.ac.uk/sssi/p2p/"><img width="340px" height="512px"
- src="http://cloud.github.com/downloads/tav/plexnet/gfx.poster.media-ecologies.jpg"
+ src="http://cloud.github.com/downloads/tav/plexnet/gfx.poster.media-ecologies.small.png"
/></a>
</div>
Myself and other crazy visionaries will be speaking in Manchester on the 3rd of
November for the `Media Ecologies Workshop
<http://www.espach.salford.ac.uk/sssi/p2p/>`_.
Put together by `Phoebe Moore
<http://www.espach.salford.ac.uk/page/Phoebe_Moore>`_, it promises to be a rare
gathering of various pioneering efforts -- from those working on collaborative
platforms to `distributed manufacturing
<http://www.espach.salford.ac.uk/sssi/p2p/programme.html>`_ efforts.
Sadly it's only a one day event -- so if anyone wants to organise a follow-up
event for the next day, it'd certainly be very welcome!
Some of the speakers like the illustrious `Michel Bauwens
<http://www.google.com/search?q=michel+bauwens>`_ of the `P2P Foundation
<http://blog.p2pfoundation.net/>`_ will be coming over from distant lands and
it'd be a shame to only get a day of their time.
In any case, I hope that you can come to Manchester for the event -- it's free!
\ No newline at end of file
|
tav/oldblog
|
9657f8d5d3ce9f5701f838dbf27c0bd5da2eaf32
|
Commenting out the sharethis button.
|
diff --git a/website/index.genshi b/website/index.genshi
index 99ccdb2..1a8daa3 100644
--- a/website/index.genshi
+++ b/website/index.genshi
@@ -1,103 +1,103 @@
<div xmlns:py="http://genshi.edgewall.org/">
<?python
from operator import lt
STATIC = 'http://cloud.github.com/downloads/tav/plexnet'
MONTHS = [
'Zero Month',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
last_post_name = ['']
def set_name(post):
last_post_name[0] = post['__name__']
return last_post_name[0]
site_url = 'http://tav.espians.com'
?>
<style type="text/css">
.more { display: none; }
.more-link { display: block; }
</style>
<div id="site-welcome">Thanks for coming to Asktav<em>!</em> Other articles
you might like:</div>
<ul>
<li>
<a href="http://www.espians.com/plexnet.html">Plexnet</a>
<br /><span class="index-link-info">A Set of Open Web Standards</span>
</li>
</ul>
<div py:for="post in sorted([item for item in items if item.get('x-created') and item.get('x-type', 'blog') == 'blog'], key=lambda x: x['x-created'], reverse=True)[:60]">
<?python
post_url = disqus_url = 'http://tav.espians.com' + '/' + set_name(post) + '.html'
if lt(post['x-created'][1:8], "2009-07"):
disqus_url = 'http://www.asktav.com' + '/' + post['__name__'] + '.html'
?>
<div class="post-title">
<div class="post-link"><a href="${set_name(post)}.html">${Markup(post['title'])}</a></div>
<div>
<div class="float-right">
- <script language="javascript" type="text/javascript">
+ <!--<script language="javascript" type="text/javascript">
SHARETHIS.addEntry({
title:"${post['title'].replace('"', r'\"')}",
url:'${post_url}',
}, {button:true});
- </script>| <a href="${post['__name__']}.html#disqus_thread" rel="disqus:${disqus_url}">Comment!</a>
+ </script>| --><a href="${post['__name__']}.html#disqus_thread" rel="disqus:${disqus_url}">Comment!</a>
<script type="text/javascript">
tweetmeme_url = '${post_url}';
tweetmeme_source = 'tav';
tweetmeme_service = 'bit.ly';
tweetmeme_style = 'compact';
</script>
| <div class="retweetbutton">
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
</div>
» by <span><a href="http://tav.espians.com">tav</a></span> on <span py:with="created=post['x-created']" class="post-date">${MONTHS[int(created[6:8])]} ${int(created[9:11])}, ${created[1:5]} @ <a href="http://github.com/tav/blog/commits/master/${post['__name__']}.txt">${created[-6:-1]}</a></span> <a href="http://creativecommons.org/publicdomain/zero/1.0/"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Cc-pd.svg/64px-Cc-pd.svg.png" width="20px" height="20px" alt="Public Domain" class="absmiddle" /></a>
</div>
</div>
<div py:content="post.get('__lead__') and Markup(unicode(post['__lead__'], 'utf-8')) or Markup(unicode(post['__text__'], 'utf-8'))" class="blog-post" />
<div py:if="post.get('__lead__')"><a href="${set_name(post)}.html">Read moreâ¦</a></div>
<div class="post-footer">
<br /><br />
</div>
</div>
<div class="center"><a href="archive.html#article-${last_post_name[0]}">Read Previous Articles</a></div>
<div class="section-info buffer">
<table cellspacing="0" cellpadding="0" width="100%">
<tr>
<td><strong>${site_author.title()}'s Recent Web Activity</strong></td>
<td class="right">
<a href="http://friendfeed.com/${site_author_nick}">Friendfeed Archive</a>
<img class="absmiddle" src="${STATIC}/gfx.icon.friendfeed.png" alt="friendfeed" />
</td>
</tr>
</table>
</div>
<script type="text/javascript" src="http://friendfeed.com/embed/widget/${site_author_nick}?v=2&num=10&hide_logo=1&hide_subscribe=1"></script>
<div class="section-info buffer">
<table cellspacing="0" cellpadding="0" width="100%">
<tr>
<td><strong>Recent Blog Comments</strong></td>
<td class="right">
<a href="http://${site_nick}.disqus.com">Disqus Archive</a>
<img class="absmiddle" src="${STATIC}/gfx.icon.disqus.png" alt="disqus" />
</td>
</tr>
</table>
</div>
<div id="dsq-recentcomments" class="dsq-widget">
<script type="text/javascript" src="http://disqus.com/forums/${site_nick}/recent_comments_widget.js?num_items=20&avatar_size=92"></script>
</div>
</div>
diff --git a/website/main.genshi b/website/main.genshi
index 53595bd..80cc5a4 100644
--- a/website/main.genshi
+++ b/website/main.genshi
@@ -1,254 +1,255 @@
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/">
<?python
from time import time
from operator import lt
from urllib import urlencode
STATIC = 'http://cloud.github.com/downloads/tav/plexnet'
info = defined('info') and info or {}
author_info = authors.get(site_author_nick)
author = author_info[1]
version = info.get('x-version', '')
copyright = info.get('copyright', 'This work has been placed into the public domain')
description = info.get('subtitle', site_description)
subtitle = info.get('subtitle')
page_title = info.get('title') or info.get('__title__') or site_description
page_url = disqus_url = 'http://tav.espians.com' + '/' + info.get('__name__', 'index') + '.html'
if info.get('x-created') and lt(info['x-created'][1:8], "2009-07"):
disqus_url = 'http://www.asktav.com' + '/' + info.get('__name__', 'index') + '.html'
if info.get('__type__') == 'py':
description = info.get('title')
#if description:
# page_title = "%s (%s)" % (description, info.get('__title__'))
#else:
# page_title = "Source Package: %s" % info.get('__title__')
page_title = "Source Package: %s" % info.get('__title__')
MONTHS = [
'Zero Month',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
?>
<head>
- <title>${Markup(site_title)} » ${Markup(page_title)}</title>
+ <title><py:if test="not info.get('title')">${Markup(site_title)} » </py:if>${Markup(page_title)}</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<meta name="tweetmeme-title" content="${page_title}" />
<!-- disable some internet explorer features -->
<meta http-equiv="imagetoolbar" content="no" />
<meta name="MSSmartTagsPreventParsing" content="true" />
<!-- meta elements (search engines) -->
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="1 day" />
<!-- meta elements (page data) -->
<meta name="author" content="${author}" />
<meta name="description" content="${description}" />
<meta name="version" content="${version}" />
<meta name="copyright" content="${copyright}" />
<meta name="document-rating" content="general" />
<meta http-equiv="content-language" content="en" />
<meta name="verify-v1" content="aLcMPDDmDYvgufTDcJiiCOgPt/FOooMmGHiPj64BMbU=" />
<link rel="icon" type="image/png" href="${STATIC}/gfx.aaken.png" />
<link rel="alternate" type="application/rss+xml"
title="RSS Feed for ${site_title}"
href="http://feeds2.feedburner.com/${site_nick}" />
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="${STATIC}/css.screen.css?v=2" />
<link rel="stylesheet" type="text/css" media="screen" title="default"
href="${STATIC}/css.${site_nick}.css?v=2" />
<style type="text/css" media="print">
/* @import url("${STATIC}/css.print.css"); */
#ignore-this { display: none; }
</style>
<!--[if lte IE 8]>
<style type="text/css">
ol { list-style-type: disc; }
</style>
<![endif]-->
<!-- javascript -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" />
<script type="text/javascript">
GOOGLE_ANALYTICS_CODE = "${site_analytics_code}";
DISQUS_FORUM = '${site_nick}';
PAGE_URI = '${page_url}'
facebookXdReceiverPath = 'http://tav.espians.com/external/xd_receiver.html';
</script>
<script type="text/javascript" src="${STATIC}/js.init.js" />
- <script type="text/javascript" src="http://w.sharethis.com/button/sharethis.js#tabs=web%2Cpost%2Cemail&charset=utf-8&style=rotate&publisher=65b4c59a-e069-4896-84b4-7d8d7dce2b77&headerbg=%230099cd&linkfg=%230099cd"></script>
+ <!-- <script type="text/javascript"
+ src="http://w.sharethis.com/button/sharethis.js#tabs=web%2Cpost%2Cemail&charset=utf-8&style=rotate&publisher=65b4c59a-e069-4896-84b4-7d8d7dce2b77&headerbg=%230099cd&linkfg=%230099cd"></script> -->
</head>
<body>
<div id="main">
<div id="site-header">
<div id="site-info">
<a href="/" title="Asktav: A Blog by Tav"><img
id="site-logo" src="${STATIC}/gfx.logo.asktav.png" alt="Aaken Logo" width="64px" height="64px" /></a><form id="translation_form" class="menu-item-padding"><select id="lang_select" onchange="dotranslate(this);">
<option value="" id="select_language">Select Language</option>
<option value="&langpair=en|af" id="openaf">Afrikaans</option><option
value="&langpair=en|sq" id="opensq">Albanian</option><option
value="&langpair=en|ar" id="openar">Arabic (Ø§ÙØ¹Ø±Ø¨ÙØ©)</option><option
value="&langpair=en|be" id="openbe">Belarusian</option><option
value="&langpair=en|bg" id="openbg">Bulgarian (бÑлгаÑÑки)</option><option
value="&langpair=en|ca" id="openca">Catalan (català )</option><option
value="&langpair=en|zh-CN" id="openzh-CN">Chinese (䏿 [ç®ä½])</option><option
value="&langpair=en|zh-TW" id="openzh-TW">Chinese (䏿 [ç¹é«])</option><option
value="&langpair=en|hr" id="openhr">Croatian (hrvatski)</option><option
value="&langpair=en|cs" id="opencs">Czech (Äesky)</option><option
value="&langpair=en|da" id="openda">Danish (Dansk)</option><option
value="&langpair=en|nl" id="opennl">Dutch (Nederlands)</option><option
value="&langpair=en|et" id="openet">Estonian</option><option
value="&langpair=en|fa" id="openfa">Farsi/Persian</option><option
value="&langpair=en|tl" id="opentl">Filipino</option><option
value="&langpair=en|fi" id="openfi">Finnish (suomi)</option><option
value="&langpair=en|fr" id="openfr">French (Français)</option><option
value="&langpair=en|gl" id="opengl">Galician</option><option
value="&langpair=en|de" id="opende">German (Deutsch)</option><option
value="&langpair=en|el" id="openel">Greek (Îλληνικά)</option><option
value="&langpair=en|iw" id="openiw">Hebrew (×¢×ר×ת)</option><option
value="&langpair=en|hi" id="openhi">Hindi (हिनà¥à¤¦à¥)</option><option
value="&langpair=en|hu" id="openhu">Hungarian</option><option
value="&langpair=en|is" id="openis">Icelandic</option><option
value="&langpair=en|id" id="openid">Indonesian</option><option
value="&langpair=en|ga" id="openga">Irish</option><option
value="&langpair=en|it" id="openit">Italian (Italiano)</option><option
value="&langpair=en|ja" id="openja">Japanese (æ¥æ¬èª)</option><option
value="&langpair=en|ko" id="openko">Korean (íêµì´)</option><option
value="&langpair=en|lv" id="openlv">Latvian (latviešu)</option><option
value="&langpair=en|lt" id="openlt">Lithuanian (Lietuvių)</option><option
value="&langpair=en|mk" id="openmk">Macedonian</option><option
value="&langpair=en|ms" id="openms">Malay</option><option
value="&langpair=en|mt" id="openmt">Maltese</option><option
value="&langpair=en|no" id="openno">Norwegian (norsk)</option><option
value="&langpair=en|pl" id="openpl">Polish (Polski)</option><option
value="&langpair=en|pt" id="openpt">Portuguese (Português)</option><option
value="&langpair=en|ro" id="openro">Romanian (RomânÄ)</option><option
value="&langpair=en|ru" id="openru">Russian (Ð ÑÑÑкий)</option><option
value="&langpair=en|sr" id="opensr">Serbian (ÑÑпÑки)</option><option
value="&langpair=en|sk" id="opensk">Slovak (slovenÄina)</option><option
value="&langpair=en|sl" id="opensl">Slovenian (slovenÅ¡Äina)</option><option
value="&langpair=en|es" id="openes">Spanish (Español)</option><option
value="&langpair=en|sw" id="opensw">Swahili</option><option
value="&langpair=en|sv" id="opensv">Swedish (Svenska)</option><option
value="&langpair=en|th" id="openth">Thai</option><option
value="&langpair=en|tr" id="opentr">Turkish</option><option
value="&langpair=en|uk" id="openuk">Ukrainian (ÑкÑаÑнÑÑка)</option><option
value="&langpair=en|vi" id="openvi">Vietnamese (Tiếng Viá»t)</option><option
value="&langpair=en|cy" id="opency">Welsh</option><option
value="&langpair=en|yi" id="openyi">Yiddish</option>
</select></form><a href="/" class="menu-item"
title="${site_title}">Asktav Home</a><a href="archive.html" class="menu-item"
title="Site Index">Archives</a><a class="menu-item"
title="About Tav"
href="about-${site_author.lower()}.html">About
${site_author.title()}</a><a class="menu-item-final"
href="http://twitter.com/tav" title="Follow @tav" style="margin-right: 5px;"><img
src="${STATIC}/gfx.icon.twitter.png" alt="Follow @tav on Twitter"
class="absmiddle" /></a><a href="http://friendfeed.com/tav" style="margin-right: 5px;"
title="Follow tav on FriendFeed"><img src="${STATIC}/gfx.icon.friendfeed.png"
alt="FriendFeed" class="absmiddle" /></a><a
style="margin-right: 5px;"
href="http://github.com/tav" title="Follow tav on GitHub"><img
src="${STATIC}/gfx.icon.github.png" alt="GitHub" class="absmiddle"
/></a><a style="margin-right: 5px;"
href="http://www.facebook.com/asktav"
title="Follow Tav on Facebook"><img src="${STATIC}/gfx.icon.facebook.gif"
alt="Facebook" class="absmiddle" /></a><a
href="http://feeds2.feedburner.com/${site_nick}" rel="alternate"
type="application/rss+xml" title="Subscribe to the RSS Feed"><img
alt="RSS Feed" class="absmiddle"
src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png"
/></a><div
style="margin-top: 7px; font-family: Monaco,Courier New;"></div>
<hr class="clear" />
</div>
</div>
<div py:if="defined('content')">
<div class="article-nav">
</div>
<div class="article-title">
<div class="post-link"><a href="${info['__name__']}.html">${Markup(page_title)}</a></div>
<div class="additional-content-info">
- <script language="javascript" type="text/javascript">
+ <!-- <script language="javascript" type="text/javascript">
SHARETHIS.addEntry({
title:"${page_title.replace('"', r'\"')}",
url:'${page_url}',
}, {button:true});
- </script>| <a href="#disqus_thread" rel="disqus:${disqus_url}">Add a Comment</a>
+ </script>| --><a href="#disqus_thread" rel="disqus:${disqus_url}">Add a Comment</a>
<script type="text/javascript">
tweetmeme_url = '${page_url}';
tweetmeme_source = 'tav';
tweetmeme_service = 'bit.ly';
tweetmeme_style = 'compact';
</script>
| <div class="retweetbutton">
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
</div>
<div class="article-info">
» by <a href="http://tav.espians.com">tav</a><span py:if="info.get('x-created')"> on <span py:with="created=info['x-created']" class="post-date">${MONTHS[int(created[6:8])]} ${int(created[9:11])}, ${created[1:5]} @ <a href="http://github.com/tav/blog/commits/master/${info['__name__']}.txt">${created[-6:-1]}</a></span></span> <a href="http://creativecommons.org/publicdomain/zero/1.0/"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Cc-pd.svg/64px-Cc-pd.svg.png" width="20px" height="20px" alt="Public Domain" class="absmiddle" /></a>
<!--
last updated
<span py:with="created=info['__updated__']">
${created.strftime('%H:%M')}, ${created.strftime('%d %B %Y').lower()}
</span>
-->
</div>
</div>
<div py:if="not info.get('x-created') and not info.get('__type__') == 'py'" class="attention">
This is an early draft. Many sections are incomplete. A lot more is being written.
</div>
<div id="content">
<div py:content="Markup(content)"></div>
</div>
<br /><hr class="clear" />
<div class="article-nav" style="margin-bottom: 1.5em;">
<script type="text/javascript">
ARTICLE_NAME = '${info['__name__']}';
</script>
<script type="text/javascript" src="index.js?${int(time()/4)}" />
</div>
<div id="disqus-comments-section">
<script type="text/javascript">
disqus_url = "${disqus_url}";
disqus_title = "${Markup(page_title)}";
</script>
<div id="disqus_thread"></div><script type="text/javascript"
src="http://disqus.com/forums/${site_nick}/embed.js"></script><noscript><a
href="http://${site_nick}.disqus.com/?${urlencode({'url': disqus_url})}">View the forum
thread.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">Comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
</div>
<div py:if="defined('alternative_content')">
${Markup(alternative_content)}
</div>
<div><br /><br /></div>
</div>
</body>
</html>
|
apoltix/blockip
|
1ffbab07c99c9fa52762009eb2beb5bf24840bc2
|
Improved error handling. Added installer.
|
diff --git a/README b/README
index 09e31cc..980dae4 100644
--- a/README
+++ b/README
@@ -1,26 +1,28 @@
blockip 0.1
(C) Christian Rasmussen, apoltix, 2010.
Licensed under the MIT License (see LICENSE).
Python script for a quick and easy-to-remember way to add and delete IP-addresses to the iptables INPUT DROP list.
This utility requires superuser privileges (or rather, iptables does).
+Tested working on Ubuntu 10.04 Lucid Lynx. Should work on all OSes with iptables installed.
+
Usage: blockip [ips|-h|-a ip|-d ip|-l]
-h, --help:
Displays this message.
ips:
Adds IP-addresses to the block list. Example:
blockip 1.2.3.4 2.3.4.5
-a ip, --add ip:
Adds an IP-address to the block list. Example:
blockip -a 1.2.3.4
-d ip, --delete ip:
Removes an IP-address from the block list. Example:
blockip -d 1.2.3.4
-l, --list:
Lists the blocked IP-addresses.
-v, --version:
Displays the version of the utility."
\ No newline at end of file
diff --git a/blockip.py b/blockip.py
index 8d4b4b9..edd5d34 100644
--- a/blockip.py
+++ b/blockip.py
@@ -1,57 +1,63 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+# -*- author: Christian Rasmussen -*-
+# -*- github: http://github.com/apoltix/blockip -*-
+# -*- license: MIT License -*-
# blockip: easy-to-use command to add or delete an IP-address to the blocklist in iptables
import sys
import getopt
import subprocess
_name = "blockip"
_version = "0.1"
def main(argv):
try:
opts, args = getopt.getopt(argv, "ha:d:lv", ["help", "add=", "delete=", "list", "version"])
-
+
if len(opts) == 0:
# Adding without -a or --add: iptables 1.2.3.4 2.3.4.5
if len(args) > 0:
opts = []
for arg in args:
opts.append(("-a", arg))
# Display help if no args exist
else:
opts = [("-h","")]
-
+
for opt, arg in opts:
if opt in ("-h", "--help"):
help()
elif opt in ("-v", "--version"):
print version()
elif opt in ("-a", "--add"):
subprocess.call(["iptables", "-A", "INPUT", "-s", arg, "-j", "DROP"])
elif opt in ("-d", "--delete"):
subprocess.call(["iptables", "-D", "INPUT", "-s", arg, "-j", "DROP"])
elif opt in ("-l", "--list"):
subprocess.call(["iptables", "-L", "-n"])
except getopt.GetoptError, err:
- print "Error: " + str(err)
+ print "blockip error: " + str(err)
+ sys.exit(2)
+ except:
+ print "blockip error (unknown)."
sys.exit(2)
def version():
global _name, _version
return _name + " " + _version
def help():
print version()
print "Usage: blockip [ips|-h|-a ip|-d ip|-l]\n"
print "-h, --help: Displays this message."
print "ips: Adds IP-addresses to the block list. Example:\n\tblockip 1.2.3.4 2.3.4.5"
print "-a ip, --add ip: Adds an IP-address to the block list. Example:\n\tblockip -a 1.2.3.4"
print "-d ip, --delete ip: Removes an IP-address from the block list. Example:\n\tblockip -d 1.2.3.4"
print "-l, --list: Lists the blocked IP-addresses."
print "-v, --version: Displays the version of the utility."
if __name__ == "__main__":
- main(sys.argv[1:])
+ main(sys.argv[1:])
\ No newline at end of file
diff --git a/install.sh b/install.sh
new file mode 100755
index 0000000..9c438af
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,5 @@
+#!/bin/sh
+echo "Installing blockip..."
+sudo cp blockip.py /usr/bin/blockip
+sudo chmod +x /usr/bin/blockip
+echo "Installed blockip. Run by typing \"blockip\"."
|
apoltix/blockip
|
47917b517a97769d55d7b3b2686b97facdef60f2
|
Expanded README. Added .gitignore file.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5a1bd98
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+blockip.0.1.tgz
diff --git a/README b/README
index 570b2ff..09e31cc 100644
--- a/README
+++ b/README
@@ -1,6 +1,26 @@
blockip 0.1
(C) Christian Rasmussen, apoltix, 2010.
Licensed under the MIT License (see LICENSE).
Python script for a quick and easy-to-remember way to add and delete IP-addresses to the iptables INPUT DROP list.
+
+This utility requires superuser privileges (or rather, iptables does).
+
+Usage: blockip [ips|-h|-a ip|-d ip|-l]
+
+-h, --help:
+ Displays this message.
+ips:
+ Adds IP-addresses to the block list. Example:
+ blockip 1.2.3.4 2.3.4.5
+-a ip, --add ip:
+ Adds an IP-address to the block list. Example:
+ blockip -a 1.2.3.4
+-d ip, --delete ip:
+ Removes an IP-address from the block list. Example:
+ blockip -d 1.2.3.4
+-l, --list:
+ Lists the blocked IP-addresses.
+-v, --version:
+ Displays the version of the utility."
\ No newline at end of file
|
apoltix/blockip
|
93af5a0d98e1298d2d4daf78c92e9942763bc421
|
Oops. Now actually works.
|
diff --git a/blockip.py b/blockip.py
old mode 100755
new mode 100644
index 23f0ecf..8d4b4b9
--- a/blockip.py
+++ b/blockip.py
@@ -1,61 +1,57 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blockip: easy-to-use command to add or delete an IP-address to the blocklist in iptables
import sys
import getopt
import subprocess
_name = "blockip"
_version = "0.1"
def main(argv):
try:
opts, args = getopt.getopt(argv, "ha:d:lv", ["help", "add=", "delete=", "list", "version"])
if len(opts) == 0:
# Adding without -a or --add: iptables 1.2.3.4 2.3.4.5
if len(args) > 0:
opts = []
for arg in args:
opts.append(("-a", arg))
# Display help if no args exist
else:
opts = [("-h","")]
for opt, arg in opts:
- # print opt + ", " + arg
if opt in ("-h", "--help"):
help()
elif opt in ("-v", "--version"):
print version()
elif opt in ("-a", "--add"):
- print "Add " + str(arg)
- #subprocess.call(["iptables", "-A", "INPUT", "-s", arg, "-j", "DROP"])
+ subprocess.call(["iptables", "-A", "INPUT", "-s", arg, "-j", "DROP"])
elif opt in ("-d", "--delete"):
- pass
- #subprocess.call(["iptables", "-D", "INPUT", "-s", arg, "-j", "DROP"])
+ subprocess.call(["iptables", "-D", "INPUT", "-s", arg, "-j", "DROP"])
elif opt in ("-l", "--list"):
- pass
- #subprocess.call(["iptables", "-L", "-n"])
+ subprocess.call(["iptables", "-L", "-n"])
except getopt.GetoptError, err:
print "Error: " + str(err)
sys.exit(2)
def version():
global _name, _version
return _name + " " + _version
def help():
print version()
print "Usage: blockip [ips|-h|-a ip|-d ip|-l]\n"
print "-h, --help: Displays this message."
print "ips: Adds IP-addresses to the block list. Example:\n\tblockip 1.2.3.4 2.3.4.5"
print "-a ip, --add ip: Adds an IP-address to the block list. Example:\n\tblockip -a 1.2.3.4"
print "-d ip, --delete ip: Removes an IP-address from the block list. Example:\n\tblockip -d 1.2.3.4"
print "-l, --list: Lists the blocked IP-addresses."
print "-v, --version: Displays the version of the utility."
if __name__ == "__main__":
main(sys.argv[1:])
|
apoltix/blockip
|
f58d4a5af76416692d42f8210f607a866bb81c10
|
Added readme and license files.
|
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d6e721c
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,19 @@
+ Copyright (c) 2010 Christian Rasmussen
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
diff --git a/README b/README
new file mode 100644
index 0000000..570b2ff
--- /dev/null
+++ b/README
@@ -0,0 +1,6 @@
+blockip 0.1
+
+(C) Christian Rasmussen, apoltix, 2010.
+Licensed under the MIT License (see LICENSE).
+
+Python script for a quick and easy-to-remember way to add and delete IP-addresses to the iptables INPUT DROP list.
|
apoltix/blockip
|
498e54bf98b8bf93e982da8a7c836337adbd68c1
|
Initial import, working.
|
diff --git a/blockip.py b/blockip.py
new file mode 100755
index 0000000..23f0ecf
--- /dev/null
+++ b/blockip.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# blockip: easy-to-use command to add or delete an IP-address to the blocklist in iptables
+
+import sys
+import getopt
+import subprocess
+
+_name = "blockip"
+_version = "0.1"
+
+def main(argv):
+ try:
+ opts, args = getopt.getopt(argv, "ha:d:lv", ["help", "add=", "delete=", "list", "version"])
+
+ if len(opts) == 0:
+ # Adding without -a or --add: iptables 1.2.3.4 2.3.4.5
+ if len(args) > 0:
+ opts = []
+ for arg in args:
+ opts.append(("-a", arg))
+ # Display help if no args exist
+ else:
+ opts = [("-h","")]
+
+ for opt, arg in opts:
+ # print opt + ", " + arg
+ if opt in ("-h", "--help"):
+ help()
+ elif opt in ("-v", "--version"):
+ print version()
+ elif opt in ("-a", "--add"):
+ print "Add " + str(arg)
+ #subprocess.call(["iptables", "-A", "INPUT", "-s", arg, "-j", "DROP"])
+ elif opt in ("-d", "--delete"):
+ pass
+ #subprocess.call(["iptables", "-D", "INPUT", "-s", arg, "-j", "DROP"])
+ elif opt in ("-l", "--list"):
+ pass
+ #subprocess.call(["iptables", "-L", "-n"])
+ except getopt.GetoptError, err:
+ print "Error: " + str(err)
+ sys.exit(2)
+
+def version():
+ global _name, _version
+ return _name + " " + _version
+
+def help():
+ print version()
+ print "Usage: blockip [ips|-h|-a ip|-d ip|-l]\n"
+ print "-h, --help: Displays this message."
+ print "ips: Adds IP-addresses to the block list. Example:\n\tblockip 1.2.3.4 2.3.4.5"
+ print "-a ip, --add ip: Adds an IP-address to the block list. Example:\n\tblockip -a 1.2.3.4"
+ print "-d ip, --delete ip: Removes an IP-address from the block list. Example:\n\tblockip -d 1.2.3.4"
+ print "-l, --list: Lists the blocked IP-addresses."
+ print "-v, --version: Displays the version of the utility."
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
|
heracek/x36osy-producenti-konzumenti-processes
|
b8e2090c669bd7d29e0a88ffd4ebe1b033e512d9
|
Program vyzaduje parametry.
|
diff --git a/main.cpp b/main.cpp
index db8802f..c4a1137 100644
--- a/main.cpp
+++ b/main.cpp
@@ -36,570 +36,571 @@ Fronta **fronty;
char process_name[MAX_NAME_SIZE];
int sem_pristup_ke_fronte;
int sem_mohu_vlozit;
Shared *shared;
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
Prvek() :
cislo_producenta(0),
poradove_cislo(0),
pocet_precteni(0) { }
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
void init(int _cislo_producenta, int _poradove_cislo) {
this->cislo_producenta = _cislo_producenta;
this->poradove_cislo = _poradove_cislo;
this->pocet_precteni = 0;
}
};
class Fronta {
/**
* Pametove rozlozeni fronty:
Fronta:
Instance tridy Fronta:
[_size]
[_index_of_first]
Prvky fronty: (nasleduji okamzite za instanci Fronta)
[instance 0 (tridy Prvek) fronty]
[instance 1 (tridy Prvek) fronty]
...
[instance K_POLOZEK - 1 (tridy Prvek) fronty] (fixni pocet prvku)
*/
unsigned int _size;
unsigned int _index_of_first;
Prvek *_get_array_of_prvky() {
unsigned char *tmp_ptr = (unsigned char *) this;
tmp_ptr += sizeof(Fronta);
return (Prvek *) tmp_ptr;
}
Prvek* next_back() {
int i = (this->_index_of_first + this->_size) % K_POLOZEK;
return &(this->_get_array_of_prvky()[i]);
}
public:
void init() {
this->_size = 0;
this->_index_of_first = 0;
}
int size() {
return this->_size;
}
Prvek* front();
void push(Prvek &prvek);
void pop();
static int get_total_sizeof() {
return sizeof(Fronta) + sizeof(Prvek) * K_POLOZEK;
}
};
typedef Fronta *p_Fronta;
struct Shared {
/**
*
* Struktura sdilene pameti:
Shared:
[pokracovat_ve_vypoctu]
Fronta 0:
[instance 0 tridy Fronta]
[prveky fronty 0]
Fronta 1:
[instance 1 tridy Fronta]
[prveky fronty 1]
...
Fronta M_PRODUCENTU - 1:
[instance M_PRODUCENTU - 1 tridy Fronta]
[prveky fronty M_PRODUCENTU - 1]
*/
volatile sig_atomic_t pokracovat_ve_vypoctu;
static void connect_and_init_local_ptrs() {
/** Pripoji pament a inicializuje lokalni ukazatele na sdilenou pamet. */
shared = (Shared *) shmat(shared_mem_segment_id, NULL, NULL);
fronty = new p_Fronta[M_PRODUCENTU];
unsigned char *tmp_ptr = (unsigned char *) shared;
tmp_ptr += sizeof(Shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
fronty[i] = (Fronta *) tmp_ptr;
tmp_ptr += Fronta::get_total_sizeof();
}
}
static int get_total_sizeof() {
int velikost_vesech_front = Fronta::get_total_sizeof() * M_PRODUCENTU;
return sizeof(Shared) + velikost_vesech_front;
}
};
void Fronta::push(Prvek &prvek) {
if (this->_size >= K_POLOZEK) {
shared->pokracovat_ve_vypoctu = 0;
throw 2;
}
memcpy(this->next_back(), &prvek, sizeof(Prvek));
this->_size++;
};
Prvek* Fronta::front() {
if (this->_size <= 0) {
shared->pokracovat_ve_vypoctu = 0;
throw 1;
}
int i = _index_of_first % K_POLOZEK;
return &this->_get_array_of_prvky()[i];
}
void Fronta::pop() {
if (this->_size <= 0) {
shared->pokracovat_ve_vypoctu = 0;
throw 3;
}
this->_size--;
this->_index_of_first = (this->_index_of_first + 1) % K_POLOZEK;
}
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
void alloc_shared_mem() {
int shared_segment_size = Shared::get_total_sizeof();
printf("%s alokuje pamet velikosti %dB.\n", process_name, shared_segment_size);
shared_mem_segment_id = shmget(IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
}
void dealloc_shared_mem() {
shmctl(shared_mem_segment_id, IPC_RMID, NULL);
}
void wait_for_all_children() {
int status;
for (int i = 0; i < NUM_CHILDREN; i++) {
wait(&status);
}
}
void singnal_handler(int signal_number) {
printf("%s prijal signal %d\n", process_name, signal_number);
shared->pokracovat_ve_vypoctu = 0;
}
void init_sinals() {
signal(SIGQUIT, singnal_handler);
signal(SIGINT, singnal_handler);
signal(SIGHUP, singnal_handler);
signal(SIGTERM, singnal_handler);
}
int semaphore_allocation(int semnum) {
int sem_flags = IPC_CREAT | IPC_EXCL | SEM_R | SEM_A | SEM_R>>3 | SEM_A>>3 | SEM_R>>6 | SEM_A>>6;
int ret_val = semget(IPC_PRIVATE, semnum, sem_flags);
if (ret_val < 0) {
printf("Nepodarilo se inicializovat semafor.\n");
exit(1);
}
return ret_val;
}
void semaphore_initialize(int semid, int semnum, int init_value) {
semun argument;
for (int i = 0; i < semnum; i++) {
argument.val = init_value;
semctl(semid, i, SETVAL, argument);
}
}
int semaphore_deallocate(int semid, int semnum) {
semun ignored_argument;
return semctl(semid, semnum, IPC_RMID, ignored_argument);
}
int semaphore_down(int semid, int sem_index) {
/* Wait on a binary semaphore. Block until the semaphore
value is positive, then decrement it by one. */
sembuf operations[1];
operations[0].sem_num = sem_index;
operations[0].sem_op = -1;
operations[0].sem_flg = SEM_UNDO;
return semop(semid, operations, 1);
}
int semaphore_up(int semid, int sem_index) {
/* Post to a semaphore: increment its value by one. This returns immediately. */
sembuf operations[1];
operations[0].sem_num = sem_index;
operations[0].sem_op = 1;
operations[0].sem_flg = SEM_UNDO;
return semop(semid, operations, 1);
}
int semaphore_get(int semafor, int sem_index){
return semctl(semafor, sem_index, GETVAL, 0);
}
void dealloc_shared_resources() {
dealloc_shared_mem();
semaphore_deallocate(sem_mohu_vlozit, M_PRODUCENTU);
semaphore_deallocate(sem_pristup_ke_fronte, M_PRODUCENTU);
printf("%s dealokoval sdilene prostredky.\n", process_name);
}
void child_init() {
init_sinals();
Shared::connect_and_init_local_ptrs();
}
void root_init() {
child_pids = new pid_t[NUM_CHILDREN];
alloc_shared_mem();
init_sinals();
Shared::connect_and_init_local_ptrs();
shared->pokracovat_ve_vypoctu = 1;
sem_mohu_vlozit = semaphore_allocation(M_PRODUCENTU);
semaphore_initialize(sem_mohu_vlozit, M_PRODUCENTU, K_POLOZEK);
sem_pristup_ke_fronte = semaphore_allocation(M_PRODUCENTU);
semaphore_initialize(sem_pristup_ke_fronte, M_PRODUCENTU, 1);
for (int i = 0; i < M_PRODUCENTU; i++) {
printf("Semafory nastaveny na: sem_mohu_vlozit(%d), sem_pristup_ke_fronte(%d)\n",
semaphore_get(sem_mohu_vlozit, i),
semaphore_get(sem_pristup_ke_fronte, i));
}
}
void root_finish() {
wait_for_all_children();
dealloc_shared_resources();
delete[] child_pids;
}
void zamkni_frontu(int cislo_fronty) {
semaphore_down(sem_pristup_ke_fronte, cislo_fronty);
}
void odemkni_frontu(int cislo_fronty) {
semaphore_up(sem_pristup_ke_fronte, cislo_fronty);
}
void pockej_na_moznost_vkladat_prvek(int cislo_fronty) {
semaphore_down(sem_mohu_vlozit, cislo_fronty);
}
void umozni_vlozeni_prvku(int cislo_fronty) {
semaphore_up(sem_mohu_vlozit, cislo_fronty);
}
/**
* void producent(int cislo_producenta)
*
* pseudokod:
*
def producent():
for poradove_cislo in range(LIMIT_PRVKU):
pockej_na_moznost_vkladat_prvek()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
*/
void producent(int cislo_producenta) {
snprintf(process_name, MAX_NAME_SIZE, "PRODUCENT %d [PID:%d]", cislo_producenta, (int) getpid());
printf("%s zacatek.\n", process_name);
child_init();
Prvek prvek;
int velikos_fronty;
for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
if (shared->pokracovat_ve_vypoctu) {
prvek.init(cislo_producenta, poradove_cislo);
zamkni_frontu(cislo_producenta);
velikos_fronty = fronty[cislo_producenta]->size();
if (velikos_fronty >= K_POLOZEK) {
odemkni_frontu(cislo_producenta);
printf("%s ceka na uvolneni fronty.\n", process_name);
pockej_na_moznost_vkladat_prvek(cislo_producenta);
printf("%s muze vlozit do fronty.\n", process_name);
zamkni_frontu(cislo_producenta);
} else {
pockej_na_moznost_vkladat_prvek(cislo_producenta);
}
// pridej_prvek_do_fronty()
fronty[cislo_producenta]->push(prvek);
velikos_fronty = fronty[cislo_producenta]->size();
odemkni_frontu(cislo_producenta);
printf("%s pridal prvek %i - velikos fronty %i\n",
process_name, poradove_cislo, velikos_fronty);
pockej_nahodnou_dobu();
} else {
break;
}
}
printf("%s done.\n", process_name);
}
/**
* void konzument(int cislo_konzumenta)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
void konzument(int cislo_konzumenta) {
snprintf(process_name, MAX_NAME_SIZE, "Konzument %d [PID:%d]", cislo_konzumenta, (int) getpid());
printf("%s zacatek.\n", process_name);
child_init();
int *poradova_cisla_poslednich_prectenych_prveku = new int[M_PRODUCENTU];
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
}
Prvek *p_prvek;
int prectene_poradove_cislo;
int pocet_precteni;
int velikos_fronty;
int prectene_cislo_producenta;
int nova_velikos_fronty;
bool nove_nacteny = false;
bool prvek_odstranen = false;
bool ukonci_cteni = false;
while (shared->pokracovat_ve_vypoctu && ! ukonci_cteni) {
pockej_nahodnou_dobu();
ukonci_cteni = true;
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
zamkni_frontu(cislo_producenta);
velikos_fronty = fronty[cislo_producenta]->size();
if (velikos_fronty > 0) {
p_prvek = fronty[cislo_producenta]->front();
prectene_poradove_cislo = p_prvek->poradove_cislo;
prectene_cislo_producenta = p_prvek->cislo_producenta;
if (prectene_poradove_cislo
!= poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
nove_nacteny = true;
pocet_precteni = ++(p_prvek->pocet_precteni);
if (pocet_precteni >= N_KONZUMENTU) {
fronty[cislo_producenta]->pop();
nova_velikos_fronty = fronty[cislo_producenta]->size();
umozni_vlozeni_prvku(prectene_cislo_producenta);
prvek_odstranen = true;
}
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
= prectene_poradove_cislo;
}
}
odemkni_frontu(cislo_producenta);
/*
if (!nove_nacteny && !prvek_odstranen) {
printf("%s cte z fronty %i prvek %i - pocet precteni %i - POSLEDNI PRECTENY %d - NEDELE NIC - N_KONZUMENTU: %d.\n",
process_name,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni,
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta],
N_KONZUMENTU);
for (int i = 0; i < M_PRODUCENTU; i++) {
printf("Semafory nastaveny na: sem_mohu_vlozit(%d), sem_pristup_ke_fronte(%d)\n",
semaphore_get(sem_mohu_vlozit, i),
semaphore_get(sem_pristup_ke_fronte, i));
}
}
*/
if (nove_nacteny) {
printf("%s cte z fronty %i prvek %i - pocet precteni %i\n",
process_name,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni);
nove_nacteny = false;
}
if (prvek_odstranen) {
printf("%s odsranil z fronty %i prvek %i - velikost fronty %i\n",
process_name,
cislo_producenta,
prectene_poradove_cislo,
nova_velikos_fronty);
prvek_odstranen = false;
}
if (ukonci_cteni) {
ukonci_cteni =
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
}
}
}
printf("%s done.\n", process_name);
}
int main(int argc, char * const argv[]) {
if (argc != 1) {
sscanf(argv[1], "%d", &M_PRODUCENTU);
sscanf(argv[2], "%d", &N_KONZUMENTU);
sscanf(argv[3], "%d", &K_POLOZEK);
sscanf(argv[4], "%d", &LIMIT_PRVKU);
NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
} else {
printf("Usage:\n\t %s M_PRODUCENTU N_KONZUMENTU K_POLOZEK LIMIT_PRVKU\n\n", argv[0]);
+ exit(1);
}
pid_t root_pid = getpid();
bool exception = false;
try {
pid_t child_pid;
snprintf(process_name, MAX_NAME_SIZE, "Hlavni proces [PID:%d]", (int) getpid());
printf ("%s.\n", process_name, (int) root_pid);
root_init();
printf("Velikos Shared: %d, velikost Fronta: %d, velikost Prvek: %d.\n",
Shared::get_total_sizeof(), Fronta::get_total_sizeof(), sizeof(Prvek));
printf("Shared addr: %p (%d).\n", shared, (unsigned int) shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
printf("Fronta %d addr: %p (relativni: %d).\n",
i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
fronty[i]->init();
child_pid = fork();
if (child_pid != 0) {
child_pids[i] = child_pid;
} else {
producent(i);
exit(0);
}
}
for (int i = 0; i < N_KONZUMENTU; i++) {
child_pid = fork ();
if (child_pid != 0) {
child_pids[i + M_PRODUCENTU] = child_pid;
} else {
konzument(i);
exit(0);
}
}
} catch(...) {
exception = true;
}
if (getpid() == root_pid) {
atexit(root_finish);
}
if ( ! exception) {
printf("All OK. Done.\n");
return 0;
} else {
printf("--------------------------------- %s exception caught in main(). Done.\n", process_name);
return 1;
}
}
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
f2718df14c5ebf18775dd0b6da1d6361634e706b
|
Pridan PDF soubro s popisem.
|
diff --git a/Semestralni uloha X36OSY 2007.pdf b/Semestralni uloha X36OSY 2007.pdf
new file mode 100644
index 0000000..58e1e97
Binary files /dev/null and b/Semestralni uloha X36OSY 2007.pdf differ
diff --git a/readme.html b/readme.html
index bcf30fa..0e40e2a 100644
--- a/readme.html
+++ b/readme.html
@@ -1,117 +1,116 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Semestrálnà úloha X36OSY 2007</title>
</head>
<body>
<center><h1>Semestrálnà úloha X36OSY 2007</h1></center>
<center>Téma úlohy: Producenti a konzumenti</center>
<center>Vypracoval: Tomas Horacek <horact1@fel.cvut.cz></center>
<br />
<center>6. roÄnÃk, obor VýpoÄetnà technika, K336 FEL ÄVUT,<br />
Karlovo nám. 13, 121 35 Praha 2 </center>
<h2>Zadánà úlohy</h2>
<p>
MÄjme <i>m</i> producentů a <i>n</i> konzumentů.
Každý producent má svojà frontu o kapacitÄ <i>k</i> položek,
do které v náhodných intervalech zapisuje pokud je v nà volno, jinak se zablokuje a Äeká.
Položky ve frontách obsahujà ÄÃslo producenta a poÅadové ÄÃslo, ve kterém byly zapsány do fronty.
Konzumenti v náhodných intervalech Ätou položky z front. Každý konzument musà pÅeÄÃst vÅ¡echny
položky od všech producentů, tzn. že položky se mohou odstranit z front až
po pÅeÄtenà vÅ¡emi konzumenty.
</p>
<p><b>Vstup:</b> Producenti a konzumenti jsou reprezentováni vlákny/procesy a náhodnÄ generujÃ/Ätou položky.</p>
<p><b>Výstup:</b> Informace o tom, jak se mÄnà obsah jednotlivých front a informace v jakém stavu se producenti a konzument nacházejÃ.</p>
<h2>Analýza úlohy</h2>
<h2>ÅeÅ¡enà úlohy pomocà vláken</h2>
<p>Reseni je za pomoci mutexu, pseoudokod popisujici algoritmus je zde:</p>
<code><pre>
def my_producent():
for cislo_prvku in range(LIMIT_PRVKU):
while je_fronta_plna():
pockej_na_uvolneni_prvku()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
</pre></code>
<code><pre>
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
</pre></code>
<h2>ÅeÅ¡enà úlohy pomocà procesů</h2>
<p>
ÅeÅ¡enà je implementována jako <em>N</em> + <em>M</em> + 1 procesů. Prvni proces vytvory producenty
a konzumenty a ceka na jejich ukonceni. Fronty producentů (sdÃlená data) jsou uloženy v jednom segmentu
sdÃlené pamÄti a jsou pÅÃstupné po volánà <code>child_init()</code> pÅes ukazatel na pole
<code>fronty</code>. PÅÃstup ke frontám je ÅÃzen dvÄma sadami semaforu (každá sada má velikost <em>M</em>),
prvnà sada urcuje, zda se da s frontou manipulovat, druhá, zda se dá do fronty pÅidávat.
SdÃlené prostredky alokoje a dealokuje prvnà proces.
</p>
<p>
Signály SIGQUIT, SIGINT, SIGHUP a SIGTERM jsou odchyceny a dealokace sdÃlených prostredků probÃhá
správnÄ i pÅi jejich vyvolánÃ.
-
</p>
<h2>ZávÄr</h2>
Uloha mi pomohla prakticky vyzkouset tvoreni vlaken, jejich synchronizaci pomoci vlaken
a take vytvareni procesu, sdilene pameti a obsluhu semaforu.
<h2>Literatura</h2>
<ol>
<li>Slides ze cviceni</li>
<li>Priklady ze cviceni</li>
<li>manualove stranky</li>
<li><a href="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_21.html" title="The GNU C Library - Signal Handling">The GNU C Library - Signal Handling</a></li>
<li><a href="http://www.cplusplus.com/reference/stl/queue/queue.html" title="queue::queue - C++ Reference">queue::queue - C++ Reference</a></li>
</ol>
</body>
</html>
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
1affa322391db483c99c80c040d0800ff9149fd5
|
Pridano nacitani prarametru.
|
diff --git a/Makefile b/Makefile
index 512e1cd..4a3ce76 100644
--- a/Makefile
+++ b/Makefile
@@ -1,19 +1,19 @@
# all after symbol '#' is comment
# === which communication library to use ===
CC = g++
CFLAGS =
LIBS = -lpthread
# -lrt
default: main
main:main.cpp
$(CC) $(CFLAGS) -o main main.cpp $(LIBS)
run:main
- ./main
+ ./main 5 3 4 10
clear:
\rm main
diff --git a/main.cpp b/main.cpp
index ecba850..db8802f 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,581 +1,605 @@
/**
* X36OSY - Producenti a konzumenti
*
* vypracoval: Tomas Horacek <horact1@fel.cvut.cz>
*
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
#include <signal.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
struct Prvek;
struct Fronta;
struct Shared;
-const int M_PRODUCENTU = 10;
-const int N_KONZUMENTU = 3;
-const int K_POLOZEK = 4;
-const int LIMIT_PRVKU = 10;
+int M_PRODUCENTU = 9;
+int N_KONZUMENTU = 3;
+int K_POLOZEK = 4;
+int LIMIT_PRVKU = 50;
+int NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
+int MAX_NAHODNA_DOBA = 5000000;
const int MAX_NAME_SIZE = 30;
-const int NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
-const int MAX_NAHODNA_DOBA = 5000000;
pid_t *child_pids;
int shared_mem_segment_id;
-Shared *shared;
Fronta **fronty;
char process_name[MAX_NAME_SIZE];
int sem_pristup_ke_fronte;
int sem_mohu_vlozit;
+Shared *shared;
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
Prvek() :
cislo_producenta(0),
poradove_cislo(0),
pocet_precteni(0) { }
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
void init(int _cislo_producenta, int _poradove_cislo) {
this->cislo_producenta = _cislo_producenta;
this->poradove_cislo = _poradove_cislo;
this->pocet_precteni = 0;
}
};
class Fronta {
/**
* Pametove rozlozeni fronty:
Fronta:
Instance tridy Fronta:
[_size]
[_index_of_first]
Prvky fronty: (nasleduji okamzite za instanci Fronta)
[instance 0 (tridy Prvek) fronty]
[instance 1 (tridy Prvek) fronty]
...
[instance K_POLOZEK - 1 (tridy Prvek) fronty] (fixni pocet prvku)
*/
unsigned int _size;
unsigned int _index_of_first;
Prvek *_get_array_of_prvky() {
unsigned char *tmp_ptr = (unsigned char *) this;
tmp_ptr += sizeof(Fronta);
return (Prvek *) tmp_ptr;
}
Prvek* next_back() {
int i = (this->_index_of_first + this->_size) % K_POLOZEK;
return &(this->_get_array_of_prvky()[i]);
}
public:
void init() {
this->_size = 0;
this->_index_of_first = 0;
}
int size() {
return this->_size;
}
- Prvek* front() {
- int i = _index_of_first % K_POLOZEK;
- return &this->_get_array_of_prvky()[i];
- }
-
+ Prvek* front();
void push(Prvek &prvek);
-
- void pop() {
- this->_size--;
- this->_index_of_first = (this->_index_of_first + 1) % K_POLOZEK;
- }
+ void pop();
static int get_total_sizeof() {
return sizeof(Fronta) + sizeof(Prvek) * K_POLOZEK;
}
};
typedef Fronta *p_Fronta;
struct Shared {
/**
*
* Struktura sdilene pameti:
Shared:
[pokracovat_ve_vypoctu]
Fronta 0:
[instance 0 tridy Fronta]
[prveky fronty 0]
Fronta 1:
[instance 1 tridy Fronta]
[prveky fronty 1]
...
Fronta M_PRODUCENTU - 1:
[instance M_PRODUCENTU - 1 tridy Fronta]
[prveky fronty M_PRODUCENTU - 1]
*/
volatile sig_atomic_t pokracovat_ve_vypoctu;
static void connect_and_init_local_ptrs() {
/** Pripoji pament a inicializuje lokalni ukazatele na sdilenou pamet. */
shared = (Shared *) shmat(shared_mem_segment_id, NULL, NULL);
fronty = new p_Fronta[M_PRODUCENTU];
unsigned char *tmp_ptr = (unsigned char *) shared;
tmp_ptr += sizeof(Shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
fronty[i] = (Fronta *) tmp_ptr;
tmp_ptr += Fronta::get_total_sizeof();
}
}
static int get_total_sizeof() {
int velikost_vesech_front = Fronta::get_total_sizeof() * M_PRODUCENTU;
return sizeof(Shared) + velikost_vesech_front;
}
};
void Fronta::push(Prvek &prvek) {
if (this->_size >= K_POLOZEK) {
shared->pokracovat_ve_vypoctu = 0;
- throw 1;
+ throw 2;
}
memcpy(this->next_back(), &prvek, sizeof(Prvek));
this->_size++;
};
+Prvek* Fronta::front() {
+ if (this->_size <= 0) {
+ shared->pokracovat_ve_vypoctu = 0;
+ throw 1;
+ }
+ int i = _index_of_first % K_POLOZEK;
+ return &this->_get_array_of_prvky()[i];
+}
+
+void Fronta::pop() {
+ if (this->_size <= 0) {
+ shared->pokracovat_ve_vypoctu = 0;
+ throw 3;
+ }
+ this->_size--;
+ this->_index_of_first = (this->_index_of_first + 1) % K_POLOZEK;
+}
+
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
void alloc_shared_mem() {
int shared_segment_size = Shared::get_total_sizeof();
printf("%s alokuje pamet velikosti %dB.\n", process_name, shared_segment_size);
shared_mem_segment_id = shmget(IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
}
void dealloc_shared_mem() {
shmctl(shared_mem_segment_id, IPC_RMID, NULL);
}
void wait_for_all_children() {
int status;
for (int i = 0; i < NUM_CHILDREN; i++) {
wait(&status);
}
}
void singnal_handler(int signal_number) {
printf("%s prijal signal %d\n", process_name, signal_number);
shared->pokracovat_ve_vypoctu = 0;
}
void init_sinals() {
signal(SIGQUIT, singnal_handler);
signal(SIGINT, singnal_handler);
signal(SIGHUP, singnal_handler);
signal(SIGTERM, singnal_handler);
}
int semaphore_allocation(int semnum) {
int sem_flags = IPC_CREAT | IPC_EXCL | SEM_R | SEM_A | SEM_R>>3 | SEM_A>>3 | SEM_R>>6 | SEM_A>>6;
int ret_val = semget(IPC_PRIVATE, semnum, sem_flags);
if (ret_val < 0) {
printf("Nepodarilo se inicializovat semafor.\n");
exit(1);
}
return ret_val;
}
void semaphore_initialize(int semid, int semnum, int init_value) {
semun argument;
for (int i = 0; i < semnum; i++) {
argument.val = init_value;
semctl(semid, i, SETVAL, argument);
}
}
int semaphore_deallocate(int semid, int semnum) {
semun ignored_argument;
return semctl(semid, semnum, IPC_RMID, ignored_argument);
}
int semaphore_down(int semid, int sem_index) {
/* Wait on a binary semaphore. Block until the semaphore
value is positive, then decrement it by one. */
sembuf operations[1];
operations[0].sem_num = sem_index;
operations[0].sem_op = -1;
operations[0].sem_flg = SEM_UNDO;
return semop(semid, operations, 1);
}
int semaphore_up(int semid, int sem_index) {
/* Post to a semaphore: increment its value by one. This returns immediately. */
sembuf operations[1];
operations[0].sem_num = sem_index;
operations[0].sem_op = 1;
- operations[0].sem_flg= SEM_UNDO;
+ operations[0].sem_flg = SEM_UNDO;
return semop(semid, operations, 1);
}
int semaphore_get(int semafor, int sem_index){
return semctl(semafor, sem_index, GETVAL, 0);
}
void dealloc_shared_resources() {
dealloc_shared_mem();
semaphore_deallocate(sem_mohu_vlozit, M_PRODUCENTU);
semaphore_deallocate(sem_pristup_ke_fronte, M_PRODUCENTU);
printf("%s dealokoval sdilene prostredky.\n", process_name);
}
void child_init() {
init_sinals();
Shared::connect_and_init_local_ptrs();
}
void root_init() {
child_pids = new pid_t[NUM_CHILDREN];
alloc_shared_mem();
init_sinals();
Shared::connect_and_init_local_ptrs();
shared->pokracovat_ve_vypoctu = 1;
sem_mohu_vlozit = semaphore_allocation(M_PRODUCENTU);
semaphore_initialize(sem_mohu_vlozit, M_PRODUCENTU, K_POLOZEK);
sem_pristup_ke_fronte = semaphore_allocation(M_PRODUCENTU);
semaphore_initialize(sem_pristup_ke_fronte, M_PRODUCENTU, 1);
for (int i = 0; i < M_PRODUCENTU; i++) {
printf("Semafory nastaveny na: sem_mohu_vlozit(%d), sem_pristup_ke_fronte(%d)\n",
semaphore_get(sem_mohu_vlozit, i),
semaphore_get(sem_pristup_ke_fronte, i));
}
}
void root_finish() {
wait_for_all_children();
dealloc_shared_resources();
delete[] child_pids;
}
void zamkni_frontu(int cislo_fronty) {
semaphore_down(sem_pristup_ke_fronte, cislo_fronty);
}
void odemkni_frontu(int cislo_fronty) {
semaphore_up(sem_pristup_ke_fronte, cislo_fronty);
}
void pockej_na_moznost_vkladat_prvek(int cislo_fronty) {
semaphore_down(sem_mohu_vlozit, cislo_fronty);
}
void umozni_vlozeni_prvku(int cislo_fronty) {
semaphore_up(sem_mohu_vlozit, cislo_fronty);
}
/**
* void producent(int cislo_producenta)
*
* pseudokod:
*
def producent():
for poradove_cislo in range(LIMIT_PRVKU):
pockej_na_moznost_vkladat_prvek()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
*/
void producent(int cislo_producenta) {
snprintf(process_name, MAX_NAME_SIZE, "PRODUCENT %d [PID:%d]", cislo_producenta, (int) getpid());
printf("%s zacatek.\n", process_name);
child_init();
Prvek prvek;
int velikos_fronty;
for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
if (shared->pokracovat_ve_vypoctu) {
prvek.init(cislo_producenta, poradove_cislo);
zamkni_frontu(cislo_producenta);
velikos_fronty = fronty[cislo_producenta]->size();
if (velikos_fronty >= K_POLOZEK) {
odemkni_frontu(cislo_producenta);
printf("%s ceka na uvolneni fronty.\n", process_name);
pockej_na_moznost_vkladat_prvek(cislo_producenta);
printf("%s muze vlozit do fronty.\n", process_name);
zamkni_frontu(cislo_producenta);
} else {
pockej_na_moznost_vkladat_prvek(cislo_producenta);
}
// pridej_prvek_do_fronty()
fronty[cislo_producenta]->push(prvek);
velikos_fronty = fronty[cislo_producenta]->size();
odemkni_frontu(cislo_producenta);
printf("%s pridal prvek %i - velikos fronty %i\n",
- process_name, poradove_cislo, velikos_fronty);
+ process_name, poradove_cislo, velikos_fronty);
pockej_nahodnou_dobu();
} else {
break;
}
}
printf("%s done.\n", process_name);
}
/**
* void konzument(int cislo_konzumenta)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
void konzument(int cislo_konzumenta) {
snprintf(process_name, MAX_NAME_SIZE, "Konzument %d [PID:%d]", cislo_konzumenta, (int) getpid());
printf("%s zacatek.\n", process_name);
child_init();
int *poradova_cisla_poslednich_prectenych_prveku = new int[M_PRODUCENTU];
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
}
Prvek *p_prvek;
int prectene_poradove_cislo;
int pocet_precteni;
int velikos_fronty;
int prectene_cislo_producenta;
int nova_velikos_fronty;
bool nove_nacteny = false;
bool prvek_odstranen = false;
bool ukonci_cteni = false;
while (shared->pokracovat_ve_vypoctu && ! ukonci_cteni) {
pockej_nahodnou_dobu();
ukonci_cteni = true;
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
zamkni_frontu(cislo_producenta);
velikos_fronty = fronty[cislo_producenta]->size();
if (velikos_fronty > 0) {
p_prvek = fronty[cislo_producenta]->front();
prectene_poradove_cislo = p_prvek->poradove_cislo;
prectene_cislo_producenta = p_prvek->cislo_producenta;
if (prectene_poradove_cislo
!= poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
nove_nacteny = true;
pocet_precteni = ++(p_prvek->pocet_precteni);
if (pocet_precteni >= N_KONZUMENTU) {
fronty[cislo_producenta]->pop();
nova_velikos_fronty = fronty[cislo_producenta]->size();
- umozni_vlozeni_prvku(cislo_producenta);
+ umozni_vlozeni_prvku(prectene_cislo_producenta);
prvek_odstranen = true;
- // nova_velikos_fronty = xfronty[cislo_producenta].size();
- //
- // if (nova_velikos_fronty == (K_POLOZEK - 1)) {
- // pthread_cond_signal(&condy_front[cislo_producenta]);
- // printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
- // cislo_konzumenta,
- // cislo_producenta,
- // velikos_fronty);
- // }
}
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
= prectene_poradove_cislo;
}
}
odemkni_frontu(cislo_producenta);
+ /*
+ if (!nove_nacteny && !prvek_odstranen) {
+ printf("%s cte z fronty %i prvek %i - pocet precteni %i - POSLEDNI PRECTENY %d - NEDELE NIC - N_KONZUMENTU: %d.\n",
+ process_name,
+ cislo_producenta,
+ prectene_poradove_cislo,
+ pocet_precteni,
+ poradova_cisla_poslednich_prectenych_prveku[cislo_producenta],
+ N_KONZUMENTU);
+
+ for (int i = 0; i < M_PRODUCENTU; i++) {
+ printf("Semafory nastaveny na: sem_mohu_vlozit(%d), sem_pristup_ke_fronte(%d)\n",
+ semaphore_get(sem_mohu_vlozit, i),
+ semaphore_get(sem_pristup_ke_fronte, i));
+ }
+ }
+ */
if (nove_nacteny) {
printf("%s cte z fronty %i prvek %i - pocet precteni %i\n",
process_name,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni);
nove_nacteny = false;
}
if (prvek_odstranen) {
printf("%s odsranil z fronty %i prvek %i - velikost fronty %i\n",
process_name,
cislo_producenta,
prectene_poradove_cislo,
nova_velikos_fronty);
prvek_odstranen = false;
}
if (ukonci_cteni) {
ukonci_cteni =
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
}
}
}
printf("%s done.\n", process_name);
}
int main(int argc, char * const argv[]) {
- // Fronta *f = malloc(Fronta::get_total_sizeof());
- // Prvke p;
- // p.poradove_cislo
+ if (argc != 1) {
+ sscanf(argv[1], "%d", &M_PRODUCENTU);
+ sscanf(argv[2], "%d", &N_KONZUMENTU);
+ sscanf(argv[3], "%d", &K_POLOZEK);
+ sscanf(argv[4], "%d", &LIMIT_PRVKU);
+ NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
+ } else {
+ printf("Usage:\n\t %s M_PRODUCENTU N_KONZUMENTU K_POLOZEK LIMIT_PRVKU\n\n", argv[0]);
+ }
pid_t root_pid = getpid();
bool exception = false;
try {
pid_t child_pid;
snprintf(process_name, MAX_NAME_SIZE, "Hlavni proces [PID:%d]", (int) getpid());
printf ("%s.\n", process_name, (int) root_pid);
root_init();
printf("Velikos Shared: %d, velikost Fronta: %d, velikost Prvek: %d.\n",
Shared::get_total_sizeof(), Fronta::get_total_sizeof(), sizeof(Prvek));
printf("Shared addr: %p (%d).\n", shared, (unsigned int) shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
printf("Fronta %d addr: %p (relativni: %d).\n",
i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
fronty[i]->init();
child_pid = fork();
if (child_pid != 0) {
child_pids[i] = child_pid;
} else {
producent(i);
exit(0);
}
}
for (int i = 0; i < N_KONZUMENTU; i++) {
child_pid = fork ();
if (child_pid != 0) {
child_pids[i + M_PRODUCENTU] = child_pid;
} else {
konzument(i);
exit(0);
}
}
} catch(...) {
exception = true;
}
if (getpid() == root_pid) {
- root_finish();
+ atexit(root_finish);
}
if ( ! exception) {
printf("All OK. Done.\n");
return 0;
} else {
- printf("%s exception caught in main(). Done.\n", process_name);
+ printf("--------------------------------- %s exception caught in main(). Done.\n", process_name);
return 1;
}
}
\ No newline at end of file
diff --git a/readme.html b/readme.html
index 0186735..bcf30fa 100644
--- a/readme.html
+++ b/readme.html
@@ -1,98 +1,117 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Semestrálnà úloha X36OSY 2007</title>
</head>
<body>
<center><h1>Semestrálnà úloha X36OSY 2007</h1></center>
<center>Téma úlohy: Producenti a konzumenti</center>
<center>Vypracoval: Tomas Horacek <horact1@fel.cvut.cz></center>
<br />
<center>6. roÄnÃk, obor VýpoÄetnà technika, K336 FEL ÄVUT,<br />
Karlovo nám. 13, 121 35 Praha 2 </center>
<h2>Zadánà úlohy</h2>
<p>
MÄjme <i>m</i> producentů a <i>n</i> konzumentů.
Každý producent má svojà frontu o kapacitÄ <i>k</i> položek,
do které v náhodných intervalech zapisuje pokud je v nà volno, jinak se zablokuje a Äeká.
Položky ve frontách obsahujà ÄÃslo producenta a poÅadové ÄÃslo, ve kterém byly zapsány do fronty.
Konzumenti v náhodných intervalech Ätou položky z front. Každý konzument musà pÅeÄÃst vÅ¡echny
položky od všech producentů, tzn. že položky se mohou odstranit z front až
po pÅeÄtenà vÅ¡emi konzumenty.
</p>
<p><b>Vstup:</b> Producenti a konzumenti jsou reprezentováni vlákny/procesy a náhodnÄ generujÃ/Ätou položky.</p>
<p><b>Výstup:</b> Informace o tom, jak se mÄnà obsah jednotlivých front a informace v jakém stavu se producenti a konzument nacházejÃ.</p>
<h2>Analýza úlohy</h2>
<h2>ÅeÅ¡enà úlohy pomocà vláken</h2>
<p>Reseni je za pomoci mutexu, pseoudokod popisujici algoritmus je zde:</p>
<code><pre>
def my_producent():
for cislo_prvku in range(LIMIT_PRVKU):
while je_fronta_plna():
pockej_na_uvolneni_prvku()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
</pre></code>
<code><pre>
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
</pre></code>
<h2>ÅeÅ¡enà úlohy pomocà procesů</h2>
-
+
+
+
+ <p>
+ ÅeÅ¡enà je implementována jako <em>N</em> + <em>M</em> + 1 procesů. Prvni proces vytvory producenty
+ a konzumenty a ceka na jejich ukonceni. Fronty producentů (sdÃlená data) jsou uloženy v jednom segmentu
+ sdÃlené pamÄti a jsou pÅÃstupné po volánà <code>child_init()</code> pÅes ukazatel na pole
+ <code>fronty</code>. PÅÃstup ke frontám je ÅÃzen dvÄma sadami semaforu (každá sada má velikost <em>M</em>),
+ prvnà sada urcuje, zda se da s frontou manipulovat, druhá, zda se dá do fronty pÅidávat.
+ SdÃlené prostredky alokoje a dealokuje prvnà proces.
+ </p>
+
+ <p>
+ Signály SIGQUIT, SIGINT, SIGHUP a SIGTERM jsou odchyceny a dealokace sdÃlených prostredků probÃhá
+ správnÄ i pÅi jejich vyvolánÃ.
+
+ </p>
+
+
<h2>ZávÄr</h2>
- Uloha mi pomohla prakticky vyzkouset tvoreni vlaken a jejich synchronizaci.
+ Uloha mi pomohla prakticky vyzkouset tvoreni vlaken, jejich synchronizaci pomoci vlaken
+ a take vytvareni procesu, sdilene pameti a obsluhu semaforu.
<h2>Literatura</h2>
<ol>
<li>Slides ze cviceni</li>
<li>Priklady ze cviceni</li>
<li>manualove stranky</li>
<li><a href="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_21.html" title="The GNU C Library - Signal Handling">The GNU C Library - Signal Handling</a></li>
<li><a href="http://www.cplusplus.com/reference/stl/queue/queue.html" title="queue::queue - C++ Reference">queue::queue - C++ Reference</a></li>
</ol>
</body>
</html>
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
ef0d6385cadf960dbb3b37c6b7b571326735d8cf
|
Pridana prvni verze konzumenta a funkcni fronty.
|
diff --git a/main.cpp b/main.cpp
index 3e8f5c8..ecba850 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,636 +1,581 @@
/**
* X36OSY - Producenti a konzumenti
*
* vypracoval: Tomas Horacek <horact1@fel.cvut.cz>
*
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
#include <signal.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
struct Prvek;
struct Fronta;
struct Shared;
-const int M_PRODUCENTU = 5;
+const int M_PRODUCENTU = 10;
const int N_KONZUMENTU = 3;
-const int K_POLOZEK = 3;
+const int K_POLOZEK = 4;
const int LIMIT_PRVKU = 10;
const int MAX_NAME_SIZE = 30;
const int NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
-const int MAX_NAHODNA_DOBA = 50000;
+const int MAX_NAHODNA_DOBA = 5000000;
pid_t *child_pids;
int shared_mem_segment_id;
Shared *shared;
Fronta **fronty;
char process_name[MAX_NAME_SIZE];
int sem_pristup_ke_fronte;
int sem_mohu_vlozit;
-int sem_mohu_cist;
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
Prvek() :
cislo_producenta(0),
poradove_cislo(0),
pocet_precteni(0) { }
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
void init(int _cislo_producenta, int _poradove_cislo) {
this->cislo_producenta = _cislo_producenta;
this->poradove_cislo = _poradove_cislo;
this->pocet_precteni = 0;
}
};
class Fronta {
/**
* Pametove rozlozeni fronty:
Fronta:
Instance tridy Fronta:
[_size]
[_index_of_first]
Prvky fronty: (nasleduji okamzite za instanci Fronta)
[instance 0 (tridy Prvek) fronty]
[instance 1 (tridy Prvek) fronty]
...
[instance K_POLOZEK - 1 (tridy Prvek) fronty] (fixni pocet prvku)
*/
unsigned int _size;
unsigned int _index_of_first;
Prvek *_get_array_of_prvky() {
unsigned char *tmp_ptr = (unsigned char *) this;
tmp_ptr += sizeof(Fronta);
return (Prvek *) tmp_ptr;
}
+
+ Prvek* next_back() {
+ int i = (this->_index_of_first + this->_size) % K_POLOZEK;
+ return &(this->_get_array_of_prvky()[i]);
+ }
public:
void init() {
this->_size = 0;
this->_index_of_first = 0;
}
int size() {
return this->_size;
}
- int empty() {
- return this->_size == 0;
+ Prvek* front() {
+ int i = _index_of_first % K_POLOZEK;
+ return &this->_get_array_of_prvky()[i];
}
- void front() {
-
- }
+ void push(Prvek &prvek);
- void push(Prvek &prvek) {
- this->_size++;
- }
-
- Prvek &pop() {
-
+ void pop() {
+ this->_size--;
+ this->_index_of_first = (this->_index_of_first + 1) % K_POLOZEK;
}
static int get_total_sizeof() {
return sizeof(Fronta) + sizeof(Prvek) * K_POLOZEK;
}
};
typedef Fronta *p_Fronta;
struct Shared {
/**
*
* Struktura sdilene pameti:
Shared:
[pokracovat_ve_vypoctu]
Fronta 0:
[instance 0 tridy Fronta]
[prveky fronty 0]
Fronta 1:
[instance 1 tridy Fronta]
[prveky fronty 1]
...
Fronta M_PRODUCENTU - 1:
[instance M_PRODUCENTU - 1 tridy Fronta]
[prveky fronty M_PRODUCENTU - 1]
*/
volatile sig_atomic_t pokracovat_ve_vypoctu;
static void connect_and_init_local_ptrs() {
/** Pripoji pament a inicializuje lokalni ukazatele na sdilenou pamet. */
shared = (Shared *) shmat(shared_mem_segment_id, NULL, NULL);
fronty = new p_Fronta[M_PRODUCENTU];
unsigned char *tmp_ptr = (unsigned char *) shared;
tmp_ptr += sizeof(Shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
fronty[i] = (Fronta *) tmp_ptr;
tmp_ptr += Fronta::get_total_sizeof();
}
}
static int get_total_sizeof() {
int velikost_vesech_front = Fronta::get_total_sizeof() * M_PRODUCENTU;
return sizeof(Shared) + velikost_vesech_front;
}
};
-pthread_cond_t condy_front[M_PRODUCENTU];
-pthread_mutex_t mutexy_front[M_PRODUCENTU];
-queue<Prvek*> xfronty[M_PRODUCENTU];
+void Fronta::push(Prvek &prvek) {
+ if (this->_size >= K_POLOZEK) {
+ shared->pokracovat_ve_vypoctu = 0;
+ throw 1;
+ }
+ memcpy(this->next_back(), &prvek, sizeof(Prvek));
+ this->_size++;
+};
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
-/**
- * void *konzument(void *idp)
- *
- * pseudokod:
- *
-def konzument():
- while True:
- pockej_nahodnou_dobu()
-
- ukonci_cteni = True
- for producent in range(M_PRODUCENTU):
- zamkni_frontu()
- if not fornta_je_prazdna():
- prvek = fronta[producent].front()
-
- if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
- prvek.pocet_precteni++
-
- if prvek.pocet_precteni == N_KONZUMENTU:
- fronta[producent].pop()
- delete prvek;
- zavolej_uvolneni_prvku()
-
- poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
- odemkni_frontu()
-
- if ukonci_cteni:
- ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
-
- if ukonci_cteni:
- ukonci_vlakno()
- */
-void *xkonzument(void *idp) {
- int cislo_konzumenta = *((int *) idp) - M_PRODUCENTU;
- bool ukonci_cteni;
- int cislo_producenta;
- int prectene_poradove_cislo;
- int prectene_cislo_producenta;
- int velikos_fronty;
- Prvek *prvek;
- int poradova_cisla_poslednich_prectenych_prveku[M_PRODUCENTU];
- bool prvek_odstranen = false;
- int nova_velikos_fronty;
- bool nove_nacteny = false;
- int pocet_precteni;
-
- for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
- poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
- }
-
- while (1) {
- pockej_nahodnou_dobu();
-
- ukonci_cteni = true;
- for (cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
- pthread_mutex_lock(&mutexy_front[cislo_producenta]);
-
- if ( ! xfronty[cislo_producenta].empty()) {
- prvek = xfronty[cislo_producenta].front();
- velikos_fronty = xfronty[cislo_producenta].size();
-
- prectene_poradove_cislo = prvek->poradove_cislo;
- prectene_cislo_producenta = prvek->cislo_producenta;
-
- if (prectene_poradove_cislo
- != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
- nove_nacteny = true;
- pocet_precteni = ++(prvek->pocet_precteni);
-
- if (prvek->pocet_precteni == N_KONZUMENTU) {
- xfronty[cislo_producenta].pop();
- delete prvek;
-
- pthread_cond_signal(&condy_front[cislo_producenta]);
-
- prvek_odstranen = true;
- nova_velikos_fronty = xfronty[cislo_producenta].size();
- if (nova_velikos_fronty == (K_POLOZEK - 1)) {
- pthread_cond_signal(&condy_front[cislo_producenta]);
- printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
- cislo_konzumenta,
- cislo_producenta,
- velikos_fronty);
- }
- }
-
- poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
- = prectene_poradove_cislo;
- }
- }
-
- pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
-
- if (nove_nacteny) {
- printf("konzument %i cte z fronty %i prvek %i - pocet precteni %i\n",
- cislo_konzumenta,
- cislo_producenta,
- prectene_poradove_cislo,
- pocet_precteni);
- nove_nacteny = false;
- }
-
- if (prvek_odstranen) {
- printf("konzument %i odsranil z fronty %i prvek %i - velikost fronty %i\n",
- cislo_konzumenta,
- cislo_producenta,
- prectene_poradove_cislo,
- nova_velikos_fronty);
- prvek_odstranen = false;
- }
-
- if (ukonci_cteni) {
- ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
- == (LIMIT_PRVKU - 1);
- }
- }
-
- if (ukonci_cteni) {
- printf("konzument %i konec\n", cislo_konzumenta);
- pthread_exit(NULL);
- return NULL;
- }
- }
- pthread_exit(NULL);
-}
-
void alloc_shared_mem() {
int shared_segment_size = Shared::get_total_sizeof();
printf("%s alokuje pamet velikosti %dB.\n", process_name, shared_segment_size);
shared_mem_segment_id = shmget(IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
}
void dealloc_shared_mem() {
shmctl(shared_mem_segment_id, IPC_RMID, NULL);
}
void wait_for_all_children() {
int status;
for (int i = 0; i < NUM_CHILDREN; i++) {
wait(&status);
}
}
void singnal_handler(int signal_number) {
printf("%s prijal signal %d\n", process_name, signal_number);
shared->pokracovat_ve_vypoctu = 0;
}
void init_sinals() {
signal(SIGQUIT, singnal_handler);
signal(SIGINT, singnal_handler);
signal(SIGHUP, singnal_handler);
signal(SIGTERM, singnal_handler);
}
int semaphore_allocation(int semnum) {
int sem_flags = IPC_CREAT | IPC_EXCL | SEM_R | SEM_A | SEM_R>>3 | SEM_A>>3 | SEM_R>>6 | SEM_A>>6;
int ret_val = semget(IPC_PRIVATE, semnum, sem_flags);
if (ret_val < 0) {
printf("Nepodarilo se inicializovat semafor.\n");
exit(1);
}
return ret_val;
}
void semaphore_initialize(int semid, int semnum, int init_value) {
semun argument;
for (int i = 0; i < semnum; i++) {
argument.val = init_value;
semctl(semid, i, SETVAL, argument);
}
}
int semaphore_deallocate(int semid, int semnum) {
semun ignored_argument;
return semctl(semid, semnum, IPC_RMID, ignored_argument);
}
int semaphore_down(int semid, int sem_index) {
/* Wait on a binary semaphore. Block until the semaphore
value is positive, then decrement it by one. */
sembuf operations[1];
operations[0].sem_num = sem_index;
operations[0].sem_op = -1;
operations[0].sem_flg = SEM_UNDO;
return semop(semid, operations, 1);
}
int semaphore_up(int semid, int sem_index) {
/* Post to a semaphore: increment its value by one. This returns immediately. */
sembuf operations[1];
operations[0].sem_num = sem_index;
operations[0].sem_op = 1;
operations[0].sem_flg= SEM_UNDO;
return semop(semid, operations, 1);
}
int semaphore_get(int semafor, int sem_index){
return semctl(semafor, sem_index, GETVAL, 0);
}
void dealloc_shared_resources() {
dealloc_shared_mem();
semaphore_deallocate(sem_mohu_vlozit, M_PRODUCENTU);
- semaphore_deallocate(sem_mohu_cist, M_PRODUCENTU);
semaphore_deallocate(sem_pristup_ke_fronte, M_PRODUCENTU);
printf("%s dealokoval sdilene prostredky.\n", process_name);
}
void child_init() {
init_sinals();
Shared::connect_and_init_local_ptrs();
}
void root_init() {
child_pids = new pid_t[NUM_CHILDREN];
alloc_shared_mem();
init_sinals();
Shared::connect_and_init_local_ptrs();
shared->pokracovat_ve_vypoctu = 1;
sem_mohu_vlozit = semaphore_allocation(M_PRODUCENTU);
semaphore_initialize(sem_mohu_vlozit, M_PRODUCENTU, K_POLOZEK);
-
- sem_mohu_cist = semaphore_allocation(M_PRODUCENTU);
- semaphore_initialize(sem_mohu_cist, M_PRODUCENTU, 0);
-
+
sem_pristup_ke_fronte = semaphore_allocation(M_PRODUCENTU);
semaphore_initialize(sem_pristup_ke_fronte, M_PRODUCENTU, 1);
for (int i = 0; i < M_PRODUCENTU; i++) {
- printf("Semafory nastaveny na: sem_mohu_vlozit(%d), sem_mohu_cist(%d), sem_pristup_ke_fronte(%d)\n",
+ printf("Semafory nastaveny na: sem_mohu_vlozit(%d), sem_pristup_ke_fronte(%d)\n",
semaphore_get(sem_mohu_vlozit, i),
- semaphore_get(sem_mohu_cist, i),
semaphore_get(sem_pristup_ke_fronte, i));
}
}
void root_finish() {
wait_for_all_children();
dealloc_shared_resources();
delete[] child_pids;
}
void zamkni_frontu(int cislo_fronty) {
semaphore_down(sem_pristup_ke_fronte, cislo_fronty);
}
void odemkni_frontu(int cislo_fronty) {
semaphore_up(sem_pristup_ke_fronte, cislo_fronty);
}
void pockej_na_moznost_vkladat_prvek(int cislo_fronty) {
semaphore_down(sem_mohu_vlozit, cislo_fronty);
}
void umozni_vlozeni_prvku(int cislo_fronty) {
semaphore_up(sem_mohu_vlozit, cislo_fronty);
}
-void umozni_cteni_z_fronty(int cislo_fronty) {
- semaphore_up(sem_mohu_cist, cislo_fronty);
-}
-
-void pockej_na_moznost_cteni_z_fornty(int cislo_fronty) {
- semaphore_down(sem_mohu_cist, cislo_fronty);
-}
/**
* void producent(int cislo_producenta)
*
* pseudokod:
*
def producent():
for poradove_cislo in range(LIMIT_PRVKU):
pockej_na_moznost_vkladat_prvek()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
*/
void producent(int cislo_producenta) {
snprintf(process_name, MAX_NAME_SIZE, "PRODUCENT %d [PID:%d]", cislo_producenta, (int) getpid());
printf("%s zacatek.\n", process_name);
child_init();
Prvek prvek;
int velikos_fronty;
for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
if (shared->pokracovat_ve_vypoctu) {
prvek.init(cislo_producenta, poradove_cislo);
zamkni_frontu(cislo_producenta);
velikos_fronty = fronty[cislo_producenta]->size();
if (velikos_fronty >= K_POLOZEK) {
odemkni_frontu(cislo_producenta);
printf("%s ceka na uvolneni fronty.\n", process_name);
pockej_na_moznost_vkladat_prvek(cislo_producenta);
printf("%s muze vlozit do fronty.\n", process_name);
zamkni_frontu(cislo_producenta);
} else {
pockej_na_moznost_vkladat_prvek(cislo_producenta);
}
// pridej_prvek_do_fronty()
fronty[cislo_producenta]->push(prvek);
-
- umozni_cteni_z_fronty(cislo_producenta);
+ velikos_fronty = fronty[cislo_producenta]->size();
odemkni_frontu(cislo_producenta);
printf("%s pridal prvek %i - velikos fronty %i\n",
process_name, poradove_cislo, velikos_fronty);
pockej_nahodnou_dobu();
} else {
break;
}
}
printf("%s done.\n", process_name);
}
/**
* void konzument(int cislo_konzumenta)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
void konzument(int cislo_konzumenta) {
snprintf(process_name, MAX_NAME_SIZE, "Konzument %d [PID:%d]", cislo_konzumenta, (int) getpid());
printf("%s zacatek.\n", process_name);
child_init();
+ int *poradova_cisla_poslednich_prectenych_prveku = new int[M_PRODUCENTU];
- for (int i = 0; i < LIMIT_PRVKU; i++) {
- if (shared->pokracovat_ve_vypoctu) {
- sleep(1);
- } else {
- break;
- }
+ for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
+ poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
+ }
+
+ Prvek *p_prvek;
+ int prectene_poradove_cislo;
+ int pocet_precteni;
+ int velikos_fronty;
+ int prectene_cislo_producenta;
+ int nova_velikos_fronty;
+ bool nove_nacteny = false;
+ bool prvek_odstranen = false;
+
+ bool ukonci_cteni = false;
+ while (shared->pokracovat_ve_vypoctu && ! ukonci_cteni) {
+ pockej_nahodnou_dobu();
+
+ ukonci_cteni = true;
+ for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
+ zamkni_frontu(cislo_producenta);
+ velikos_fronty = fronty[cislo_producenta]->size();
+
+ if (velikos_fronty > 0) {
+ p_prvek = fronty[cislo_producenta]->front();
+
+ prectene_poradove_cislo = p_prvek->poradove_cislo;
+ prectene_cislo_producenta = p_prvek->cislo_producenta;
+
+ if (prectene_poradove_cislo
+ != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
+ nove_nacteny = true;
+ pocet_precteni = ++(p_prvek->pocet_precteni);
+
+ if (pocet_precteni >= N_KONZUMENTU) {
+ fronty[cislo_producenta]->pop();
+ nova_velikos_fronty = fronty[cislo_producenta]->size();
+ umozni_vlozeni_prvku(cislo_producenta);
+
+
+ prvek_odstranen = true;
+ // nova_velikos_fronty = xfronty[cislo_producenta].size();
+ //
+ // if (nova_velikos_fronty == (K_POLOZEK - 1)) {
+ // pthread_cond_signal(&condy_front[cislo_producenta]);
+ // printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
+ // cislo_konzumenta,
+ // cislo_producenta,
+ // velikos_fronty);
+ // }
+ }
+
+ poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
+ = prectene_poradove_cislo;
+ }
+ }
+ odemkni_frontu(cislo_producenta);
+
+ if (nove_nacteny) {
+ printf("%s cte z fronty %i prvek %i - pocet precteni %i\n",
+ process_name,
+ cislo_producenta,
+ prectene_poradove_cislo,
+ pocet_precteni);
+ nove_nacteny = false;
+ }
+
+ if (prvek_odstranen) {
+ printf("%s odsranil z fronty %i prvek %i - velikost fronty %i\n",
+ process_name,
+ cislo_producenta,
+ prectene_poradove_cislo,
+ nova_velikos_fronty);
+ prvek_odstranen = false;
+ }
+
+ if (ukonci_cteni) {
+ ukonci_cteni =
+ poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
+ }
+ }
}
printf("%s done.\n", process_name);
}
int main(int argc, char * const argv[]) {
+ // Fronta *f = malloc(Fronta::get_total_sizeof());
+ // Prvke p;
+ // p.poradove_cislo
+
pid_t root_pid = getpid();
bool exception = false;
try {
pid_t child_pid;
snprintf(process_name, MAX_NAME_SIZE, "Hlavni proces [PID:%d]", (int) getpid());
printf ("%s.\n", process_name, (int) root_pid);
root_init();
printf("Velikos Shared: %d, velikost Fronta: %d, velikost Prvek: %d.\n",
Shared::get_total_sizeof(), Fronta::get_total_sizeof(), sizeof(Prvek));
printf("Shared addr: %p (%d).\n", shared, (unsigned int) shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
printf("Fronta %d addr: %p (relativni: %d).\n",
i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
fronty[i]->init();
child_pid = fork();
if (child_pid != 0) {
child_pids[i] = child_pid;
} else {
producent(i);
exit(0);
}
}
for (int i = 0; i < N_KONZUMENTU; i++) {
child_pid = fork ();
if (child_pid != 0) {
child_pids[i + M_PRODUCENTU] = child_pid;
} else {
konzument(i);
exit(0);
}
}
} catch(...) {
exception = true;
}
if (getpid() == root_pid) {
root_finish();
}
if ( ! exception) {
printf("All OK. Done.\n");
return 0;
} else {
printf("%s exception caught in main(). Done.\n", process_name);
return 1;
}
}
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
244b26dd8ee06f4fc8e076c17e6c3fe857ac10b5
|
Pridan funkcni producent.
|
diff --git a/main.cpp b/main.cpp
index 3aac953..3e8f5c8 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,515 +1,636 @@
/**
* X36OSY - Producenti a konzumenti
*
* vypracoval: Tomas Horacek <horact1@fel.cvut.cz>
*
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
#include <signal.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
struct Prvek;
struct Fronta;
struct Shared;
const int M_PRODUCENTU = 5;
const int N_KONZUMENTU = 3;
const int K_POLOZEK = 3;
const int LIMIT_PRVKU = 10;
const int MAX_NAME_SIZE = 30;
const int NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
const int MAX_NAHODNA_DOBA = 50000;
pid_t *child_pids;
int shared_mem_segment_id;
Shared *shared;
Fronta **fronty;
char process_name[MAX_NAME_SIZE];
+int sem_pristup_ke_fronte;
+int sem_mohu_vlozit;
+int sem_mohu_cist;
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
+ Prvek() :
+ cislo_producenta(0),
+ poradove_cislo(0),
+ pocet_precteni(0) { }
+
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
+
+ void init(int _cislo_producenta, int _poradove_cislo) {
+ this->cislo_producenta = _cislo_producenta;
+ this->poradove_cislo = _poradove_cislo;
+ this->pocet_precteni = 0;
+ }
};
class Fronta {
/**
* Pametove rozlozeni fronty:
Fronta:
Instance tridy Fronta:
[_size]
[_index_of_first]
Prvky fronty: (nasleduji okamzite za instanci Fronta)
[instance 0 (tridy Prvek) fronty]
[instance 1 (tridy Prvek) fronty]
...
[instance K_POLOZEK - 1 (tridy Prvek) fronty] (fixni pocet prvku)
*/
unsigned int _size;
unsigned int _index_of_first;
Prvek *_get_array_of_prvky() {
unsigned char *tmp_ptr = (unsigned char *) this;
tmp_ptr += sizeof(Fronta);
return (Prvek *) tmp_ptr;
}
public:
void init() {
this->_size = 0;
this->_index_of_first = 0;
}
int size() {
return this->_size;
}
-
- int full() {
- return this->_size == K_POLOZEK;
- }
-
+
int empty() {
return this->_size == 0;
}
void front() {
}
void push(Prvek &prvek) {
-
+ this->_size++;
}
- void pop() {
+ Prvek &pop() {
}
static int get_total_sizeof() {
return sizeof(Fronta) + sizeof(Prvek) * K_POLOZEK;
}
};
typedef Fronta *p_Fronta;
struct Shared {
/**
*
* Struktura sdilene pameti:
Shared:
[pokracovat_ve_vypoctu]
Fronta 0:
[instance 0 tridy Fronta]
[prveky fronty 0]
Fronta 1:
[instance 1 tridy Fronta]
[prveky fronty 1]
...
Fronta M_PRODUCENTU - 1:
[instance M_PRODUCENTU - 1 tridy Fronta]
[prveky fronty M_PRODUCENTU - 1]
*/
volatile sig_atomic_t pokracovat_ve_vypoctu;
static void connect_and_init_local_ptrs() {
/** Pripoji pament a inicializuje lokalni ukazatele na sdilenou pamet. */
shared = (Shared *) shmat(shared_mem_segment_id, NULL, NULL);
fronty = new p_Fronta[M_PRODUCENTU];
unsigned char *tmp_ptr = (unsigned char *) shared;
tmp_ptr += sizeof(Shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
fronty[i] = (Fronta *) tmp_ptr;
tmp_ptr += Fronta::get_total_sizeof();
}
}
static int get_total_sizeof() {
int velikost_vesech_front = Fronta::get_total_sizeof() * M_PRODUCENTU;
return sizeof(Shared) + velikost_vesech_front;
}
};
pthread_cond_t condy_front[M_PRODUCENTU];
pthread_mutex_t mutexy_front[M_PRODUCENTU];
queue<Prvek*> xfronty[M_PRODUCENTU];
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
-/**
- * void *my_producent(void *idp)
- *
- * pseudokod:
- *
-def my_producent():
- for cislo_prvku in range(LIMIT_PRVKU):
- while je_fronta_plna():
- pockej_na_uvolneni_prvku()
-
- zamkni_frontu()
- pridej_prvek_do_fronty()
- odemkni_frontu()
-
- pockej_nahodnou_dobu()
-
- ukonci_vlakno()
- */
-void *xmy_producent(void *idp) {
- int cislo_producenta = *((int *) idp);
- Prvek *prvek;
- int velikos_fronty;
- for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
- prvek = new Prvek(cislo_producenta, poradove_cislo);
-
- pthread_mutex_lock(&mutexy_front[cislo_producenta]);
-
- while ((velikos_fronty = xfronty[cislo_producenta].size()) > K_POLOZEK) {
- printf("PRODUCENT %i je zablokovan - velikost fronty %i\n", cislo_producenta, velikos_fronty);
- pthread_cond_wait(&condy_front[cislo_producenta], &mutexy_front[cislo_producenta]);
- }
-
- xfronty[cislo_producenta].push(prvek);
-
- pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
-
- printf("PRODUCENT %i pridal prvek %i - velikos fronty %i\n",
- cislo_producenta,
- poradove_cislo,
- velikos_fronty
- );
-
- pockej_nahodnou_dobu();
- }
-
- printf("PRODUCENT %i konec\n", cislo_producenta);
- pthread_exit(NULL);
-}
-
/**
* void *konzument(void *idp)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
void *xkonzument(void *idp) {
int cislo_konzumenta = *((int *) idp) - M_PRODUCENTU;
bool ukonci_cteni;
int cislo_producenta;
int prectene_poradove_cislo;
int prectene_cislo_producenta;
int velikos_fronty;
Prvek *prvek;
int poradova_cisla_poslednich_prectenych_prveku[M_PRODUCENTU];
bool prvek_odstranen = false;
int nova_velikos_fronty;
bool nove_nacteny = false;
int pocet_precteni;
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
}
while (1) {
pockej_nahodnou_dobu();
ukonci_cteni = true;
for (cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
if ( ! xfronty[cislo_producenta].empty()) {
prvek = xfronty[cislo_producenta].front();
velikos_fronty = xfronty[cislo_producenta].size();
prectene_poradove_cislo = prvek->poradove_cislo;
prectene_cislo_producenta = prvek->cislo_producenta;
if (prectene_poradove_cislo
!= poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
nove_nacteny = true;
pocet_precteni = ++(prvek->pocet_precteni);
if (prvek->pocet_precteni == N_KONZUMENTU) {
xfronty[cislo_producenta].pop();
delete prvek;
pthread_cond_signal(&condy_front[cislo_producenta]);
prvek_odstranen = true;
nova_velikos_fronty = xfronty[cislo_producenta].size();
if (nova_velikos_fronty == (K_POLOZEK - 1)) {
pthread_cond_signal(&condy_front[cislo_producenta]);
printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
velikos_fronty);
}
}
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
= prectene_poradove_cislo;
}
}
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
if (nove_nacteny) {
printf("konzument %i cte z fronty %i prvek %i - pocet precteni %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni);
nove_nacteny = false;
}
if (prvek_odstranen) {
printf("konzument %i odsranil z fronty %i prvek %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
nova_velikos_fronty);
prvek_odstranen = false;
}
if (ukonci_cteni) {
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
== (LIMIT_PRVKU - 1);
}
}
if (ukonci_cteni) {
printf("konzument %i konec\n", cislo_konzumenta);
pthread_exit(NULL);
return NULL;
}
}
pthread_exit(NULL);
}
-void producent(int cislo_producenta) {
- snprintf(process_name, MAX_NAME_SIZE, "Producent %d [PID:%d]", cislo_producenta, (int) getpid());
- printf("%s.\n", process_name);
-
- Shared::connect_and_init_local_ptrs();
-
- sleep(3);
- printf("%s done.\n", process_name);
-}
-
-void konzument(int cislo_konzumenta) {
- snprintf(process_name, MAX_NAME_SIZE, "Konzument %d [PID:%d]", cislo_konzumenta, (int) getpid());
- printf("%s.\n", process_name);
-
- Shared::connect_and_init_local_ptrs();
-
- sleep(3);
- printf("%s done.\n", process_name);
-}
-
void alloc_shared_mem() {
int shared_segment_size = Shared::get_total_sizeof();
printf("%s alokuje pamet velikosti %dB.\n", process_name, shared_segment_size);
shared_mem_segment_id = shmget(IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
}
void dealloc_shared_mem() {
shmctl(shared_mem_segment_id, IPC_RMID, NULL);
}
void wait_for_all_children() {
int status;
for (int i = 0; i < NUM_CHILDREN; i++) {
wait(&status);
}
}
-void root_init() {
- child_pids = new pid_t[NUM_CHILDREN];
- alloc_shared_mem();
-}
-
-void dealloc_shared_resources() {
- dealloc_shared_mem();
- printf("%s dealokoval sdilene prostredky.\n", process_name);
-}
-
-void root_finish() {
- wait_for_all_children();
-
- dealloc_shared_resources();
- delete[] child_pids;
-}
-
void singnal_handler(int signal_number) {
- printf("%s prijal signal %d", process_name, signal_number);
+ printf("%s prijal signal %d\n", process_name, signal_number);
shared->pokracovat_ve_vypoctu = 0;
}
void init_sinals() {
- struct sigaction sa;
- memset (&sa, 0, sizeof (sa));
- sa.sa_handler = &singnal_handler;
- sigaction(SIGQUIT, &sa, NULL);
+ signal(SIGQUIT, singnal_handler);
+ signal(SIGINT, singnal_handler);
+ signal(SIGHUP, singnal_handler);
+ signal(SIGTERM, singnal_handler);
}
-int semaphore_allocation(key_t key, int semnum, int sem_flags) {
- return semget(key, semnum, sem_flags);
+int semaphore_allocation(int semnum) {
+ int sem_flags = IPC_CREAT | IPC_EXCL | SEM_R | SEM_A | SEM_R>>3 | SEM_A>>3 | SEM_R>>6 | SEM_A>>6;
+ int ret_val = semget(IPC_PRIVATE, semnum, sem_flags);
+
+ if (ret_val < 0) {
+ printf("Nepodarilo se inicializovat semafor.\n");
+ exit(1);
+ }
+
+ return ret_val;
}
-int semaphore_initialize(int semid, int semnum, int init_value) {
+void semaphore_initialize(int semid, int semnum, int init_value) {
semun argument;
- u_short *values = new u_short[semnum];
for (int i = 0; i < semnum; i++) {
- values[i] = init_value;
+ argument.val = init_value;
+ semctl(semid, i, SETVAL, argument);
}
-
- argument.array = values;
- int ret_val = semctl(semid, 0, SETALL, argument);
-
- delete[] values;
- return ret_val;
}
int semaphore_deallocate(int semid, int semnum) {
semun ignored_argument;
return semctl(semid, semnum, IPC_RMID, ignored_argument);
}
int semaphore_down(int semid, int sem_index) {
/* Wait on a binary semaphore. Block until the semaphore
value is positive, then decrement it by one. */
sembuf operations[1];
operations[0].sem_num = sem_index;
operations[0].sem_op = -1;
operations[0].sem_flg = SEM_UNDO;
return semop(semid, operations, 1);
}
int semaphore_up(int semid, int sem_index) {
/* Post to a semaphore: increment its value by one. This returns immediately. */
sembuf operations[1];
operations[0].sem_num = sem_index;
operations[0].sem_op = 1;
operations[0].sem_flg= SEM_UNDO;
return semop(semid, operations, 1);
}
+int semaphore_get(int semafor, int sem_index){
+ return semctl(semafor, sem_index, GETVAL, 0);
+}
+
+void dealloc_shared_resources() {
+ dealloc_shared_mem();
+ semaphore_deallocate(sem_mohu_vlozit, M_PRODUCENTU);
+ semaphore_deallocate(sem_mohu_cist, M_PRODUCENTU);
+ semaphore_deallocate(sem_pristup_ke_fronte, M_PRODUCENTU);
+ printf("%s dealokoval sdilene prostredky.\n", process_name);
+}
+
+void child_init() {
+ init_sinals();
+
+ Shared::connect_and_init_local_ptrs();
+}
+
+
+void root_init() {
+ child_pids = new pid_t[NUM_CHILDREN];
+ alloc_shared_mem();
+
+ init_sinals();
+
+ Shared::connect_and_init_local_ptrs();
+
+ shared->pokracovat_ve_vypoctu = 1;
+
+ sem_mohu_vlozit = semaphore_allocation(M_PRODUCENTU);
+ semaphore_initialize(sem_mohu_vlozit, M_PRODUCENTU, K_POLOZEK);
+
+ sem_mohu_cist = semaphore_allocation(M_PRODUCENTU);
+ semaphore_initialize(sem_mohu_cist, M_PRODUCENTU, 0);
+
+ sem_pristup_ke_fronte = semaphore_allocation(M_PRODUCENTU);
+ semaphore_initialize(sem_pristup_ke_fronte, M_PRODUCENTU, 1);
+
+ for (int i = 0; i < M_PRODUCENTU; i++) {
+ printf("Semafory nastaveny na: sem_mohu_vlozit(%d), sem_mohu_cist(%d), sem_pristup_ke_fronte(%d)\n",
+ semaphore_get(sem_mohu_vlozit, i),
+ semaphore_get(sem_mohu_cist, i),
+ semaphore_get(sem_pristup_ke_fronte, i));
+ }
+}
+
+
+void root_finish() {
+ wait_for_all_children();
+
+ dealloc_shared_resources();
+ delete[] child_pids;
+}
+
+void zamkni_frontu(int cislo_fronty) {
+ semaphore_down(sem_pristup_ke_fronte, cislo_fronty);
+}
+
+void odemkni_frontu(int cislo_fronty) {
+ semaphore_up(sem_pristup_ke_fronte, cislo_fronty);
+}
+
+void pockej_na_moznost_vkladat_prvek(int cislo_fronty) {
+ semaphore_down(sem_mohu_vlozit, cislo_fronty);
+}
+
+void umozni_vlozeni_prvku(int cislo_fronty) {
+ semaphore_up(sem_mohu_vlozit, cislo_fronty);
+}
+
+void umozni_cteni_z_fronty(int cislo_fronty) {
+ semaphore_up(sem_mohu_cist, cislo_fronty);
+}
+
+void pockej_na_moznost_cteni_z_fornty(int cislo_fronty) {
+ semaphore_down(sem_mohu_cist, cislo_fronty);
+}
+
+/**
+ * void producent(int cislo_producenta)
+ *
+ * pseudokod:
+ *
+def producent():
+ for poradove_cislo in range(LIMIT_PRVKU):
+ pockej_na_moznost_vkladat_prvek()
+
+ zamkni_frontu()
+ pridej_prvek_do_fronty()
+ odemkni_frontu()
+
+
+ pockej_nahodnou_dobu()
+
+ ukonci_vlakno()
+ */
+void producent(int cislo_producenta) {
+ snprintf(process_name, MAX_NAME_SIZE, "PRODUCENT %d [PID:%d]", cislo_producenta, (int) getpid());
+ printf("%s zacatek.\n", process_name);
+
+ child_init();
+
+ Prvek prvek;
+ int velikos_fronty;
+
+ for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
+ if (shared->pokracovat_ve_vypoctu) {
+ prvek.init(cislo_producenta, poradove_cislo);
+
+ zamkni_frontu(cislo_producenta);
+
+ velikos_fronty = fronty[cislo_producenta]->size();
+
+ if (velikos_fronty >= K_POLOZEK) {
+ odemkni_frontu(cislo_producenta);
+
+ printf("%s ceka na uvolneni fronty.\n", process_name);
+ pockej_na_moznost_vkladat_prvek(cislo_producenta);
+ printf("%s muze vlozit do fronty.\n", process_name);
+
+ zamkni_frontu(cislo_producenta);
+ } else {
+ pockej_na_moznost_vkladat_prvek(cislo_producenta);
+ }
+
+ // pridej_prvek_do_fronty()
+ fronty[cislo_producenta]->push(prvek);
+
+ umozni_cteni_z_fronty(cislo_producenta);
+
+ odemkni_frontu(cislo_producenta);
+
+ printf("%s pridal prvek %i - velikos fronty %i\n",
+ process_name, poradove_cislo, velikos_fronty);
+
+ pockej_nahodnou_dobu();
+ } else {
+ break;
+ }
+ }
+
+ printf("%s done.\n", process_name);
+}
+
+/**
+ * void konzument(int cislo_konzumenta)
+ *
+ * pseudokod:
+ *
+def konzument():
+ while True:
+ pockej_nahodnou_dobu()
+
+ ukonci_cteni = True
+ for producent in range(M_PRODUCENTU):
+ zamkni_frontu()
+ if not fornta_je_prazdna():
+ prvek = fronta[producent].front()
+
+ if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
+ prvek.pocet_precteni++
+
+ if prvek.pocet_precteni == N_KONZUMENTU:
+ fronta[producent].pop()
+ delete prvek;
+ zavolej_uvolneni_prvku()
+
+ poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
+ odemkni_frontu()
+
+ if ukonci_cteni:
+ ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
+
+ if ukonci_cteni:
+ ukonci_vlakno()
+ */
+void konzument(int cislo_konzumenta) {
+ snprintf(process_name, MAX_NAME_SIZE, "Konzument %d [PID:%d]", cislo_konzumenta, (int) getpid());
+ printf("%s zacatek.\n", process_name);
+
+ child_init();
+
+
+ for (int i = 0; i < LIMIT_PRVKU; i++) {
+ if (shared->pokracovat_ve_vypoctu) {
+ sleep(1);
+ } else {
+ break;
+ }
+ }
+
+ printf("%s done.\n", process_name);
+}
+
int main(int argc, char * const argv[]) {
+ pid_t root_pid = getpid();
bool exception = false;
try {
- pid_t root_pid = getpid();
pid_t child_pid;
snprintf(process_name, MAX_NAME_SIZE, "Hlavni proces [PID:%d]", (int) getpid());
printf ("%s.\n", process_name, (int) root_pid);
root_init();
printf("Velikos Shared: %d, velikost Fronta: %d, velikost Prvek: %d.\n",
Shared::get_total_sizeof(), Fronta::get_total_sizeof(), sizeof(Prvek));
- Shared::connect_and_init_local_ptrs();
-
printf("Shared addr: %p (%d).\n", shared, (unsigned int) shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
printf("Fronta %d addr: %p (relativni: %d).\n",
i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
fronty[i]->init();
child_pid = fork();
if (child_pid != 0) {
child_pids[i] = child_pid;
} else {
producent(i);
exit(0);
}
}
for (int i = 0; i < N_KONZUMENTU; i++) {
child_pid = fork ();
if (child_pid != 0) {
child_pids[i + M_PRODUCENTU] = child_pid;
} else {
konzument(i);
exit(0);
}
}
} catch(...) {
exception = true;
}
- root_finish();
+
+ if (getpid() == root_pid) {
+ root_finish();
+ }
if ( ! exception) {
printf("All OK. Done.\n");
return 0;
} else {
- printf("Exception caught in main(). Done.\n");
+ printf("%s exception caught in main(). Done.\n", process_name);
return 1;
}
}
\ No newline at end of file
|
heracek/x36osy-producenti-konzumenti-processes
|
b74fbba1dd34ca8dede289262ee3773706da0364
|
Pridany funkce pro obsluhu semaforu.
|
diff --git a/main.cpp b/main.cpp
index 61d8c23..3aac953 100644
--- a/main.cpp
+++ b/main.cpp
@@ -1,452 +1,515 @@
/**
* X36OSY - Producenti a konzumenti
*
* vypracoval: Tomas Horacek <horact1@fel.cvut.cz>
*
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
#include <signal.h>
+#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
struct Prvek;
struct Fronta;
struct Shared;
const int M_PRODUCENTU = 5;
const int N_KONZUMENTU = 3;
const int K_POLOZEK = 3;
const int LIMIT_PRVKU = 10;
const int MAX_NAME_SIZE = 30;
const int NUM_CHILDREN = M_PRODUCENTU + N_KONZUMENTU;
const int MAX_NAHODNA_DOBA = 50000;
pid_t *child_pids;
int shared_mem_segment_id;
Shared *shared;
Fronta **fronty;
char process_name[MAX_NAME_SIZE];
struct Prvek {
int cislo_producenta;
int poradove_cislo;
int pocet_precteni;
Prvek(int cislo_producenta, int poradove_cislo) :
cislo_producenta(cislo_producenta),
poradove_cislo(poradove_cislo),
pocet_precteni(0) { }
};
class Fronta {
/**
* Pametove rozlozeni fronty:
Fronta:
Instance tridy Fronta:
[_size]
[_index_of_first]
Prvky fronty: (nasleduji okamzite za instanci Fronta)
[instance 0 (tridy Prvek) fronty]
[instance 1 (tridy Prvek) fronty]
...
[instance K_POLOZEK - 1 (tridy Prvek) fronty] (fixni pocet prvku)
*/
unsigned int _size;
unsigned int _index_of_first;
Prvek *_get_array_of_prvky() {
unsigned char *tmp_ptr = (unsigned char *) this;
tmp_ptr += sizeof(Fronta);
return (Prvek *) tmp_ptr;
}
public:
void init() {
this->_size = 0;
this->_index_of_first = 0;
}
int size() {
return this->_size;
}
int full() {
return this->_size == K_POLOZEK;
}
int empty() {
return this->_size == 0;
}
void front() {
}
void push(Prvek &prvek) {
}
void pop() {
}
static int get_total_sizeof() {
return sizeof(Fronta) + sizeof(Prvek) * K_POLOZEK;
}
};
typedef Fronta *p_Fronta;
struct Shared {
/**
*
* Struktura sdilene pameti:
Shared:
[pokracovat_ve_vypoctu]
Fronta 0:
[instance 0 tridy Fronta]
[prveky fronty 0]
Fronta 1:
[instance 1 tridy Fronta]
[prveky fronty 1]
...
Fronta M_PRODUCENTU - 1:
[instance M_PRODUCENTU - 1 tridy Fronta]
[prveky fronty M_PRODUCENTU - 1]
*/
volatile sig_atomic_t pokracovat_ve_vypoctu;
static void connect_and_init_local_ptrs() {
/** Pripoji pament a inicializuje lokalni ukazatele na sdilenou pamet. */
shared = (Shared *) shmat(shared_mem_segment_id, NULL, NULL);
fronty = new p_Fronta[M_PRODUCENTU];
unsigned char *tmp_ptr = (unsigned char *) shared;
tmp_ptr += sizeof(Shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
fronty[i] = (Fronta *) tmp_ptr;
tmp_ptr += Fronta::get_total_sizeof();
}
}
static int get_total_sizeof() {
int velikost_vesech_front = Fronta::get_total_sizeof() * M_PRODUCENTU;
return sizeof(Shared) + velikost_vesech_front;
}
};
-
pthread_cond_t condy_front[M_PRODUCENTU];
pthread_mutex_t mutexy_front[M_PRODUCENTU];
queue<Prvek*> xfronty[M_PRODUCENTU];
void pockej_nahodnou_dobu() {
double result = 0.0;
int doba = random() % MAX_NAHODNA_DOBA;
for (int j = 0; j < doba; j++)
result = result + (double)random();
}
/**
* void *my_producent(void *idp)
*
* pseudokod:
*
def my_producent():
for cislo_prvku in range(LIMIT_PRVKU):
while je_fronta_plna():
pockej_na_uvolneni_prvku()
zamkni_frontu()
pridej_prvek_do_fronty()
odemkni_frontu()
pockej_nahodnou_dobu()
ukonci_vlakno()
*/
void *xmy_producent(void *idp) {
int cislo_producenta = *((int *) idp);
Prvek *prvek;
int velikos_fronty;
for (int poradove_cislo = 0; poradove_cislo < LIMIT_PRVKU; poradove_cislo++) {
prvek = new Prvek(cislo_producenta, poradove_cislo);
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
while ((velikos_fronty = xfronty[cislo_producenta].size()) > K_POLOZEK) {
printf("PRODUCENT %i je zablokovan - velikost fronty %i\n", cislo_producenta, velikos_fronty);
pthread_cond_wait(&condy_front[cislo_producenta], &mutexy_front[cislo_producenta]);
}
xfronty[cislo_producenta].push(prvek);
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
printf("PRODUCENT %i pridal prvek %i - velikos fronty %i\n",
cislo_producenta,
poradove_cislo,
velikos_fronty
);
pockej_nahodnou_dobu();
}
printf("PRODUCENT %i konec\n", cislo_producenta);
pthread_exit(NULL);
}
/**
* void *konzument(void *idp)
*
* pseudokod:
*
def konzument():
while True:
pockej_nahodnou_dobu()
ukonci_cteni = True
for producent in range(M_PRODUCENTU):
zamkni_frontu()
if not fornta_je_prazdna():
prvek = fronta[producent].front()
if prvek.poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[producent]:
prvek.pocet_precteni++
if prvek.pocet_precteni == N_KONZUMENTU:
fronta[producent].pop()
delete prvek;
zavolej_uvolneni_prvku()
poradova_cisla_poslednich_prectenych_prveku[producent] = prvek.poradove_cislo
odemkni_frontu()
if ukonci_cteni:
ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[producent] == (LIMIT_PRVKU - 1)
if ukonci_cteni:
ukonci_vlakno()
*/
void *xkonzument(void *idp) {
int cislo_konzumenta = *((int *) idp) - M_PRODUCENTU;
bool ukonci_cteni;
int cislo_producenta;
int prectene_poradove_cislo;
int prectene_cislo_producenta;
int velikos_fronty;
Prvek *prvek;
int poradova_cisla_poslednich_prectenych_prveku[M_PRODUCENTU];
bool prvek_odstranen = false;
int nova_velikos_fronty;
bool nove_nacteny = false;
int pocet_precteni;
for (int cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = -1;
}
while (1) {
pockej_nahodnou_dobu();
ukonci_cteni = true;
for (cislo_producenta = 0; cislo_producenta < M_PRODUCENTU; cislo_producenta++) {
pthread_mutex_lock(&mutexy_front[cislo_producenta]);
if ( ! xfronty[cislo_producenta].empty()) {
prvek = xfronty[cislo_producenta].front();
velikos_fronty = xfronty[cislo_producenta].size();
prectene_poradove_cislo = prvek->poradove_cislo;
prectene_cislo_producenta = prvek->cislo_producenta;
- if (prectene_poradove_cislo != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
+ if (prectene_poradove_cislo
+ != poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]) {
nove_nacteny = true;
pocet_precteni = ++(prvek->pocet_precteni);
if (prvek->pocet_precteni == N_KONZUMENTU) {
xfronty[cislo_producenta].pop();
delete prvek;
pthread_cond_signal(&condy_front[cislo_producenta]);
prvek_odstranen = true;
nova_velikos_fronty = xfronty[cislo_producenta].size();
if (nova_velikos_fronty == (K_POLOZEK - 1)) {
pthread_cond_signal(&condy_front[cislo_producenta]);
printf("konzument %i odblokoval frontu %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
velikos_fronty);
}
}
- poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] = prectene_poradove_cislo;
+ poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
+ = prectene_poradove_cislo;
}
}
pthread_mutex_unlock(&mutexy_front[cislo_producenta]);
if (nove_nacteny) {
printf("konzument %i cte z fronty %i prvek %i - pocet precteni %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
pocet_precteni);
nove_nacteny = false;
}
if (prvek_odstranen) {
printf("konzument %i odsranil z fronty %i prvek %i - velikost fronty %i\n",
cislo_konzumenta,
cislo_producenta,
prectene_poradove_cislo,
nova_velikos_fronty);
prvek_odstranen = false;
}
if (ukonci_cteni) {
- ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta] == (LIMIT_PRVKU - 1);
+ ukonci_cteni = poradova_cisla_poslednich_prectenych_prveku[cislo_producenta]
+ == (LIMIT_PRVKU - 1);
}
}
if (ukonci_cteni) {
printf("konzument %i konec\n", cislo_konzumenta);
pthread_exit(NULL);
return NULL;
}
}
pthread_exit(NULL);
}
void producent(int cislo_producenta) {
snprintf(process_name, MAX_NAME_SIZE, "Producent %d [PID:%d]", cislo_producenta, (int) getpid());
printf("%s.\n", process_name);
Shared::connect_and_init_local_ptrs();
sleep(3);
printf("%s done.\n", process_name);
}
void konzument(int cislo_konzumenta) {
snprintf(process_name, MAX_NAME_SIZE, "Konzument %d [PID:%d]", cislo_konzumenta, (int) getpid());
printf("%s.\n", process_name);
Shared::connect_and_init_local_ptrs();
sleep(3);
printf("%s done.\n", process_name);
}
void alloc_shared_mem() {
int shared_segment_size = Shared::get_total_sizeof();
printf("%s alokuje pamet velikosti %dB.\n", process_name, shared_segment_size);
- shared_mem_segment_id = shmget(IPC_PRIVATE, shared_segment_size, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
+ shared_mem_segment_id = shmget(IPC_PRIVATE, shared_segment_size,
+ IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
}
void dealloc_shared_mem() {
shmctl(shared_mem_segment_id, IPC_RMID, NULL);
}
void wait_for_all_children() {
int status;
for (int i = 0; i < NUM_CHILDREN; i++) {
wait(&status);
}
}
void root_init() {
child_pids = new pid_t[NUM_CHILDREN];
alloc_shared_mem();
}
void dealloc_shared_resources() {
dealloc_shared_mem();
printf("%s dealokoval sdilene prostredky.\n", process_name);
}
void root_finish() {
wait_for_all_children();
dealloc_shared_resources();
delete[] child_pids;
}
+void singnal_handler(int signal_number) {
+ printf("%s prijal signal %d", process_name, signal_number);
+ shared->pokracovat_ve_vypoctu = 0;
+}
+
+void init_sinals() {
+ struct sigaction sa;
+ memset (&sa, 0, sizeof (sa));
+ sa.sa_handler = &singnal_handler;
+ sigaction(SIGQUIT, &sa, NULL);
+}
+
+int semaphore_allocation(key_t key, int semnum, int sem_flags) {
+ return semget(key, semnum, sem_flags);
+}
+
+int semaphore_initialize(int semid, int semnum, int init_value) {
+ semun argument;
+ u_short *values = new u_short[semnum];
+
+ for (int i = 0; i < semnum; i++) {
+ values[i] = init_value;
+ }
+
+ argument.array = values;
+ int ret_val = semctl(semid, 0, SETALL, argument);
+
+ delete[] values;
+ return ret_val;
+}
+
+int semaphore_deallocate(int semid, int semnum) {
+ semun ignored_argument;
+ return semctl(semid, semnum, IPC_RMID, ignored_argument);
+}
+
+int semaphore_down(int semid, int sem_index) {
+ /* Wait on a binary semaphore. Block until the semaphore
+ value is positive, then decrement it by one. */
+ sembuf operations[1];
+ operations[0].sem_num = sem_index;
+ operations[0].sem_op = -1;
+ operations[0].sem_flg = SEM_UNDO;
+
+ return semop(semid, operations, 1);
+}
+
+
+int semaphore_up(int semid, int sem_index) {
+ /* Post to a semaphore: increment its value by one. This returns immediately. */
+ sembuf operations[1];
+ operations[0].sem_num = sem_index;
+ operations[0].sem_op = 1;
+ operations[0].sem_flg= SEM_UNDO;
+
+ return semop(semid, operations, 1);
+}
+
int main(int argc, char * const argv[]) {
bool exception = false;
try {
pid_t root_pid = getpid();
pid_t child_pid;
snprintf(process_name, MAX_NAME_SIZE, "Hlavni proces [PID:%d]", (int) getpid());
printf ("%s.\n", process_name, (int) root_pid);
-
+
root_init();
printf("Velikos Shared: %d, velikost Fronta: %d, velikost Prvek: %d.\n",
Shared::get_total_sizeof(), Fronta::get_total_sizeof(), sizeof(Prvek));
Shared::connect_and_init_local_ptrs();
printf("Shared addr: %p (%d).\n", shared, (unsigned int) shared);
for (int i = 0; i < M_PRODUCENTU; i++) {
- printf("Fronta %d addr: %p (relativni: %d).\n", i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
+ printf("Fronta %d addr: %p (relativni: %d).\n",
+ i , fronty[i], (unsigned int) fronty[i] - (unsigned int) shared);
fronty[i]->init();
child_pid = fork();
if (child_pid != 0) {
child_pids[i] = child_pid;
} else {
producent(i);
exit(0);
}
}
for (int i = 0; i < N_KONZUMENTU; i++) {
child_pid = fork ();
if (child_pid != 0) {
child_pids[i + M_PRODUCENTU] = child_pid;
} else {
konzument(i);
exit(0);
}
}
} catch(...) {
exception = true;
}
root_finish();
if ( ! exception) {
printf("All OK. Done.\n");
return 0;
} else {
printf("Exception caught in main(). Done.\n");
return 1;
}
}
\ No newline at end of file
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.