repo
string
commit
string
message
string
diff
string
cvan/secinv-client
b1864635b74d88f84a88eb4297656d3f8da23f13
initialize auth config
diff --git a/client/common.py b/client/common.py index d184f42..50a8a4c 100644 --- a/client/common.py +++ b/client/common.py @@ -1,103 +1,103 @@ from ConfigParser import ConfigParser import os import re import sys ROOT = os.path.dirname(os.path.abspath(__file__)) # Used to translate path in this directory to an absolute path. path = lambda *a: os.path.join(ROOT, *a) # Supress warnings. import warnings warnings.filterwarnings('ignore') # Path to client configuration file. AUTH_CONFIG_FN = path('auth.conf') CLIENT_CONFIG_FN = path('settings.conf') -client_config = ConfigParser() +client_config = auth_config = ConfigParser() try: client_config.readfp(file(CLIENT_CONFIG_FN)) except IOError: sys.exit("Error: Cannot open inventory configuration file '%s'" % CLIENT_CONFIG_FN) try: auth_config.readfp(file(AUTH_CONFIG_FN)) except IOError: sys.exit("Error: Cannot open inventory authorization token file '%s'" % AUTH_CONFIG_FN) ## Server. HOST = client_config.get('server', 'host') PORT = client_config.get('server', 'port') AUTH_TOKEN = auth_config.get('auth_token', 'auth_token') DEBUG = client_config.get('server', 'debug').lower() == 'true' and True or False ## Paths. RH_RELEASE = os.path.abspath(client_config.get('paths', 'rh_release')) IP_FORWARD = os.path.abspath(client_config.get('paths', 'ip_forward')) RPM_PKGS = os.path.abspath(client_config.get('paths', 'rpm_pkgs')) SSH_CONFIG_FILE = os.path.abspath(client_config.get('paths', 'ssh_config_file')) IPTABLES = client_config.get('paths', 'iptables') PHP_INI = client_config.get('paths', 'php_ini') MY_CNF = client_config.get('paths', 'my_cnf') IFCONFIG = client_config.get('paths', 'ifconfig') HOSTNAME = client_config.get('paths', 'hostname') UNAME = client_config.get('paths', 'uname') MOUNT = client_config.get('paths', 'mount') LSOF = client_config.get('paths', 'lsof') IPTABLES = client_config.get('paths', 'iptables') IPTABLES_SAVE = client_config.get('paths', 'iptables_save') ## Apache. APACHE_ROOT = os.path.abspath(client_config.get('apache', 'server_root')) APACHE_CONF = os.path.abspath(client_config.get('apache', 'conf_file')) APACHE_IGNORE_DIRECTIVES = [f.strip() for f in \ re.split(',', client_config.get('apache', 'ignore_directives'))] ## Miscellaneous. PARSE_CONF_COMMENTS = client_config.get('miscellaneous', 'parse_conf_comments').lower() == 'true' and True or False def clean_body(body, comments_prefix=('#')): """ Clean up whitespace, multiline instructions, and comments (if applicable). """ if not type(comments_prefix) in (tuple, list, str): raise TypeError if type(body) is list: lines = body else: lines = re.split('\n', body) body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] in comments_prefix): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] body += '%s\n' % line return body
cvan/secinv-client
9587a4e994f28f6467266767d527b8dd3a13f9be
remove auth conf and add gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0d3e86d --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +*.conf +*.pyc +*._* +.DS_Store +_build +.*.sw[po] +*.egg-info +dist +build +MANIFEST +.htaccess +
cvan/secinv-client
b14b33f2c24e96efbbc0f6e7be48be74634ac7cf
add auth config file
diff --git a/client/apacheparser.py b/client/apacheparser.py index 4e808c1..44c0bc5 100644 --- a/client/apacheparser.py +++ b/client/apacheparser.py @@ -1,242 +1,241 @@ import glob import os import re import sys from common import * class ApacheNode: re_comment = re.compile(r"""^#.*$""") re_section_start = re.compile(r"""^<(?P<name>[^/\s>]+)\s*(?P<value>[^>]+)?>$""") re_section_end = re.compile(r"""^</(?P<name>[^\s>]+)\s*>$""") #re_statement = re.compile(r"""^(?P<name>[^\s]+)\s*(?P<value>.+)?$""") def __init__(self, name, values=[], section=False): self.name = name self.children = [] self.values = values self.section = section def add_child(self, child): self.children.append(child) child.parent = self return child def find(self, path): """Return the first element which matches the path.""" pathelements = path.strip('/').split('/') if not pathelements[0]: return self return self._find(pathelements) def _find(self, pathelements): if pathelements: # There is still more to do ... next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result = child._find(pathelements) if result: return result return None else: # no pathelements left, result is self return self def findall(self, path): """Return all elements which match the path.""" pathelements = path.strip('/').split('/') if not pathelements[0]: return [self] return self._findall(pathelements) def _findall(self, pathelements): if pathelements: # there is still more to do ... result = [] next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result.extend(child._findall(pathelements)) return result else: # no pathelements left, result is self return [self] def print_r(self, indent=-1): """Recursively print node.""" if self.section: if indent >= 0: print ' ' * indent + '<' + self.name + ' ' + (' '.join(self.values)) + '>' for child in self.children: child.print_r(indent + 1) if indent >= 0: print ' ' * indent + '</' + self.name + '>' else: if indent >= 0: print ' ' * indent + self.name + ' ' + ' '.join(self.values) @classmethod def parse_file(cls, file): """Parse a file.""" try: f = open(file) root = cls._parse(f) f.close() return root except IOError: return False @classmethod def parse_string(cls, string): """Parse a string.""" return cls._parse(string.splitlines()) @classmethod def _parse(cls, itobj): root = node = ApacheNode('', section=True) for line in itobj: line = line.strip() if not line or cls.re_comment.match(line): continue # Concatenate multiline directives delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), itobj.next().strip()]) m = cls.re_section_start.match(line) if m: values = m.group('value').split() new_node = ApacheNode(m.group('name'), values=values, section=True) node = node.add_child(new_node) continue m = cls.re_section_end.match(line) if m: if node.name != m.group('name'): raise Exception("Section mismatch: '%s' should be '%s'" % ( m.group('name'), node.name)) node = node.parent continue values = line.split() name = values.pop(0) # Capitalize first letter. if name[0].islower(): name = name[0].upper() + name[1:] node.add_child(ApacheNode(name, values=values, section=False)) return root class ApacheConfig: def __init__(self): self.filename = None self.ac = None self.root = None self.directives = {} self.domains = {} def parse(self, filename): self.filename = filename self.ac = ApacheNode(filename) self.root = self.ac.parse_file(filename) self.scan_children(self.root.children) def get_body(self): re_comment = re.compile(r"""^#.*$""") try: config_file = open(self.filename, 'r') config_lines = config_file.readlines() config_file.close() except IOError: return '' return clean_body(config_lines, '#') def print_children(self, children, indent=-1): """Recursively print children.""" indent += 1 for child in children: print '\t' * indent + (child.section and '----- ' or '') + \ child.name, ' '.join(child.values), \ child.section and '-----' or '' print_children(child.children, indent) def scan_children(self, children, indent=-1): """Recursively scan children and build directives dictionary.""" body_list = [] for child in children: name = child.name value = ' '.join(child.values) body_list.append({'name': name, 'value': value, 'children': self.scan_children(child.children, indent)}) if name in self.directives: self.directives[name] += [value] # Check for lowercased directive. # TODO: Better check. elif name.lower() in self.directives: self.directives[name.lower()] += [value] else: self.directives[name] = [value] return body_list def get_directives(self): return self.directives def get_domains(self): vh = self.root.findall('VirtualHost') for v in vh: ports_str = ' '.join(v.values) # Strip all non-numeric characters. p = re.compile(r'[^0-9]+') ports_str = p.sub(' ', ports_str).strip() ports = re.split(' ', ports_str) sn = v.findall('ServerName') if sn: dn = sn[0].values[0] self.domains.setdefault(dn, []).append(ports) return self.domains def get_includes(self): included_list = [] sr_node = self.root.find('ServerRoot') if DEBUG: server_root = APACHE_ROOT else: if sr_node: server_root = ''.join(sr_node.values) # Strip quotation marks. if server_root[0] in ('"', "'") and \ server_root[0] == server_root[-1]: server_root = server_root[1:-1] else: server_root = APACHE_ROOT for i in self.root.findall('Include'): i = ''.join(i.values) i_fn = os.path.join(server_root, i) - #print '-', i_fn # Shell-style filename expansion (e.g., `conf.d/*.conf`). included_list += glob.glob(i_fn) return included_list diff --git a/client/auth.conf b/client/auth.conf new file mode 100644 index 0000000..95a3a46 --- /dev/null +++ b/client/auth.conf @@ -0,0 +1,2 @@ +[auth_token] +auth_token=Jz_Cl1d0kF);}SwE diff --git a/client/client.py b/client/client.py index 268bc92..2c40e49 100755 --- a/client/client.py +++ b/client/client.py @@ -1,51 +1,50 @@ #!/usr/bin/env python import xmlrpclib import sys from common import * from inventory import * -proxy = xmlrpclib.ServerProxy(uri="%s:%s" % (HOST, PORT), - verbose=False) +proxy = xmlrpclib.ServerProxy(uri="%s:%s" % (HOST, PORT), verbose=False) multicall = xmlrpclib.MultiCall(proxy) # Send authentication key. -multicall.authenticate(AUTH_KEY) +multicall.authenticate(AUTH_TOKEN) ip = Interfaces() ip_dict = ip.get_interfaces() system = System() system_dict = system.get_system_dict() services = Services() services_dict = services.get_services() rpms = RPMs() rpms_dict = rpms.get_rpms() cp = SSHConfig() sshconfig_dict = cp.parse() ipt = IPTables() ipt_dict = ipt.get_ipt_dict() acl = ApacheConfigList() acl_list = acl.get_apache_configs() phpini = PHPConfig() phpini_dict = phpini.parse() mycnf = MySQLConfig() mycnf_dict = mycnf.parse() multicall.machine(ip_dict, system_dict, services_dict, rpms_dict, sshconfig_dict, ipt_dict, acl_list, phpini_dict, mycnf_dict) result = multicall() print "Authentication: %s" % result[0] print "Received machine info: %s" % result[1] diff --git a/client/common.py b/client/common.py index c36c019..d184f42 100644 --- a/client/common.py +++ b/client/common.py @@ -1,95 +1,103 @@ from ConfigParser import ConfigParser import os import re import sys ROOT = os.path.dirname(os.path.abspath(__file__)) # Used to translate path in this directory to an absolute path. path = lambda *a: os.path.join(ROOT, *a) # Supress warnings. import warnings warnings.filterwarnings('ignore') # Path to client configuration file. +AUTH_CONFIG_FN = path('auth.conf') CLIENT_CONFIG_FN = path('settings.conf') client_config = ConfigParser() try: client_config.readfp(file(CLIENT_CONFIG_FN)) except IOError: sys.exit("Error: Cannot open inventory configuration file '%s'" % CLIENT_CONFIG_FN) +try: + auth_config.readfp(file(AUTH_CONFIG_FN)) +except IOError: + sys.exit("Error: Cannot open inventory authorization token file '%s'" + % AUTH_CONFIG_FN) + + ## Server. HOST = client_config.get('server', 'host') PORT = client_config.get('server', 'port') -AUTH_KEY = client_config.get('server', 'auth_key') +AUTH_TOKEN = auth_config.get('auth_token', 'auth_token') DEBUG = client_config.get('server', 'debug').lower() == 'true' and True or False ## Paths. RH_RELEASE = os.path.abspath(client_config.get('paths', 'rh_release')) IP_FORWARD = os.path.abspath(client_config.get('paths', 'ip_forward')) RPM_PKGS = os.path.abspath(client_config.get('paths', 'rpm_pkgs')) SSH_CONFIG_FILE = os.path.abspath(client_config.get('paths', 'ssh_config_file')) IPTABLES = client_config.get('paths', 'iptables') PHP_INI = client_config.get('paths', 'php_ini') MY_CNF = client_config.get('paths', 'my_cnf') IFCONFIG = client_config.get('paths', 'ifconfig') HOSTNAME = client_config.get('paths', 'hostname') UNAME = client_config.get('paths', 'uname') MOUNT = client_config.get('paths', 'mount') LSOF = client_config.get('paths', 'lsof') IPTABLES = client_config.get('paths', 'iptables') IPTABLES_SAVE = client_config.get('paths', 'iptables_save') ## Apache. APACHE_ROOT = os.path.abspath(client_config.get('apache', 'server_root')) APACHE_CONF = os.path.abspath(client_config.get('apache', 'conf_file')) APACHE_IGNORE_DIRECTIVES = [f.strip() for f in \ re.split(',', client_config.get('apache', 'ignore_directives'))] ## Miscellaneous. PARSE_CONF_COMMENTS = client_config.get('miscellaneous', 'parse_conf_comments').lower() == 'true' and True or False def clean_body(body, comments_prefix=('#')): """ Clean up whitespace, multiline instructions, and comments (if applicable). """ if not type(comments_prefix) in (tuple, list, str): raise TypeError if type(body) is list: lines = body else: lines = re.split('\n', body) body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] in comments_prefix): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] body += '%s\n' % line return body diff --git a/client/inventory.py b/client/inventory.py index 44f65c1..cbf3e9a 100644 --- a/client/inventory.py +++ b/client/inventory.py @@ -1,470 +1,470 @@ from ConfigParser import ConfigParser import os import re import subprocess import string from apacheparser import * from common import * # TODO: Use `logging`. class Interfaces: @classmethod def get_interfaces(cls): """ Return dictionary of IP address, MAC address, and netmask for each interface. """ - assets_dict = {} + i_dict = {} open_files = subprocess.Popen(IFCONFIG, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = open_files.split('\n') for line in lines: if not line: continue ls = line.split() if ls[0].strip(): interface = ls[0].strip() - assets_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''} + i_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''} # Get MAC address. if 'HWaddr' in ls: - assets_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower() + i_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower() # Get IP address and netmask. if 'inet' in ls: inet = ls[ls.index('inet') + 1] - assets_dict[interface]['i_ip'] = inet.split(':')[1] - assets_dict[interface]['i_mask'] = ls[-1].split(':')[1] + i_dict[interface]['i_ip'] = inet.split(':')[1] + i_dict[interface]['i_mask'] = ls[-1].split(':')[1] - return assets_dict + return i_dict class System: @classmethod def _get_ip(self): """Get `hostname` and return local IP address from hostname.""" try: import socket sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0] except (socket.error, socket.herror, socket.gaierror): sys_ip = '' return sys_ip @classmethod def _get_hostname(self): """Parse `hostname` and return local hostname.""" full_hn = subprocess.Popen(HOSTNAME, shell=True, stdout=subprocess.PIPE).communicate()[0] p = re.compile(r'([^\.]+)') m = p.match(full_hn) return m and m.group(0).strip() or '' @classmethod def _get_kernel_release(self): """ Call `uname -r` and return kernel release version number. """ kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True, stdout=subprocess.PIPE).communicate()[0] return kernel_rel.strip() @classmethod def _get_redhat_version(self, filename=RH_RELEASE): """ Parse `redhat-release` file and return release name and version number. """ rh_version = '' try: rh_file = open(filename, 'r') release_line = rh_file.readline() rh_file.close() p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n') m = p.match(release_line) if m: rh_version = m.group(1) except IOError: #raise Exception("Notice: Cannot open redhat-release file '%s'." % filename) print "Notice: Cannot open redhat-release file '%s'" % filename rh_version = '' return rh_version.strip() @classmethod def _ip_fwd_status(self, filename=IP_FORWARD): """ Parse `ip_forward` file and return a boolean of IP forwarding status. """ ip_fwd = 0 try: ip_file = open(filename, 'r') status_line = ip_file.readline().strip() ip_file.close() if status_line == '1': ip_fwd = 1 except IOError: #raise Exception("Notice: Cannot open ip_forward file '%s'." % filename) print "Notice: Cannot open ip_forward file '%s'" % filename pass return ip_fwd @classmethod def _nfs_status(self): """ Check and return an integer of whether a NFS is currently mounted. """ found_nfs = 0 mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True, stdout=subprocess.PIPE).communicate()[0] mount_info = mount_info.strip('\n') lines = mount_info.split('\n') for line in lines: if not line: continue p = re.compile(r'.+ type ([^\s].+) ') m = p.match(line) if m and m.group(1) == 'nfs': found_nfs = 1 break return found_nfs @classmethod def get_system_dict(cls): """Build and return dictionary of assets fields.""" - assets_dict = {'sys_ip': cls._get_ip(), + i_dict = {'sys_ip': cls._get_ip(), 'hostname': cls._get_hostname(), 'kernel_rel': cls._get_kernel_release(), 'rh_rel': cls._get_redhat_version(), 'nfs': cls._nfs_status(), 'ip_fwd': cls._ip_fwd_status()} - return assets_dict + return i_dict class Services: @classmethod def get_services(cls): """ Parse `lsof -ni -P` and return a dictionary of all listening processes and ports. """ ports_dict = {} open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = open_files.split('\n') for line in lines: if not line: continue chunks = re.split('\s*', line) if not '(LISTEN)' in chunks: continue proc_name = chunks[0] full_name = chunks[-2] ports_dict[proc_name] = full_name.split(':')[1] return ports_dict class RPMs: @classmethod def get_rpms(cls, filename=RPM_PKGS): """Get all RPMs installed.""" rpms_dict = {'list': ''} try: rpmpkgs_file = open(filename, 'r') lines = rpmpkgs_file.readlines() rpmpkgs_file.close() lines_str = ''.join(lines) lines_str = lines_str.strip('\n') rpms_dict = {'list': lines_str} except IOError: # TODO: Logging Error. #raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename) print "Notice: Cannot open rpmpkgs file '%s'" % filename return rpms_dict class SSHConfig: @classmethod def parse(cls, filename=SSH_CONFIG_FILE): """ Parse SSH configuration file and a return a dictionary of body, parameters/values, and filename. """ body = '' items = {} filename = path(filename) try: file_obj = open(filename, 'r') lines = file_obj.readlines() file_obj.close() except IOError: #raise Exception("Notice: Cannot open SSH config file '%s'." % filename) print "Notice: Cannot open SSH config file '%s'" % filename lines = '' if lines: body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] if line[0] != '#': ls = re.split('\s*', line) if ls[0] in items: items[ls[0]] += [' %s' % ' '.join(ls[1:])] else: items[ls[0]] = [' '.join(ls[1:])] body += '%s\n' % line ssh_dict = {'body': body, 'items': items, 'filename': filename} return ssh_dict class IPTables: @classmethod def _status(self): """ Check and return an integer of whether iptables are running. """ ipt_status = 0 status_info = subprocess.Popen('%s status' % IPTABLES, shell=True, stdout=subprocess.PIPE).communicate()[0] status_info = status_info.strip('\n') if status_info != 'Firewall is stopped.': ipt_status = 1 return ipt_status @classmethod def _parse(self): """ Parse IP tables and a return a dictionary of policies for each table. """ ipt_dict = {} lines = subprocess.Popen(IPTABLES_SAVE, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = lines.split('\n') table_name = '' body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \ (PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \ line.startswith('# Completed on')): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] if line[0] == ':': # Chain specification. # :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>] # Strip packet-counter and byte-counter. ls = line.split() if len(ls) > 2 and ls[0].strip(): chain_name = ls[0].strip()[1:] chain_policy = ls[1].strip() line = ':%s %s' % (chain_name, chain_policy) body += '%s\n' % line ipt_dict['body'] = body return ipt_dict @classmethod def get_ipt_dict(cls): """Build and return dictionary of iptables fields.""" ipt_dict = {'status': cls._status(), 'rules': cls._parse()} return ipt_dict class ApacheConfigList: def __init__(self): self.apache_configs = [] def recurse_apache_includes(self, fn, includes_list): for i_fn in includes_list: i_ac = ApacheConfig() i_ac.parse(i_fn) i_apache = {'body': i_ac.get_body(), 'filename': i_fn, 'directives': i_ac.get_directives(), 'domains': i_ac.get_domains(), 'included': i_ac.get_includes()} # Remove circular includes. try: del i_apache['included'][i_apache['included'].index(fn)] except ValueError: pass self.apache_configs.append(i_apache) self.recurse_apache_includes(i_fn, i_apache['included']) def recurse(self): ac = ApacheConfig() ac.parse(APACHE_CONF) apache = {'body': ac.get_body(), 'filename': APACHE_CONF, 'directives': ac.get_directives(), 'domains': ac.get_domains(), 'included': ac.get_includes()} # Remove circular includes. try: del apache['included'][apache['included'].index(APACHE_CONF)] except ValueError: pass self.apache_configs.append(apache) self.recurse_apache_includes(APACHE_CONF, apache['included']) def get_apache_configs(self): if os.path.exists(APACHE_CONF): self.recurse() return self.apache_configs class PHPConfig: def get_items(self): parameters = {} php_config = ConfigParser() try: php_config.readfp(file(path(PHP_INI))) sections = php_config.sections() except IOError: #sys.exit("Notice: Cannot open PHP configuration file '%s'" % PHP_INI) print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI sections = [] for section in sections: items = php_config.items(section) #parameters[section] = {} for item in items: #parameters[section][item[0]] = [item[1]] if item[0] in parameters: parameters[item[0]] += [item[1]] else: parameters[item[0]] = [item[1]] #parameters.setdefault(item[0], []).append(item[1]) return parameters def parse(self): try: file_obj = open(path(PHP_INI), 'r') lines = file_obj.readlines() file_obj.close() body = clean_body(lines, ';') items = self.get_items() php_dict = {'body': body, 'items': items, 'filename': PHP_INI} except IOError: #raise Exception("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)' print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI php_dict = {'body': '', 'items': [], 'filename': ''} return php_dict class MySQLConfig: def get_items(self): parameters = {} mysql_config = ConfigParser() try: mysql_config.readfp(file(path(MY_CNF))) sections = mysql_config.sections() except IOError: #sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF) print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF sections = [] for section in sections: items = mysql_config.items(section) #parameters[section] = {} for item in items: #parameters[section][item[0]] = [item[1]] if item[0] in parameters: parameters[item[0]] += [item[1]] else: parameters[item[0]] = [item[1]] #parameters.setdefault(item[0], []).append(item[1]) return parameters def parse(self): try: file_obj = open(path(MY_CNF), 'r') lines = file_obj.readlines() file_obj.close() body = clean_body(lines, '#') items = self.get_items() my_dict = {'body': body, 'items': items, 'filename': MY_CNF} except IOError: #raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)' print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF my_dict = {'body': '', 'items': [], 'filename': ''} return my_dict diff --git a/client/settings.conf b/client/settings.conf index 91511cd..02e4c65 100644 --- a/client/settings.conf +++ b/client/settings.conf @@ -1,34 +1,33 @@ [server] host=https://cm-sectest01 port=8668 -auth_key=Jz_Cl1d0kF);}SwE debug=false [paths] rh_release=/etc/redhat-release ip_forward=/proc/sys/net/ipv4/ip_forward rpm_pkgs=/var/log/rpmpkgs ssh_config_file=/etc/ssh/sshd_config iptables=/etc/init.d/iptables php_ini=/etc/php.ini my_cnf=/etc/my.cnf ifconfig=/sbin/ifconfig hostname=/bin/hostname uname=/bin/uname mount=/bin/mount lsof=/usr/sbin/lsof iptables=/etc/init.d/iptables iptables_save=/sbin/iptables-save [apache] server_root=/etc/httpd/ conf_file=%(server_root)s/conf/httpd.conf ignore_directives=AddLanguage, LanguagePriority [miscellaneous] parse_conf_comments=true
cvan/secinv-client
e18a991a5745817ba3d2b6a044987d46428ab3bd
check for null lines
diff --git a/client/inventory.py b/client/inventory.py index 03161a2..44f65c1 100644 --- a/client/inventory.py +++ b/client/inventory.py @@ -1,461 +1,470 @@ from ConfigParser import ConfigParser import os import re import subprocess import string from apacheparser import * from common import * # TODO: Use `logging`. class Interfaces: @classmethod def get_interfaces(cls): """ Return dictionary of IP address, MAC address, and netmask for each interface. """ assets_dict = {} open_files = subprocess.Popen(IFCONFIG, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = open_files.split('\n') for line in lines: + if not line: + continue + ls = line.split() if ls[0].strip(): interface = ls[0].strip() assets_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''} # Get MAC address. if 'HWaddr' in ls: assets_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower() # Get IP address and netmask. if 'inet' in ls: inet = ls[ls.index('inet') + 1] assets_dict[interface]['i_ip'] = inet.split(':')[1] assets_dict[interface]['i_mask'] = ls[-1].split(':')[1] return assets_dict class System: @classmethod def _get_ip(self): """Get `hostname` and return local IP address from hostname.""" try: import socket sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0] except (socket.error, socket.herror, socket.gaierror): sys_ip = '' return sys_ip @classmethod def _get_hostname(self): """Parse `hostname` and return local hostname.""" full_hn = subprocess.Popen(HOSTNAME, shell=True, stdout=subprocess.PIPE).communicate()[0] p = re.compile(r'([^\.]+)') m = p.match(full_hn) return m and m.group(0).strip() or '' @classmethod def _get_kernel_release(self): """ Call `uname -r` and return kernel release version number. """ kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True, stdout=subprocess.PIPE).communicate()[0] return kernel_rel.strip() @classmethod def _get_redhat_version(self, filename=RH_RELEASE): """ Parse `redhat-release` file and return release name and version number. """ rh_version = '' try: rh_file = open(filename, 'r') release_line = rh_file.readline() rh_file.close() p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n') m = p.match(release_line) if m: rh_version = m.group(1) except IOError: #raise Exception("Notice: Cannot open redhat-release file '%s'." % filename) print "Notice: Cannot open redhat-release file '%s'" % filename rh_version = '' return rh_version.strip() @classmethod def _ip_fwd_status(self, filename=IP_FORWARD): """ Parse `ip_forward` file and return a boolean of IP forwarding status. """ ip_fwd = 0 try: ip_file = open(filename, 'r') status_line = ip_file.readline().strip() ip_file.close() if status_line == '1': ip_fwd = 1 except IOError: #raise Exception("Notice: Cannot open ip_forward file '%s'." % filename) print "Notice: Cannot open ip_forward file '%s'" % filename pass return ip_fwd @classmethod def _nfs_status(self): """ Check and return an integer of whether a NFS is currently mounted. """ found_nfs = 0 mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True, stdout=subprocess.PIPE).communicate()[0] mount_info = mount_info.strip('\n') lines = mount_info.split('\n') for line in lines: + if not line: + continue + p = re.compile(r'.+ type ([^\s].+) ') m = p.match(line) if m and m.group(1) == 'nfs': found_nfs = 1 break return found_nfs @classmethod def get_system_dict(cls): """Build and return dictionary of assets fields.""" assets_dict = {'sys_ip': cls._get_ip(), 'hostname': cls._get_hostname(), 'kernel_rel': cls._get_kernel_release(), 'rh_rel': cls._get_redhat_version(), 'nfs': cls._nfs_status(), 'ip_fwd': cls._ip_fwd_status()} return assets_dict class Services: @classmethod def get_services(cls): """ Parse `lsof -ni -P` and return a dictionary of all listening processes and ports. """ ports_dict = {} open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = open_files.split('\n') for line in lines: + if not line: + continue + chunks = re.split('\s*', line) if not '(LISTEN)' in chunks: continue proc_name = chunks[0] full_name = chunks[-2] ports_dict[proc_name] = full_name.split(':')[1] return ports_dict class RPMs: @classmethod def get_rpms(cls, filename=RPM_PKGS): """Get all RPMs installed.""" rpms_dict = {'list': ''} try: rpmpkgs_file = open(filename, 'r') lines = rpmpkgs_file.readlines() rpmpkgs_file.close() lines_str = ''.join(lines) lines_str = lines_str.strip('\n') rpms_dict = {'list': lines_str} except IOError: # TODO: Logging Error. #raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename) print "Notice: Cannot open rpmpkgs file '%s'" % filename return rpms_dict class SSHConfig: @classmethod def parse(cls, filename=SSH_CONFIG_FILE): """ Parse SSH configuration file and a return a dictionary of body, parameters/values, and filename. """ body = '' items = {} filename = path(filename) try: file_obj = open(filename, 'r') lines = file_obj.readlines() file_obj.close() except IOError: #raise Exception("Notice: Cannot open SSH config file '%s'." % filename) print "Notice: Cannot open SSH config file '%s'" % filename lines = '' if lines: body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] if line[0] != '#': ls = re.split('\s*', line) if ls[0] in items: items[ls[0]] += [' %s' % ' '.join(ls[1:])] else: items[ls[0]] = [' '.join(ls[1:])] body += '%s\n' % line ssh_dict = {'body': body, 'items': items, 'filename': filename} return ssh_dict class IPTables: @classmethod def _status(self): """ Check and return an integer of whether iptables are running. """ ipt_status = 0 status_info = subprocess.Popen('%s status' % IPTABLES, shell=True, stdout=subprocess.PIPE).communicate()[0] status_info = status_info.strip('\n') if status_info != 'Firewall is stopped.': ipt_status = 1 return ipt_status @classmethod def _parse(self): """ Parse IP tables and a return a dictionary of policies for each table. """ ipt_dict = {} lines = subprocess.Popen(IPTABLES_SAVE, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = lines.split('\n') table_name = '' body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \ (PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \ line.startswith('# Completed on')): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] if line[0] == ':': # Chain specification. # :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>] # Strip packet-counter and byte-counter. ls = line.split() if len(ls) > 2 and ls[0].strip(): chain_name = ls[0].strip()[1:] chain_policy = ls[1].strip() line = ':%s %s' % (chain_name, chain_policy) body += '%s\n' % line ipt_dict['body'] = body return ipt_dict @classmethod def get_ipt_dict(cls): """Build and return dictionary of iptables fields.""" ipt_dict = {'status': cls._status(), 'rules': cls._parse()} return ipt_dict class ApacheConfigList: def __init__(self): self.apache_configs = [] def recurse_apache_includes(self, fn, includes_list): for i_fn in includes_list: i_ac = ApacheConfig() i_ac.parse(i_fn) i_apache = {'body': i_ac.get_body(), 'filename': i_fn, 'directives': i_ac.get_directives(), 'domains': i_ac.get_domains(), 'included': i_ac.get_includes()} # Remove circular includes. try: del i_apache['included'][i_apache['included'].index(fn)] except ValueError: pass self.apache_configs.append(i_apache) self.recurse_apache_includes(i_fn, i_apache['included']) def recurse(self): ac = ApacheConfig() ac.parse(APACHE_CONF) apache = {'body': ac.get_body(), 'filename': APACHE_CONF, 'directives': ac.get_directives(), 'domains': ac.get_domains(), 'included': ac.get_includes()} # Remove circular includes. try: del apache['included'][apache['included'].index(APACHE_CONF)] except ValueError: pass self.apache_configs.append(apache) self.recurse_apache_includes(APACHE_CONF, apache['included']) def get_apache_configs(self): if os.path.exists(APACHE_CONF): self.recurse() return self.apache_configs class PHPConfig: def get_items(self): parameters = {} php_config = ConfigParser() try: php_config.readfp(file(path(PHP_INI))) sections = php_config.sections() except IOError: #sys.exit("Notice: Cannot open PHP configuration file '%s'" % PHP_INI) print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI sections = [] for section in sections: items = php_config.items(section) #parameters[section] = {} for item in items: #parameters[section][item[0]] = [item[1]] if item[0] in parameters: parameters[item[0]] += [item[1]] else: parameters[item[0]] = [item[1]] #parameters.setdefault(item[0], []).append(item[1]) return parameters def parse(self): try: file_obj = open(path(PHP_INI), 'r') lines = file_obj.readlines() file_obj.close() body = clean_body(lines, ';') items = self.get_items() php_dict = {'body': body, 'items': items, 'filename': PHP_INI} except IOError: #raise Exception("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)' print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI php_dict = {'body': '', 'items': [], 'filename': ''} return php_dict class MySQLConfig: def get_items(self): parameters = {} mysql_config = ConfigParser() try: mysql_config.readfp(file(path(MY_CNF))) sections = mysql_config.sections() except IOError: #sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF) print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF sections = [] for section in sections: items = mysql_config.items(section) #parameters[section] = {} for item in items: #parameters[section][item[0]] = [item[1]] if item[0] in parameters: parameters[item[0]] += [item[1]] else: parameters[item[0]] = [item[1]] #parameters.setdefault(item[0], []).append(item[1]) return parameters def parse(self): try: file_obj = open(path(MY_CNF), 'r') lines = file_obj.readlines() file_obj.close() body = clean_body(lines, '#') items = self.get_items() my_dict = {'body': body, 'items': items, 'filename': MY_CNF} except IOError: #raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)' print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF my_dict = {'body': '', 'items': [], 'filename': ''} return my_dict
cvan/secinv-client
04bc3160d5327dda66a4770a4162687690298815
add setdefault
diff --git a/client/apacheparser.py b/client/apacheparser.py index 0f3039f..4e808c1 100644 --- a/client/apacheparser.py +++ b/client/apacheparser.py @@ -1,245 +1,242 @@ import glob import os import re import sys from common import * class ApacheNode: re_comment = re.compile(r"""^#.*$""") re_section_start = re.compile(r"""^<(?P<name>[^/\s>]+)\s*(?P<value>[^>]+)?>$""") re_section_end = re.compile(r"""^</(?P<name>[^\s>]+)\s*>$""") #re_statement = re.compile(r"""^(?P<name>[^\s]+)\s*(?P<value>.+)?$""") def __init__(self, name, values=[], section=False): self.name = name self.children = [] self.values = values self.section = section def add_child(self, child): self.children.append(child) child.parent = self return child def find(self, path): """Return the first element which matches the path.""" pathelements = path.strip('/').split('/') if not pathelements[0]: return self return self._find(pathelements) def _find(self, pathelements): if pathelements: # There is still more to do ... next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result = child._find(pathelements) if result: return result return None else: # no pathelements left, result is self return self def findall(self, path): """Return all elements which match the path.""" pathelements = path.strip('/').split('/') if not pathelements[0]: return [self] return self._findall(pathelements) def _findall(self, pathelements): if pathelements: # there is still more to do ... result = [] next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result.extend(child._findall(pathelements)) return result else: # no pathelements left, result is self return [self] def print_r(self, indent=-1): """Recursively print node.""" if self.section: if indent >= 0: print ' ' * indent + '<' + self.name + ' ' + (' '.join(self.values)) + '>' for child in self.children: child.print_r(indent + 1) if indent >= 0: print ' ' * indent + '</' + self.name + '>' else: if indent >= 0: print ' ' * indent + self.name + ' ' + ' '.join(self.values) @classmethod def parse_file(cls, file): """Parse a file.""" try: f = open(file) root = cls._parse(f) f.close() return root except IOError: return False @classmethod def parse_string(cls, string): """Parse a string.""" return cls._parse(string.splitlines()) @classmethod def _parse(cls, itobj): root = node = ApacheNode('', section=True) for line in itobj: line = line.strip() if not line or cls.re_comment.match(line): continue # Concatenate multiline directives delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), itobj.next().strip()]) m = cls.re_section_start.match(line) if m: values = m.group('value').split() new_node = ApacheNode(m.group('name'), values=values, section=True) node = node.add_child(new_node) continue m = cls.re_section_end.match(line) if m: if node.name != m.group('name'): raise Exception("Section mismatch: '%s' should be '%s'" % ( m.group('name'), node.name)) node = node.parent continue values = line.split() name = values.pop(0) # Capitalize first letter. if name[0].islower(): name = name[0].upper() + name[1:] node.add_child(ApacheNode(name, values=values, section=False)) return root class ApacheConfig: def __init__(self): self.filename = None self.ac = None self.root = None self.directives = {} self.domains = {} def parse(self, filename): self.filename = filename self.ac = ApacheNode(filename) self.root = self.ac.parse_file(filename) self.scan_children(self.root.children) def get_body(self): re_comment = re.compile(r"""^#.*$""") try: config_file = open(self.filename, 'r') config_lines = config_file.readlines() config_file.close() except IOError: return '' return clean_body(config_lines, '#') def print_children(self, children, indent=-1): """Recursively print children.""" indent += 1 for child in children: print '\t' * indent + (child.section and '----- ' or '') + \ child.name, ' '.join(child.values), \ child.section and '-----' or '' print_children(child.children, indent) def scan_children(self, children, indent=-1): """Recursively scan children and build directives dictionary.""" body_list = [] for child in children: name = child.name value = ' '.join(child.values) body_list.append({'name': name, 'value': value, 'children': self.scan_children(child.children, indent)}) if name in self.directives: self.directives[name] += [value] # Check for lowercased directive. # TODO: Better check. elif name.lower() in self.directives: self.directives[name.lower()] += [value] else: self.directives[name] = [value] return body_list def get_directives(self): return self.directives def get_domains(self): vh = self.root.findall('VirtualHost') for v in vh: ports_str = ' '.join(v.values) # Strip all non-numeric characters. p = re.compile(r'[^0-9]+') ports_str = p.sub(' ', ports_str).strip() ports = re.split(' ', ports_str) sn = v.findall('ServerName') if sn: dn = sn[0].values[0] - if dn in self.domains: - self.domains[dn] += ports - else: - self.domains[dn] = ports + self.domains.setdefault(dn, []).append(ports) return self.domains def get_includes(self): included_list = [] sr_node = self.root.find('ServerRoot') if DEBUG: server_root = APACHE_ROOT else: if sr_node: server_root = ''.join(sr_node.values) # Strip quotation marks. if server_root[0] in ('"', "'") and \ server_root[0] == server_root[-1]: server_root = server_root[1:-1] else: server_root = APACHE_ROOT for i in self.root.findall('Include'): i = ''.join(i.values) i_fn = os.path.join(server_root, i) #print '-', i_fn # Shell-style filename expansion (e.g., `conf.d/*.conf`). included_list += glob.glob(i_fn) return included_list diff --git a/client/common.py b/client/common.py index 5b4582e..c36c019 100644 --- a/client/common.py +++ b/client/common.py @@ -1,96 +1,95 @@ from ConfigParser import ConfigParser import os import re import sys ROOT = os.path.dirname(os.path.abspath(__file__)) # Used to translate path in this directory to an absolute path. path = lambda *a: os.path.join(ROOT, *a) # Supress warnings. import warnings warnings.filterwarnings('ignore') # Path to client configuration file. CLIENT_CONFIG_FN = path('settings.conf') client_config = ConfigParser() try: client_config.readfp(file(CLIENT_CONFIG_FN)) except IOError: sys.exit("Error: Cannot open inventory configuration file '%s'" % CLIENT_CONFIG_FN) ## Server. HOST = client_config.get('server', 'host') PORT = client_config.get('server', 'port') AUTH_KEY = client_config.get('server', 'auth_key') DEBUG = client_config.get('server', 'debug').lower() == 'true' and True or False ## Paths. RH_RELEASE = os.path.abspath(client_config.get('paths', 'rh_release')) IP_FORWARD = os.path.abspath(client_config.get('paths', 'ip_forward')) RPM_PKGS = os.path.abspath(client_config.get('paths', 'rpm_pkgs')) SSH_CONFIG_FILE = os.path.abspath(client_config.get('paths', 'ssh_config_file')) IPTABLES = client_config.get('paths', 'iptables') PHP_INI = client_config.get('paths', 'php_ini') MY_CNF = client_config.get('paths', 'my_cnf') IFCONFIG = client_config.get('paths', 'ifconfig') HOSTNAME = client_config.get('paths', 'hostname') UNAME = client_config.get('paths', 'uname') MOUNT = client_config.get('paths', 'mount') LSOF = client_config.get('paths', 'lsof') IPTABLES = client_config.get('paths', 'iptables') IPTABLES_SAVE = client_config.get('paths', 'iptables_save') ## Apache. APACHE_ROOT = os.path.abspath(client_config.get('apache', 'server_root')) APACHE_CONF = os.path.abspath(client_config.get('apache', 'conf_file')) APACHE_IGNORE_DIRECTIVES = [f.strip() for f in \ re.split(',', client_config.get('apache', 'ignore_directives'))] ## Miscellaneous. PARSE_CONF_COMMENTS = client_config.get('miscellaneous', 'parse_conf_comments').lower() == 'true' and True or False - def clean_body(body, comments_prefix=('#')): """ Clean up whitespace, multiline instructions, and comments (if applicable). """ if not type(comments_prefix) in (tuple, list, str): raise TypeError if type(body) is list: lines = body else: lines = re.split('\n', body) body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] in comments_prefix): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] body += '%s\n' % line return body
cvan/secinv-client
b889723fe9f2ab36df0bd4347a0d1e65bd06b25b
undo setdefault, remove redundant split argument
diff --git a/client/apacheparser.py b/client/apacheparser.py index 4e808c1..0f3039f 100644 --- a/client/apacheparser.py +++ b/client/apacheparser.py @@ -1,242 +1,245 @@ import glob import os import re import sys from common import * class ApacheNode: re_comment = re.compile(r"""^#.*$""") re_section_start = re.compile(r"""^<(?P<name>[^/\s>]+)\s*(?P<value>[^>]+)?>$""") re_section_end = re.compile(r"""^</(?P<name>[^\s>]+)\s*>$""") #re_statement = re.compile(r"""^(?P<name>[^\s]+)\s*(?P<value>.+)?$""") def __init__(self, name, values=[], section=False): self.name = name self.children = [] self.values = values self.section = section def add_child(self, child): self.children.append(child) child.parent = self return child def find(self, path): """Return the first element which matches the path.""" pathelements = path.strip('/').split('/') if not pathelements[0]: return self return self._find(pathelements) def _find(self, pathelements): if pathelements: # There is still more to do ... next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result = child._find(pathelements) if result: return result return None else: # no pathelements left, result is self return self def findall(self, path): """Return all elements which match the path.""" pathelements = path.strip('/').split('/') if not pathelements[0]: return [self] return self._findall(pathelements) def _findall(self, pathelements): if pathelements: # there is still more to do ... result = [] next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result.extend(child._findall(pathelements)) return result else: # no pathelements left, result is self return [self] def print_r(self, indent=-1): """Recursively print node.""" if self.section: if indent >= 0: print ' ' * indent + '<' + self.name + ' ' + (' '.join(self.values)) + '>' for child in self.children: child.print_r(indent + 1) if indent >= 0: print ' ' * indent + '</' + self.name + '>' else: if indent >= 0: print ' ' * indent + self.name + ' ' + ' '.join(self.values) @classmethod def parse_file(cls, file): """Parse a file.""" try: f = open(file) root = cls._parse(f) f.close() return root except IOError: return False @classmethod def parse_string(cls, string): """Parse a string.""" return cls._parse(string.splitlines()) @classmethod def _parse(cls, itobj): root = node = ApacheNode('', section=True) for line in itobj: line = line.strip() if not line or cls.re_comment.match(line): continue # Concatenate multiline directives delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), itobj.next().strip()]) m = cls.re_section_start.match(line) if m: values = m.group('value').split() new_node = ApacheNode(m.group('name'), values=values, section=True) node = node.add_child(new_node) continue m = cls.re_section_end.match(line) if m: if node.name != m.group('name'): raise Exception("Section mismatch: '%s' should be '%s'" % ( m.group('name'), node.name)) node = node.parent continue values = line.split() name = values.pop(0) # Capitalize first letter. if name[0].islower(): name = name[0].upper() + name[1:] node.add_child(ApacheNode(name, values=values, section=False)) return root class ApacheConfig: def __init__(self): self.filename = None self.ac = None self.root = None self.directives = {} self.domains = {} def parse(self, filename): self.filename = filename self.ac = ApacheNode(filename) self.root = self.ac.parse_file(filename) self.scan_children(self.root.children) def get_body(self): re_comment = re.compile(r"""^#.*$""") try: config_file = open(self.filename, 'r') config_lines = config_file.readlines() config_file.close() except IOError: return '' return clean_body(config_lines, '#') def print_children(self, children, indent=-1): """Recursively print children.""" indent += 1 for child in children: print '\t' * indent + (child.section and '----- ' or '') + \ child.name, ' '.join(child.values), \ child.section and '-----' or '' print_children(child.children, indent) def scan_children(self, children, indent=-1): """Recursively scan children and build directives dictionary.""" body_list = [] for child in children: name = child.name value = ' '.join(child.values) body_list.append({'name': name, 'value': value, 'children': self.scan_children(child.children, indent)}) if name in self.directives: self.directives[name] += [value] # Check for lowercased directive. # TODO: Better check. elif name.lower() in self.directives: self.directives[name.lower()] += [value] else: self.directives[name] = [value] return body_list def get_directives(self): return self.directives def get_domains(self): vh = self.root.findall('VirtualHost') for v in vh: ports_str = ' '.join(v.values) # Strip all non-numeric characters. p = re.compile(r'[^0-9]+') ports_str = p.sub(' ', ports_str).strip() ports = re.split(' ', ports_str) sn = v.findall('ServerName') if sn: dn = sn[0].values[0] - self.domains.setdefault(dn, []).append(ports) + if dn in self.domains: + self.domains[dn] += ports + else: + self.domains[dn] = ports return self.domains def get_includes(self): included_list = [] sr_node = self.root.find('ServerRoot') if DEBUG: server_root = APACHE_ROOT else: if sr_node: server_root = ''.join(sr_node.values) # Strip quotation marks. if server_root[0] in ('"', "'") and \ server_root[0] == server_root[-1]: server_root = server_root[1:-1] else: server_root = APACHE_ROOT for i in self.root.findall('Include'): i = ''.join(i.values) i_fn = os.path.join(server_root, i) #print '-', i_fn # Shell-style filename expansion (e.g., `conf.d/*.conf`). included_list += glob.glob(i_fn) return included_list diff --git a/client/common.py b/client/common.py index d8b7376..5b4582e 100644 --- a/client/common.py +++ b/client/common.py @@ -1,96 +1,96 @@ from ConfigParser import ConfigParser import os import re import sys ROOT = os.path.dirname(os.path.abspath(__file__)) # Used to translate path in this directory to an absolute path. path = lambda *a: os.path.join(ROOT, *a) # Supress warnings. import warnings warnings.filterwarnings('ignore') # Path to client configuration file. CLIENT_CONFIG_FN = path('settings.conf') client_config = ConfigParser() try: client_config.readfp(file(CLIENT_CONFIG_FN)) except IOError: sys.exit("Error: Cannot open inventory configuration file '%s'" % CLIENT_CONFIG_FN) ## Server. HOST = client_config.get('server', 'host') PORT = client_config.get('server', 'port') AUTH_KEY = client_config.get('server', 'auth_key') DEBUG = client_config.get('server', 'debug').lower() == 'true' and True or False ## Paths. RH_RELEASE = os.path.abspath(client_config.get('paths', 'rh_release')) IP_FORWARD = os.path.abspath(client_config.get('paths', 'ip_forward')) RPM_PKGS = os.path.abspath(client_config.get('paths', 'rpm_pkgs')) SSH_CONFIG_FILE = os.path.abspath(client_config.get('paths', 'ssh_config_file')) IPTABLES = client_config.get('paths', 'iptables') PHP_INI = client_config.get('paths', 'php_ini') MY_CNF = client_config.get('paths', 'my_cnf') IFCONFIG = client_config.get('paths', 'ifconfig') HOSTNAME = client_config.get('paths', 'hostname') UNAME = client_config.get('paths', 'uname') MOUNT = client_config.get('paths', 'mount') LSOF = client_config.get('paths', 'lsof') IPTABLES = client_config.get('paths', 'iptables') IPTABLES_SAVE = client_config.get('paths', 'iptables_save') ## Apache. APACHE_ROOT = os.path.abspath(client_config.get('apache', 'server_root')) APACHE_CONF = os.path.abspath(client_config.get('apache', 'conf_file')) APACHE_IGNORE_DIRECTIVES = [f.strip() for f in \ re.split(',', client_config.get('apache', 'ignore_directives'))] ## Miscellaneous. PARSE_CONF_COMMENTS = client_config.get('miscellaneous', 'parse_conf_comments').lower() == 'true' and True or False def clean_body(body, comments_prefix=('#')): """ Clean up whitespace, multiline instructions, and comments (if applicable). """ if not type(comments_prefix) in (tuple, list, str): raise TypeError if type(body) is list: lines = body else: lines = re.split('\n', body) body = '' for index, line in enumerate(lines): line = line.strip() - if len(line) == 0 or (not PARSE_CONF_COMMENTS and line[0] in comments_prefix): + if not line or (not PARSE_CONF_COMMENTS and line[0] in comments_prefix): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] body += '%s\n' % line return body diff --git a/client/inventory.py b/client/inventory.py index 8caab7b..03161a2 100644 --- a/client/inventory.py +++ b/client/inventory.py @@ -1,461 +1,461 @@ from ConfigParser import ConfigParser import os import re import subprocess import string from apacheparser import * from common import * # TODO: Use `logging`. class Interfaces: @classmethod def get_interfaces(cls): """ Return dictionary of IP address, MAC address, and netmask for each interface. """ assets_dict = {} open_files = subprocess.Popen(IFCONFIG, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = open_files.split('\n') for line in lines: - ls = line.split(' ') + ls = line.split() if ls[0].strip(): interface = ls[0].strip() assets_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''} # Get MAC address. if 'HWaddr' in ls: assets_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower() # Get IP address and netmask. if 'inet' in ls: inet = ls[ls.index('inet') + 1] assets_dict[interface]['i_ip'] = inet.split(':')[1] assets_dict[interface]['i_mask'] = ls[-1].split(':')[1] return assets_dict class System: @classmethod def _get_ip(self): """Get `hostname` and return local IP address from hostname.""" try: import socket sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0] except (socket.error, socket.herror, socket.gaierror): sys_ip = '' return sys_ip @classmethod def _get_hostname(self): """Parse `hostname` and return local hostname.""" full_hn = subprocess.Popen(HOSTNAME, shell=True, stdout=subprocess.PIPE).communicate()[0] p = re.compile(r'([^\.]+)') m = p.match(full_hn) return m and m.group(0).strip() or '' @classmethod def _get_kernel_release(self): """ Call `uname -r` and return kernel release version number. """ kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True, stdout=subprocess.PIPE).communicate()[0] return kernel_rel.strip() @classmethod def _get_redhat_version(self, filename=RH_RELEASE): """ Parse `redhat-release` file and return release name and version number. """ rh_version = '' try: rh_file = open(filename, 'r') release_line = rh_file.readline() rh_file.close() p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n') m = p.match(release_line) if m: rh_version = m.group(1) except IOError: #raise Exception("Notice: Cannot open redhat-release file '%s'." % filename) print "Notice: Cannot open redhat-release file '%s'" % filename rh_version = '' return rh_version.strip() @classmethod def _ip_fwd_status(self, filename=IP_FORWARD): """ Parse `ip_forward` file and return a boolean of IP forwarding status. """ ip_fwd = 0 try: ip_file = open(filename, 'r') status_line = ip_file.readline().strip() ip_file.close() if status_line == '1': ip_fwd = 1 except IOError: #raise Exception("Notice: Cannot open ip_forward file '%s'." % filename) print "Notice: Cannot open ip_forward file '%s'" % filename pass return ip_fwd @classmethod def _nfs_status(self): """ Check and return an integer of whether a NFS is currently mounted. """ found_nfs = 0 mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True, stdout=subprocess.PIPE).communicate()[0] mount_info = mount_info.strip('\n') lines = mount_info.split('\n') for line in lines: p = re.compile(r'.+ type ([^\s].+) ') m = p.match(line) if m and m.group(1) == 'nfs': found_nfs = 1 break return found_nfs @classmethod def get_system_dict(cls): """Build and return dictionary of assets fields.""" assets_dict = {'sys_ip': cls._get_ip(), 'hostname': cls._get_hostname(), 'kernel_rel': cls._get_kernel_release(), 'rh_rel': cls._get_redhat_version(), 'nfs': cls._nfs_status(), 'ip_fwd': cls._ip_fwd_status()} return assets_dict class Services: @classmethod def get_services(cls): """ Parse `lsof -ni -P` and return a dictionary of all listening processes and ports. """ ports_dict = {} open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = open_files.split('\n') for line in lines: chunks = re.split('\s*', line) if not '(LISTEN)' in chunks: continue proc_name = chunks[0] full_name = chunks[-2] ports_dict[proc_name] = full_name.split(':')[1] return ports_dict class RPMs: @classmethod def get_rpms(cls, filename=RPM_PKGS): """Get all RPMs installed.""" rpms_dict = {'list': ''} try: rpmpkgs_file = open(filename, 'r') lines = rpmpkgs_file.readlines() rpmpkgs_file.close() lines_str = ''.join(lines) lines_str = lines_str.strip('\n') rpms_dict = {'list': lines_str} except IOError: # TODO: Logging Error. #raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename) print "Notice: Cannot open rpmpkgs file '%s'" % filename return rpms_dict class SSHConfig: @classmethod def parse(cls, filename=SSH_CONFIG_FILE): """ Parse SSH configuration file and a return a dictionary of body, parameters/values, and filename. """ body = '' items = {} filename = path(filename) try: file_obj = open(filename, 'r') lines = file_obj.readlines() file_obj.close() except IOError: #raise Exception("Notice: Cannot open SSH config file '%s'." % filename) print "Notice: Cannot open SSH config file '%s'" % filename lines = '' if lines: body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] if line[0] != '#': ls = re.split('\s*', line) if ls[0] in items: items[ls[0]] += [' %s' % ' '.join(ls[1:])] else: items[ls[0]] = [' '.join(ls[1:])] body += '%s\n' % line ssh_dict = {'body': body, 'items': items, 'filename': filename} return ssh_dict class IPTables: @classmethod def _status(self): """ Check and return an integer of whether iptables are running. """ ipt_status = 0 status_info = subprocess.Popen('%s status' % IPTABLES, shell=True, stdout=subprocess.PIPE).communicate()[0] status_info = status_info.strip('\n') if status_info != 'Firewall is stopped.': ipt_status = 1 return ipt_status @classmethod def _parse(self): """ Parse IP tables and a return a dictionary of policies for each table. """ ipt_dict = {} lines = subprocess.Popen(IPTABLES_SAVE, shell=True, stdout=subprocess.PIPE).communicate()[0] lines = lines.split('\n') table_name = '' body = '' for index, line in enumerate(lines): line = line.strip() if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \ (PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \ line.startswith('# Completed on')): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] if line[0] == ':': # Chain specification. # :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>] # Strip packet-counter and byte-counter. - ls = line.split(' ') + ls = line.split() if len(ls) > 2 and ls[0].strip(): chain_name = ls[0].strip()[1:] chain_policy = ls[1].strip() line = ':%s %s' % (chain_name, chain_policy) body += '%s\n' % line ipt_dict['body'] = body return ipt_dict @classmethod def get_ipt_dict(cls): """Build and return dictionary of iptables fields.""" ipt_dict = {'status': cls._status(), 'rules': cls._parse()} return ipt_dict class ApacheConfigList: def __init__(self): self.apache_configs = [] def recurse_apache_includes(self, fn, includes_list): for i_fn in includes_list: i_ac = ApacheConfig() i_ac.parse(i_fn) i_apache = {'body': i_ac.get_body(), 'filename': i_fn, 'directives': i_ac.get_directives(), 'domains': i_ac.get_domains(), 'included': i_ac.get_includes()} # Remove circular includes. try: del i_apache['included'][i_apache['included'].index(fn)] except ValueError: pass self.apache_configs.append(i_apache) self.recurse_apache_includes(i_fn, i_apache['included']) def recurse(self): ac = ApacheConfig() ac.parse(APACHE_CONF) apache = {'body': ac.get_body(), 'filename': APACHE_CONF, 'directives': ac.get_directives(), 'domains': ac.get_domains(), 'included': ac.get_includes()} # Remove circular includes. try: del apache['included'][apache['included'].index(APACHE_CONF)] except ValueError: pass self.apache_configs.append(apache) self.recurse_apache_includes(APACHE_CONF, apache['included']) def get_apache_configs(self): if os.path.exists(APACHE_CONF): self.recurse() return self.apache_configs class PHPConfig: def get_items(self): parameters = {} php_config = ConfigParser() try: php_config.readfp(file(path(PHP_INI))) sections = php_config.sections() except IOError: #sys.exit("Notice: Cannot open PHP configuration file '%s'" % PHP_INI) print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI sections = [] for section in sections: items = php_config.items(section) #parameters[section] = {} for item in items: #parameters[section][item[0]] = [item[1]] if item[0] in parameters: parameters[item[0]] += [item[1]] else: parameters[item[0]] = [item[1]] #parameters.setdefault(item[0], []).append(item[1]) return parameters def parse(self): try: file_obj = open(path(PHP_INI), 'r') lines = file_obj.readlines() file_obj.close() body = clean_body(lines, ';') items = self.get_items() php_dict = {'body': body, 'items': items, 'filename': PHP_INI} except IOError: #raise Exception("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)' print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI php_dict = {'body': '', 'items': [], 'filename': ''} return php_dict class MySQLConfig: def get_items(self): parameters = {} mysql_config = ConfigParser() try: mysql_config.readfp(file(path(MY_CNF))) sections = mysql_config.sections() except IOError: #sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF) print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF sections = [] for section in sections: items = mysql_config.items(section) #parameters[section] = {} for item in items: #parameters[section][item[0]] = [item[1]] if item[0] in parameters: parameters[item[0]] += [item[1]] else: parameters[item[0]] = [item[1]] #parameters.setdefault(item[0], []).append(item[1]) return parameters def parse(self): try: file_obj = open(path(MY_CNF), 'r') lines = file_obj.readlines() file_obj.close() body = clean_body(lines, '#') items = self.get_items() my_dict = {'body': body, 'items': items, 'filename': MY_CNF} except IOError: #raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)' print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF my_dict = {'body': '', 'items': [], 'filename': ''} return my_dict
cvan/secinv-client
69b8b199d273f78634e1017921d2cabc3a3473ec
clean up code
diff --git a/client/apacheparser.py b/client/apacheparser.py index 9df535a..4e808c1 100644 --- a/client/apacheparser.py +++ b/client/apacheparser.py @@ -1,279 +1,242 @@ import glob import os import re import sys from common import * class ApacheNode: re_comment = re.compile(r"""^#.*$""") re_section_start = re.compile(r"""^<(?P<name>[^/\s>]+)\s*(?P<value>[^>]+)?>$""") re_section_end = re.compile(r"""^</(?P<name>[^\s>]+)\s*>$""") #re_statement = re.compile(r"""^(?P<name>[^\s]+)\s*(?P<value>.+)?$""") def __init__(self, name, values=[], section=False): self.name = name self.children = [] self.values = values self.section = section - def add_child(self, child): self.children.append(child) child.parent = self return child - def find(self, path): """Return the first element which matches the path.""" pathelements = path.strip('/').split('/') - if pathelements[0] == '': + if not pathelements[0]: return self return self._find(pathelements) - def _find(self, pathelements): if pathelements: # There is still more to do ... next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result = child._find(pathelements) if result: return result return None else: # no pathelements left, result is self return self - def findall(self, path): """Return all elements which match the path.""" pathelements = path.strip('/').split('/') - if pathelements[0] == '': + if not pathelements[0]: return [self] return self._findall(pathelements) - def _findall(self, pathelements): if pathelements: # there is still more to do ... result = [] next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result.extend(child._findall(pathelements)) return result else: # no pathelements left, result is self return [self] - def print_r(self, indent=-1): """Recursively print node.""" if self.section: if indent >= 0: print ' ' * indent + '<' + self.name + ' ' + (' '.join(self.values)) + '>' for child in self.children: child.print_r(indent + 1) if indent >= 0: print ' ' * indent + '</' + self.name + '>' else: if indent >= 0: print ' ' * indent + self.name + ' ' + ' '.join(self.values) - @classmethod def parse_file(cls, file): """Parse a file.""" try: f = open(file) root = cls._parse(f) f.close() return root except IOError: return False - @classmethod def parse_string(cls, string): """Parse a string.""" return cls._parse(string.splitlines()) - @classmethod def _parse(cls, itobj): root = node = ApacheNode('', section=True) for line in itobj: line = line.strip() - if len(line) == 0 or cls.re_comment.match(line): + if not line or cls.re_comment.match(line): continue # Concatenate multiline directives delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), itobj.next().strip()]) m = cls.re_section_start.match(line) if m: values = m.group('value').split() new_node = ApacheNode(m.group('name'), values=values, section=True) node = node.add_child(new_node) continue m = cls.re_section_end.match(line) if m: if node.name != m.group('name'): raise Exception("Section mismatch: '%s' should be '%s'" % ( m.group('name'), node.name)) node = node.parent continue values = line.split() name = values.pop(0) # Capitalize first letter. if name[0].islower(): name = name[0].upper() + name[1:] node.add_child(ApacheNode(name, values=values, section=False)) return root class ApacheConfig: def __init__(self): self.filename = None self.ac = None self.root = None self.directives = {} self.domains = {} def parse(self, filename): self.filename = filename self.ac = ApacheNode(filename) self.root = self.ac.parse_file(filename) self.scan_children(self.root.children) def get_body(self): re_comment = re.compile(r"""^#.*$""") try: config_file = open(self.filename, 'r') config_lines = config_file.readlines() config_file.close() except IOError: return '' - ''' - body = '' - for index, line in enumerate(config_lines): - line = line.strip('\n') - line = line.replace('\t', ' ') - - #if len(line) == 0 or re_comment.match(line.strip()): - if len(line) == 0 or (not PARSE_CONF_COMMENTS and line[0] == '#'): - continue - - # Concatenate multiline directives delimited by backslash-newlines. - if line and line[-1] == '\\': - while line[-1] == '\\': - line = ' '.join([line[:-1].strip(), - config_lines[index + 1].strip()]) - del config_lines[index + 1] - - body += '%s\n' % line - ''' - return clean_body(config_lines, '#') - def print_children(self, children, indent=-1): """Recursively print children.""" indent += 1 for child in children: print '\t' * indent + (child.section and '----- ' or '') + \ child.name, ' '.join(child.values), \ child.section and '-----' or '' print_children(child.children, indent) - def scan_children(self, children, indent=-1): """Recursively scan children and build directives dictionary.""" body_list = [] for child in children: name = child.name value = ' '.join(child.values) body_list.append({'name': name, 'value': value, 'children': self.scan_children(child.children, indent)}) if name in self.directives: self.directives[name] += [value] # Check for lowercased directive. # TODO: Better check. elif name.lower() in self.directives: self.directives[name.lower()] += [value] else: self.directives[name] = [value] return body_list - def get_directives(self): return self.directives - def get_domains(self): vh = self.root.findall('VirtualHost') for v in vh: ports_str = ' '.join(v.values) # Strip all non-numeric characters. p = re.compile(r'[^0-9]+') ports_str = p.sub(' ', ports_str).strip() ports = re.split(' ', ports_str) sn = v.findall('ServerName') if sn: dn = sn[0].values[0] - - if dn in self.domains: - self.domains[dn] += ports - else: - self.domains[dn] = ports + self.domains.setdefault(dn, []).append(ports) return self.domains - def get_includes(self): included_list = [] sr_node = self.root.find('ServerRoot') if DEBUG: server_root = APACHE_ROOT else: if sr_node: server_root = ''.join(sr_node.values) # Strip quotation marks. - if server_root[0] in ('"', "'") and server_root[0] == server_root[-1]: + if server_root[0] in ('"', "'") and \ + server_root[0] == server_root[-1]: server_root = server_root[1:-1] else: server_root = APACHE_ROOT for i in self.root.findall('Include'): i = ''.join(i.values) i_fn = os.path.join(server_root, i) #print '-', i_fn # Shell-style filename expansion (e.g., `conf.d/*.conf`). included_list += glob.glob(i_fn) return included_list
cvan/secinv-client
04d86ad85b475ce9dc74c9738e50a2ed165236e3
clean up
diff --git a/client/apacheparser.py b/client/apacheparser.py index 796ddf4..4e808c1 100644 --- a/client/apacheparser.py +++ b/client/apacheparser.py @@ -1,255 +1,242 @@ import glob import os import re import sys from common import * class ApacheNode: re_comment = re.compile(r"""^#.*$""") re_section_start = re.compile(r"""^<(?P<name>[^/\s>]+)\s*(?P<value>[^>]+)?>$""") re_section_end = re.compile(r"""^</(?P<name>[^\s>]+)\s*>$""") #re_statement = re.compile(r"""^(?P<name>[^\s]+)\s*(?P<value>.+)?$""") def __init__(self, name, values=[], section=False): self.name = name self.children = [] self.values = values self.section = section - def add_child(self, child): self.children.append(child) child.parent = self return child - def find(self, path): """Return the first element which matches the path.""" pathelements = path.strip('/').split('/') - if pathelements[0] == '': + if not pathelements[0]: return self return self._find(pathelements) - def _find(self, pathelements): if pathelements: # There is still more to do ... next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result = child._find(pathelements) if result: return result return None else: # no pathelements left, result is self return self - def findall(self, path): """Return all elements which match the path.""" pathelements = path.strip('/').split('/') - if pathelements[0] == '': + if not pathelements[0]: return [self] return self._findall(pathelements) - def _findall(self, pathelements): if pathelements: # there is still more to do ... result = [] next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result.extend(child._findall(pathelements)) return result else: # no pathelements left, result is self return [self] - def print_r(self, indent=-1): """Recursively print node.""" if self.section: if indent >= 0: print ' ' * indent + '<' + self.name + ' ' + (' '.join(self.values)) + '>' for child in self.children: child.print_r(indent + 1) if indent >= 0: print ' ' * indent + '</' + self.name + '>' else: if indent >= 0: print ' ' * indent + self.name + ' ' + ' '.join(self.values) - @classmethod def parse_file(cls, file): """Parse a file.""" try: f = open(file) root = cls._parse(f) f.close() return root except IOError: return False - @classmethod def parse_string(cls, string): """Parse a string.""" return cls._parse(string.splitlines()) - @classmethod def _parse(cls, itobj): root = node = ApacheNode('', section=True) for line in itobj: line = line.strip() - if len(line) == 0 or cls.re_comment.match(line): + if not line or cls.re_comment.match(line): continue # Concatenate multiline directives delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), itobj.next().strip()]) m = cls.re_section_start.match(line) if m: values = m.group('value').split() new_node = ApacheNode(m.group('name'), values=values, section=True) node = node.add_child(new_node) continue m = cls.re_section_end.match(line) if m: if node.name != m.group('name'): raise Exception("Section mismatch: '%s' should be '%s'" % ( m.group('name'), node.name)) node = node.parent continue values = line.split() name = values.pop(0) # Capitalize first letter. if name[0].islower(): name = name[0].upper() + name[1:] node.add_child(ApacheNode(name, values=values, section=False)) return root class ApacheConfig: def __init__(self): self.filename = None self.ac = None self.root = None self.directives = {} self.domains = {} def parse(self, filename): self.filename = filename self.ac = ApacheNode(filename) self.root = self.ac.parse_file(filename) self.scan_children(self.root.children) def get_body(self): re_comment = re.compile(r"""^#.*$""") try: config_file = open(self.filename, 'r') config_lines = config_file.readlines() config_file.close() except IOError: return '' return clean_body(config_lines, '#') - def print_children(self, children, indent=-1): """Recursively print children.""" indent += 1 for child in children: print '\t' * indent + (child.section and '----- ' or '') + \ child.name, ' '.join(child.values), \ child.section and '-----' or '' print_children(child.children, indent) - def scan_children(self, children, indent=-1): """Recursively scan children and build directives dictionary.""" body_list = [] for child in children: name = child.name value = ' '.join(child.values) body_list.append({'name': name, 'value': value, 'children': self.scan_children(child.children, indent)}) if name in self.directives: self.directives[name] += [value] # Check for lowercased directive. # TODO: Better check. elif name.lower() in self.directives: self.directives[name.lower()] += [value] else: self.directives[name] = [value] return body_list - def get_directives(self): return self.directives - def get_domains(self): vh = self.root.findall('VirtualHost') for v in vh: ports_str = ' '.join(v.values) # Strip all non-numeric characters. p = re.compile(r'[^0-9]+') ports_str = p.sub(' ', ports_str).strip() ports = re.split(' ', ports_str) sn = v.findall('ServerName') if sn: dn = sn[0].values[0] self.domains.setdefault(dn, []).append(ports) return self.domains - def get_includes(self): included_list = [] sr_node = self.root.find('ServerRoot') if DEBUG: server_root = APACHE_ROOT else: if sr_node: server_root = ''.join(sr_node.values) # Strip quotation marks. - if server_root[0] in ('"', "'") and server_root[0] == server_root[-1]: + if server_root[0] in ('"', "'") and \ + server_root[0] == server_root[-1]: server_root = server_root[1:-1] else: server_root = APACHE_ROOT for i in self.root.findall('Include'): i = ''.join(i.values) i_fn = os.path.join(server_root, i) #print '-', i_fn # Shell-style filename expansion (e.g., `conf.d/*.conf`). included_list += glob.glob(i_fn) return included_list diff --git a/client/inventory.py b/client/inventory.py index 998f865..8caab7b 100644 --- a/client/inventory.py +++ b/client/inventory.py @@ -1,501 +1,461 @@ from ConfigParser import ConfigParser import os import re import subprocess import string from apacheparser import * from common import * # TODO: Use `logging`. class Interfaces: @classmethod def get_interfaces(cls): """ Return dictionary of IP address, MAC address, and netmask for each interface. """ assets_dict = {} open_files = subprocess.Popen(IFCONFIG, shell=True, stdout=subprocess.PIPE).communicate()[0] - lines = re.split('\n', open_files) + lines = open_files.split('\n') for line in lines: ls = line.split(' ') if ls[0].strip(): interface = ls[0].strip() assets_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''} # Get MAC address. if 'HWaddr' in ls: assets_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower() # Get IP address and netmask. if 'inet' in ls: inet = ls[ls.index('inet') + 1] - assets_dict[interface]['i_ip'] = re.split(':', inet)[1] - assets_dict[interface]['i_mask'] = re.split(':', ls[-1])[1] + assets_dict[interface]['i_ip'] = inet.split(':')[1] + assets_dict[interface]['i_mask'] = ls[-1].split(':')[1] return assets_dict class System: @classmethod def _get_ip(self): """Get `hostname` and return local IP address from hostname.""" try: import socket sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0] except (socket.error, socket.herror, socket.gaierror): sys_ip = '' return sys_ip @classmethod def _get_hostname(self): """Parse `hostname` and return local hostname.""" full_hn = subprocess.Popen(HOSTNAME, shell=True, stdout=subprocess.PIPE).communicate()[0] p = re.compile(r'([^\.]+)') m = p.match(full_hn) return m and m.group(0).strip() or '' @classmethod def _get_kernel_release(self): """ Call `uname -r` and return kernel release version number. """ kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True, stdout=subprocess.PIPE).communicate()[0] return kernel_rel.strip() @classmethod def _get_redhat_version(self, filename=RH_RELEASE): """ Parse `redhat-release` file and return release name and version number. """ rh_version = '' try: rh_file = open(filename, 'r') release_line = rh_file.readline() rh_file.close() p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n') m = p.match(release_line) if m: rh_version = m.group(1) except IOError: #raise Exception("Notice: Cannot open redhat-release file '%s'." % filename) print "Notice: Cannot open redhat-release file '%s'" % filename rh_version = '' return rh_version.strip() @classmethod def _ip_fwd_status(self, filename=IP_FORWARD): """ Parse `ip_forward` file and return a boolean of IP forwarding status. """ ip_fwd = 0 try: ip_file = open(filename, 'r') status_line = ip_file.readline().strip() ip_file.close() if status_line == '1': ip_fwd = 1 except IOError: #raise Exception("Notice: Cannot open ip_forward file '%s'." % filename) print "Notice: Cannot open ip_forward file '%s'" % filename pass return ip_fwd @classmethod def _nfs_status(self): """ Check and return an integer of whether a NFS is currently mounted. """ found_nfs = 0 mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True, stdout=subprocess.PIPE).communicate()[0] mount_info = mount_info.strip('\n') lines = mount_info.split('\n') for line in lines: p = re.compile(r'.+ type ([^\s].+) ') m = p.match(line) if m and m.group(1) == 'nfs': found_nfs = 1 break return found_nfs @classmethod def get_system_dict(cls): """Build and return dictionary of assets fields.""" assets_dict = {'sys_ip': cls._get_ip(), 'hostname': cls._get_hostname(), 'kernel_rel': cls._get_kernel_release(), 'rh_rel': cls._get_redhat_version(), 'nfs': cls._nfs_status(), 'ip_fwd': cls._ip_fwd_status()} return assets_dict class Services: @classmethod def get_services(cls): """ Parse `lsof -ni -P` and return a dictionary of all listening processes and ports. """ ports_dict = {} open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True, stdout=subprocess.PIPE).communicate()[0] - lines = re.split('\n', open_files) + lines = open_files.split('\n') for line in lines: chunks = re.split('\s*', line) if not '(LISTEN)' in chunks: continue proc_name = chunks[0] full_name = chunks[-2] - ports_dict[proc_name] = re.split(':', full_name)[1] + ports_dict[proc_name] = full_name.split(':')[1] return ports_dict class RPMs: @classmethod def get_rpms(cls, filename=RPM_PKGS): """Get all RPMs installed.""" rpms_dict = {'list': ''} try: rpmpkgs_file = open(filename, 'r') lines = rpmpkgs_file.readlines() rpmpkgs_file.close() lines_str = ''.join(lines) lines_str = lines_str.strip('\n') rpms_dict = {'list': lines_str} except IOError: # TODO: Logging Error. #raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename) print "Notice: Cannot open rpmpkgs file '%s'" % filename return rpms_dict -''' -class SSHConfig: - @classmethod - def parse(cls, filename=SSH_CONFIG_FILE): - """ - Parse SSH configuration file and a return a dictionary of - parameters and values. - """ - config_dict = {} - lines = '' - - try: - file_obj = open(filename, 'r') - lines = file_obj.readlines() - file_obj.close() - except IOError: - #raise Exception("Notice: Cannot open SSH config file '%s'." % filename) - print "Notice: Cannot open SSH config file '%s'" % filename - lines = '' - - for index, line in enumerate(lines): - line = line.strip() - - if len(line) == 0 or line[0] == '#': - continue - - # Concatenate multiline instructions delimited by backslash-newlines. - if line and line[-1] == '\\': - while line[-1] == '\\': - line = ' '.join([line[:-1].strip(), - lines[index + 1].strip()]) - del lines[index + 1] - - ls = re.split('\s*', line) - - if ls[0] in config_dict: - config_dict[ls[0]] += ' ' + ' '.join(ls[1:]) - else: - config_dict[ls[0]] = ' '.join(ls[1:]) - - return config_dict -''' class SSHConfig: @classmethod def parse(cls, filename=SSH_CONFIG_FILE): """ Parse SSH configuration file and a return a dictionary of body, parameters/values, and filename. """ body = '' items = {} filename = path(filename) try: file_obj = open(filename, 'r') lines = file_obj.readlines() file_obj.close() except IOError: #raise Exception("Notice: Cannot open SSH config file '%s'." % filename) print "Notice: Cannot open SSH config file '%s'" % filename lines = '' if lines: body = '' for index, line in enumerate(lines): line = line.strip() - if len(line) == 0 or (not PARSE_CONF_COMMENTS and line[0] == '#'): + if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] if line[0] != '#': ls = re.split('\s*', line) if ls[0] in items: items[ls[0]] += [' %s' % ' '.join(ls[1:])] else: items[ls[0]] = [' '.join(ls[1:])] body += '%s\n' % line ssh_dict = {'body': body, 'items': items, 'filename': filename} return ssh_dict class IPTables: @classmethod def _status(self): """ Check and return an integer of whether iptables are running. """ ipt_status = 0 status_info = subprocess.Popen('%s status' % IPTABLES, shell=True, stdout=subprocess.PIPE).communicate()[0] status_info = status_info.strip('\n') if status_info != 'Firewall is stopped.': ipt_status = 1 return ipt_status @classmethod def _parse(self): """ Parse IP tables and a return a dictionary of policies for each table. """ ipt_dict = {} lines = subprocess.Popen(IPTABLES_SAVE, shell=True, stdout=subprocess.PIPE).communicate()[0] - lines = re.split('\n', lines) + lines = lines.split('\n') table_name = '' body = '' for index, line in enumerate(lines): line = line.strip() - if len(line) == 0 or (not PARSE_CONF_COMMENTS and line[0] == '#') or \ + if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \ (PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \ line.startswith('# Completed on')): continue # Concatenate multiline instructions delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), lines[index + 1].strip()]) del lines[index + 1] if line[0] == ':': # Chain specification. # :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>] # Strip packet-counter and byte-counter. ls = line.split(' ') if len(ls) > 2 and ls[0].strip(): chain_name = ls[0].strip()[1:] chain_policy = ls[1].strip() line = ':%s %s' % (chain_name, chain_policy) body += '%s\n' % line ipt_dict['body'] = body return ipt_dict @classmethod def get_ipt_dict(cls): """Build and return dictionary of iptables fields.""" ipt_dict = {'status': cls._status(), 'rules': cls._parse()} return ipt_dict class ApacheConfigList: def __init__(self): self.apache_configs = [] def recurse_apache_includes(self, fn, includes_list): for i_fn in includes_list: i_ac = ApacheConfig() i_ac.parse(i_fn) i_apache = {'body': i_ac.get_body(), 'filename': i_fn, 'directives': i_ac.get_directives(), 'domains': i_ac.get_domains(), 'included': i_ac.get_includes()} # Remove circular includes. try: del i_apache['included'][i_apache['included'].index(fn)] except ValueError: pass self.apache_configs.append(i_apache) self.recurse_apache_includes(i_fn, i_apache['included']) def recurse(self): ac = ApacheConfig() ac.parse(APACHE_CONF) apache = {'body': ac.get_body(), 'filename': APACHE_CONF, 'directives': ac.get_directives(), 'domains': ac.get_domains(), 'included': ac.get_includes()} # Remove circular includes. try: del apache['included'][apache['included'].index(APACHE_CONF)] except ValueError: pass self.apache_configs.append(apache) self.recurse_apache_includes(APACHE_CONF, apache['included']) def get_apache_configs(self): if os.path.exists(APACHE_CONF): self.recurse() return self.apache_configs class PHPConfig: def get_items(self): parameters = {} php_config = ConfigParser() try: php_config.readfp(file(path(PHP_INI))) sections = php_config.sections() except IOError: #sys.exit("Notice: Cannot open PHP configuration file '%s'" % PHP_INI) print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI sections = [] for section in sections: items = php_config.items(section) #parameters[section] = {} for item in items: #parameters[section][item[0]] = [item[1]] if item[0] in parameters: parameters[item[0]] += [item[1]] else: parameters[item[0]] = [item[1]] + #parameters.setdefault(item[0], []).append(item[1]) return parameters def parse(self): try: file_obj = open(path(PHP_INI), 'r') lines = file_obj.readlines() file_obj.close() body = clean_body(lines, ';') items = self.get_items() php_dict = {'body': body, 'items': items, 'filename': PHP_INI} except IOError: #raise Exception("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)' print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI php_dict = {'body': '', 'items': [], 'filename': ''} return php_dict class MySQLConfig: def get_items(self): parameters = {} mysql_config = ConfigParser() try: mysql_config.readfp(file(path(MY_CNF))) sections = mysql_config.sections() except IOError: #sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF) print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF sections = [] for section in sections: items = mysql_config.items(section) #parameters[section] = {} for item in items: #parameters[section][item[0]] = [item[1]] if item[0] in parameters: parameters[item[0]] += [item[1]] else: parameters[item[0]] = [item[1]] + #parameters.setdefault(item[0], []).append(item[1]) return parameters def parse(self): try: file_obj = open(path(MY_CNF), 'r') lines = file_obj.readlines() file_obj.close() body = clean_body(lines, '#') items = self.get_items() my_dict = {'body': body, 'items': items, 'filename': MY_CNF} except IOError: #raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)' print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF my_dict = {'body': '', 'items': [], 'filename': ''} return my_dict
cvan/secinv-client
6dd8991eefefe57b36247b500fc5388f93988760
remove comments, use setdefault
diff --git a/client/apacheparser.py b/client/apacheparser.py index 9df535a..796ddf4 100644 --- a/client/apacheparser.py +++ b/client/apacheparser.py @@ -1,279 +1,255 @@ import glob import os import re import sys from common import * class ApacheNode: re_comment = re.compile(r"""^#.*$""") re_section_start = re.compile(r"""^<(?P<name>[^/\s>]+)\s*(?P<value>[^>]+)?>$""") re_section_end = re.compile(r"""^</(?P<name>[^\s>]+)\s*>$""") #re_statement = re.compile(r"""^(?P<name>[^\s]+)\s*(?P<value>.+)?$""") def __init__(self, name, values=[], section=False): self.name = name self.children = [] self.values = values self.section = section def add_child(self, child): self.children.append(child) child.parent = self return child def find(self, path): """Return the first element which matches the path.""" pathelements = path.strip('/').split('/') if pathelements[0] == '': return self return self._find(pathelements) def _find(self, pathelements): if pathelements: # There is still more to do ... next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result = child._find(pathelements) if result: return result return None else: # no pathelements left, result is self return self def findall(self, path): """Return all elements which match the path.""" pathelements = path.strip('/').split('/') if pathelements[0] == '': return [self] return self._findall(pathelements) def _findall(self, pathelements): if pathelements: # there is still more to do ... result = [] next = pathelements.pop(0) for child in self.children: # Case-insensitive comparison. if child.name.lower() == next.lower(): result.extend(child._findall(pathelements)) return result else: # no pathelements left, result is self return [self] def print_r(self, indent=-1): """Recursively print node.""" if self.section: if indent >= 0: print ' ' * indent + '<' + self.name + ' ' + (' '.join(self.values)) + '>' for child in self.children: child.print_r(indent + 1) if indent >= 0: print ' ' * indent + '</' + self.name + '>' else: if indent >= 0: print ' ' * indent + self.name + ' ' + ' '.join(self.values) @classmethod def parse_file(cls, file): """Parse a file.""" try: f = open(file) root = cls._parse(f) f.close() return root except IOError: return False @classmethod def parse_string(cls, string): """Parse a string.""" return cls._parse(string.splitlines()) @classmethod def _parse(cls, itobj): root = node = ApacheNode('', section=True) for line in itobj: line = line.strip() if len(line) == 0 or cls.re_comment.match(line): continue # Concatenate multiline directives delimited by backslash-newlines. if line and line[-1] == '\\': while line[-1] == '\\': line = ' '.join([line[:-1].strip(), itobj.next().strip()]) m = cls.re_section_start.match(line) if m: values = m.group('value').split() new_node = ApacheNode(m.group('name'), values=values, section=True) node = node.add_child(new_node) continue m = cls.re_section_end.match(line) if m: if node.name != m.group('name'): raise Exception("Section mismatch: '%s' should be '%s'" % ( m.group('name'), node.name)) node = node.parent continue values = line.split() name = values.pop(0) # Capitalize first letter. if name[0].islower(): name = name[0].upper() + name[1:] node.add_child(ApacheNode(name, values=values, section=False)) return root class ApacheConfig: def __init__(self): self.filename = None self.ac = None self.root = None self.directives = {} self.domains = {} def parse(self, filename): self.filename = filename self.ac = ApacheNode(filename) self.root = self.ac.parse_file(filename) self.scan_children(self.root.children) def get_body(self): re_comment = re.compile(r"""^#.*$""") try: config_file = open(self.filename, 'r') config_lines = config_file.readlines() config_file.close() except IOError: return '' - ''' - body = '' - for index, line in enumerate(config_lines): - line = line.strip('\n') - line = line.replace('\t', ' ') - - #if len(line) == 0 or re_comment.match(line.strip()): - if len(line) == 0 or (not PARSE_CONF_COMMENTS and line[0] == '#'): - continue - - # Concatenate multiline directives delimited by backslash-newlines. - if line and line[-1] == '\\': - while line[-1] == '\\': - line = ' '.join([line[:-1].strip(), - config_lines[index + 1].strip()]) - del config_lines[index + 1] - - body += '%s\n' % line - ''' - return clean_body(config_lines, '#') def print_children(self, children, indent=-1): """Recursively print children.""" indent += 1 for child in children: print '\t' * indent + (child.section and '----- ' or '') + \ child.name, ' '.join(child.values), \ child.section and '-----' or '' print_children(child.children, indent) def scan_children(self, children, indent=-1): """Recursively scan children and build directives dictionary.""" body_list = [] for child in children: name = child.name value = ' '.join(child.values) body_list.append({'name': name, 'value': value, 'children': self.scan_children(child.children, indent)}) if name in self.directives: self.directives[name] += [value] # Check for lowercased directive. # TODO: Better check. elif name.lower() in self.directives: self.directives[name.lower()] += [value] else: self.directives[name] = [value] return body_list def get_directives(self): return self.directives def get_domains(self): vh = self.root.findall('VirtualHost') for v in vh: ports_str = ' '.join(v.values) # Strip all non-numeric characters. p = re.compile(r'[^0-9]+') ports_str = p.sub(' ', ports_str).strip() ports = re.split(' ', ports_str) sn = v.findall('ServerName') if sn: dn = sn[0].values[0] - - if dn in self.domains: - self.domains[dn] += ports - else: - self.domains[dn] = ports + self.domains.setdefault(dn, []).append(ports) return self.domains def get_includes(self): included_list = [] sr_node = self.root.find('ServerRoot') if DEBUG: server_root = APACHE_ROOT else: if sr_node: server_root = ''.join(sr_node.values) # Strip quotation marks. if server_root[0] in ('"', "'") and server_root[0] == server_root[-1]: server_root = server_root[1:-1] else: server_root = APACHE_ROOT for i in self.root.findall('Include'): i = ''.join(i.values) i_fn = os.path.join(server_root, i) #print '-', i_fn # Shell-style filename expansion (e.g., `conf.d/*.conf`). included_list += glob.glob(i_fn) return included_list diff --git a/client/script.py b/client/script.py new file mode 100644 index 0000000..1afdaf3 --- /dev/null +++ b/client/script.py @@ -0,0 +1,14 @@ +dn = 'hey' +domains = {'hey': [5]} +ports = 10 + + +#if dn in domains: +# domains[dn] += ports +#else: +# domains[dn] = ports + +domains.setdefault(dn, []).append(ports) + +print domains +
adamalex/fast-scrolling
4036c80f9bc0b01dcfec552ebafa4eb5d785a5a4
Fixed to prevent indenting content when using swipe-to-delete - credit goes to ben's StackOverflow answer at http://stackoverflow.com/questions/742829/animating-custom-drawn-uitableviewcell-when-entering-edit-mode/1709875#1709875
diff --git a/Classes/FirstLastExampleTableViewCell.m b/Classes/FirstLastExampleTableViewCell.m index e1aadfe..412333c 100644 --- a/Classes/FirstLastExampleTableViewCell.m +++ b/Classes/FirstLastExampleTableViewCell.m @@ -1,92 +1,92 @@ // // FirstLastExampleTableViewCell.m // FastScrolling // // Created by Loren Brichter on 12/9/08. // Copyright 2008 atebits. All rights reserved. // #import "FirstLastExampleTableViewCell.h" @implementation FirstLastExampleTableViewCell @synthesize firstText; @synthesize lastText; static UIFont *firstTextFont = nil; static UIFont *lastTextFont = nil; + (void)initialize { if(self == [FirstLastExampleTableViewCell class]) { firstTextFont = [[UIFont systemFontOfSize:20] retain]; lastTextFont = [[UIFont boldSystemFontOfSize:20] retain]; // this is a good spot to load any graphics you might be drawing in -drawContentView: // just load them and retain them here (ONLY if they're small enough that you don't care about them wasting memory) // the idea is to do as LITTLE work (e.g. allocations) in -drawContentView: as possible } } - (void)dealloc { [firstText release]; [lastText release]; [super dealloc]; } // the reason I don't synthesize setters for 'firstText' and 'lastText' is because I need to // call -setNeedsDisplay when they change - (void)setFirstText:(NSString *)s { [firstText release]; firstText = [s copy]; [self setNeedsDisplay]; } - (void)setLastText:(NSString *)s { [lastText release]; lastText = [s copy]; [self setNeedsDisplay]; } - (void)layoutSubviews { CGRect b = [self bounds]; b.size.height -= 1; // leave room for the separator line b.size.width += 30; // allow extra width to slide for editing - b.origin.x -= (self.editing) ? 0 : 30; // start 30px left unless editing + b.origin.x -= (self.editing && !self.showingDeleteConfirmation) ? 0 : 30; // start 30px left unless editing [contentView setFrame:b]; [super layoutSubviews]; } - (void)drawContentView:(CGRect)r { CGContextRef context = UIGraphicsGetCurrentContext(); UIColor *backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0]; UIColor *textColor = [UIColor blackColor]; if(self.selected) { backgroundColor = [UIColor clearColor]; textColor = [UIColor whiteColor]; } [backgroundColor set]; CGContextFillRect(context, r); CGPoint p; p.x = 42; p.y = 9; [textColor set]; CGSize s = [firstText drawAtPoint:p withFont:firstTextFont]; p.x += s.width + 6; // space between words [lastText drawAtPoint:p withFont:lastTextFont]; } @end
adamalex/fast-scrolling
763b63b0f99927b5d3dcfa140f1b04fd7f5228d2
Enabled swipe-to-delete on the UITableView
diff --git a/Classes/RootViewController.m b/Classes/RootViewController.m index 5c383fd..ee9b815 100644 --- a/Classes/RootViewController.m +++ b/Classes/RootViewController.m @@ -1,64 +1,69 @@ // // RootViewController.m // FastScrolling // // Created by Loren Brichter on 12/9/08. // Copyright atebits 2008. All rights reserved. // #import "RootViewController.h" #import "FastScrollingAppDelegate.h" #import "FirstLastExampleTableViewCell.h" @implementation RootViewController - (void)viewDidLoad { self.title = @"Fast Scrolling Example"; self.navigationItem.leftBarButtonItem = self.editButtonItem; [super viewDidLoad]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 100; } static NSString *randomWords[] = { @"Hello", @"World", @"Some", @"Random", @"Words", @"Blarg", @"Poop", @"Something", @"Zoom zoom", @"Beeeep", }; #define N_RANDOM_WORDS (sizeof(randomWords)/sizeof(NSString *)) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; FirstLastExampleTableViewCell *cell = (FirstLastExampleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil) { cell = [[[FirstLastExampleTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } cell.firstText = randomWords[indexPath.row % N_RANDOM_WORDS]; cell.lastText = randomWords[(indexPath.row+1) % N_RANDOM_WORDS]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } +- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath +{ + // This method must exist to enable swipe-to-delete +} + @end
adamalex/fast-scrolling
0ed1d8a1d0a9ecfc064132e3a97ceb0f88f44a69
Revert "Configured cell to adapt to edit mode (non-animated)"
diff --git a/Classes/FirstLastExampleTableViewCell.m b/Classes/FirstLastExampleTableViewCell.m index f907a91..20f06e0 100644 --- a/Classes/FirstLastExampleTableViewCell.m +++ b/Classes/FirstLastExampleTableViewCell.m @@ -1,87 +1,82 @@ // // FirstLastExampleTableViewCell.m // FastScrolling // // Created by Loren Brichter on 12/9/08. // Copyright 2008 atebits. All rights reserved. // #import "FirstLastExampleTableViewCell.h" @implementation FirstLastExampleTableViewCell @synthesize firstText; @synthesize lastText; static UIFont *firstTextFont = nil; static UIFont *lastTextFont = nil; + (void)initialize { if(self == [FirstLastExampleTableViewCell class]) { firstTextFont = [[UIFont systemFontOfSize:20] retain]; lastTextFont = [[UIFont boldSystemFontOfSize:20] retain]; // this is a good spot to load any graphics you might be drawing in -drawContentView: // just load them and retain them here (ONLY if they're small enough that you don't care about them wasting memory) // the idea is to do as LITTLE work (e.g. allocations) in -drawContentView: as possible } } - (void)dealloc { [firstText release]; [lastText release]; [super dealloc]; } // the reason I don't synthesize setters for 'firstText' and 'lastText' is because I need to // call -setNeedsDisplay when they change - (void)setFirstText:(NSString *)s { [firstText release]; firstText = [s copy]; [self setNeedsDisplay]; } - (void)setLastText:(NSString *)s { [lastText release]; lastText = [s copy]; [self setNeedsDisplay]; } -- (void)setEditing:(BOOL)editing animated:(BOOL)animated { - [super setEditing:editing animated:animated]; - [self setNeedsDisplay]; -} - - (void)drawContentView:(CGRect)r { CGContextRef context = UIGraphicsGetCurrentContext(); UIColor *backgroundColor = [UIColor whiteColor]; UIColor *textColor = [UIColor blackColor]; if(self.selected) { backgroundColor = [UIColor clearColor]; textColor = [UIColor whiteColor]; } [backgroundColor set]; CGContextFillRect(context, r); CGPoint p; - p.x = (self.editing) ? 42 : 12; + p.x = 12; p.y = 9; [textColor set]; CGSize s = [firstText drawAtPoint:p withFont:firstTextFont]; p.x += s.width + 6; // space between words [lastText drawAtPoint:p withFont:lastTextFont]; } @end
adamalex/fast-scrolling
eb88ffd7af320cd55eda230f204251644dca4fbf
Configured cell to adapt to edit mode (non-animated)
diff --git a/Classes/FirstLastExampleTableViewCell.m b/Classes/FirstLastExampleTableViewCell.m index 20f06e0..f907a91 100644 --- a/Classes/FirstLastExampleTableViewCell.m +++ b/Classes/FirstLastExampleTableViewCell.m @@ -1,82 +1,87 @@ // // FirstLastExampleTableViewCell.m // FastScrolling // // Created by Loren Brichter on 12/9/08. // Copyright 2008 atebits. All rights reserved. // #import "FirstLastExampleTableViewCell.h" @implementation FirstLastExampleTableViewCell @synthesize firstText; @synthesize lastText; static UIFont *firstTextFont = nil; static UIFont *lastTextFont = nil; + (void)initialize { if(self == [FirstLastExampleTableViewCell class]) { firstTextFont = [[UIFont systemFontOfSize:20] retain]; lastTextFont = [[UIFont boldSystemFontOfSize:20] retain]; // this is a good spot to load any graphics you might be drawing in -drawContentView: // just load them and retain them here (ONLY if they're small enough that you don't care about them wasting memory) // the idea is to do as LITTLE work (e.g. allocations) in -drawContentView: as possible } } - (void)dealloc { [firstText release]; [lastText release]; [super dealloc]; } // the reason I don't synthesize setters for 'firstText' and 'lastText' is because I need to // call -setNeedsDisplay when they change - (void)setFirstText:(NSString *)s { [firstText release]; firstText = [s copy]; [self setNeedsDisplay]; } - (void)setLastText:(NSString *)s { [lastText release]; lastText = [s copy]; [self setNeedsDisplay]; } +- (void)setEditing:(BOOL)editing animated:(BOOL)animated { + [super setEditing:editing animated:animated]; + [self setNeedsDisplay]; +} + - (void)drawContentView:(CGRect)r { CGContextRef context = UIGraphicsGetCurrentContext(); UIColor *backgroundColor = [UIColor whiteColor]; UIColor *textColor = [UIColor blackColor]; if(self.selected) { backgroundColor = [UIColor clearColor]; textColor = [UIColor whiteColor]; } [backgroundColor set]; CGContextFillRect(context, r); CGPoint p; - p.x = 12; + p.x = (self.editing) ? 42 : 12; p.y = 9; [textColor set]; CGSize s = [firstText drawAtPoint:p withFont:firstTextFont]; p.x += s.width + 6; // space between words [lastText drawAtPoint:p withFont:lastTextFont]; } @end
adamalex/fast-scrolling
9fa66a3ecb9c98bcc3ed4bd5cf26a7b6825b5ffb
Configured UITableView to be editable
diff --git a/Classes/RootViewController.m b/Classes/RootViewController.m index daad140..5c383fd 100644 --- a/Classes/RootViewController.m +++ b/Classes/RootViewController.m @@ -1,63 +1,64 @@ // // RootViewController.m // FastScrolling // // Created by Loren Brichter on 12/9/08. // Copyright atebits 2008. All rights reserved. // #import "RootViewController.h" #import "FastScrollingAppDelegate.h" #import "FirstLastExampleTableViewCell.h" @implementation RootViewController - (void)viewDidLoad { self.title = @"Fast Scrolling Example"; + self.navigationItem.leftBarButtonItem = self.editButtonItem; [super viewDidLoad]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 100; } static NSString *randomWords[] = { @"Hello", @"World", @"Some", @"Random", @"Words", @"Blarg", @"Poop", @"Something", @"Zoom zoom", @"Beeeep", }; #define N_RANDOM_WORDS (sizeof(randomWords)/sizeof(NSString *)) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; FirstLastExampleTableViewCell *cell = (FirstLastExampleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil) { cell = [[[FirstLastExampleTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } cell.firstText = randomWords[indexPath.row % N_RANDOM_WORDS]; cell.lastText = randomWords[(indexPath.row+1) % N_RANDOM_WORDS]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } @end
adamalex/fast-scrolling
95d7ff695598a18ae2c6ada4a0de582eb4d97d2e
Added ignore file
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..07ca61d --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.pbxuser +*.mode1v3 +build/**/*
h1t/emacs-chat
ed7d296d3cc5ee924cafdc95db4051c9083722b3
used sgml mode for strip xml tags
diff --git a/pidgin-dbus.el b/pidgin-dbus.el index 48b3893..8a2f8c1 100644 --- a/pidgin-dbus.el +++ b/pidgin-dbus.el @@ -1,113 +1,105 @@ (require 'dbus) (require 'xml) ;;http://habahaba.jrudevels.org/ (defconst pidgin-icq-protocol "icq") (defconst pidgin-jabber-protocol "xmpp") (defvar pidgin-accounts nil) (defvar pidgin-all-user-list nil) (defvar pidgin-regexp-filter '(("<br>\\|<br/>" "\n") ("<a href='.*'>\\(.*\\)</a>" "\\1"))) (defun pidgin-recieve-signal (account sender text conversation flags) (let* ((protocol (car (rassoc account pidgin-accounts))) (message (pidgin-parse-message text)) (sender-name (car (rassoc (list (car (split-string sender "/"))) (pidgin-user-list protocol))))) (pidgin-chat-recieve (pidgin-protocol-user-name sender-name) (pidgin-protocol-user-name sender-name protocol) message))) (defun pidgin-parse-message (message) (message "%s" (format "from jabber: '%s'" message)) (with-temp-buffer (insert message) (mapc (lambda (regexp-info) (goto-char (point-min)) (apply 'pidgin-replace-regexp regexp-info)) pidgin-regexp-filter) - (let* ((body (xml-parse-region (point-min) (point-max))) - (xml (cddr (if (assoc 'body body) - (assoc 'body body) - (assoc 'body (car body))))) - (res "")) - (labels ((pidgin-visitor (span-list) - (cond ((stringp span-list) (setq res (concat res span-list))) - ((eq (car span-list) 'span) (pidgin-visitor (cddr span-list))) - (t (mapc 'pidgin-visitor span-list))))) - (pidgin-visitor xml)) - res))) + (sgml-mode) + (sgml-tags-invisible 0) + (buffer-string))) (defun pidgin-init () (ignore-errors (dbus-register-signal :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" "ReceivedImMsg" 'pidgin-recieve-signal)) (setq pidgin-accounts (pidgin-account-list)) (setq pidgin-all-user-list (mapcar (lambda (account-info) (list (car account-info) (pidgin-buddy-list (cdr account-info)))) pidgin-accounts))) (defun pidgin-send-message (to message) (let* ((sender (split-string to pidgin-protocol-delimeter)) (name (car sender)) (protocol (second sender))) (pidgin-dbus-send-message (cdr (assoc protocol pidgin-accounts)) (second (assoc name (pidgin-user-list protocol))) message))) (defmacro pidgin-dbus-purple-call-method (method &rest args) `(dbus-call-method :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" ,method ,@args)) (defun pidgin-account-list () (mapcar (lambda (account) (cons (downcase (pidgin-dbus-purple-call-method "PurpleAccountGetProtocolName" :int32 account)) account)) (pidgin-dbus-purple-call-method "PurpleAccountsGetAllActive"))) (defun pidgin-dbus-send-message (account recipient message) (let* ((conversation (pidgin-dbus-purple-call-method "PurpleConversationNew" :int32 1 :int32 account recipient)) (im (pidgin-dbus-purple-call-method "PurpleConvIm" :int32 conversation))) (pidgin-dbus-purple-call-method "PurpleConvImSend" :int32 im (string-as-unibyte message)))) (defun pidgin-user-list (protocol) (second (assoc protocol pidgin-all-user-list))) (defun pidgin-buddy-list (account) (mapcar (lambda (buddy) (list (pidgin-dbus-purple-call-method "PurpleBuddyGetAlias" :int32 buddy) (pidgin-dbus-purple-call-method "PurpleBuddyGetName" :int32 buddy))) (pidgin-dbus-purple-call-method "PurpleFindBuddies" :int32 account ""))) (provide 'pidgin-dbus)
h1t/emacs-chat
376dc4764358c434b50e856d04eab996eb46781c
fix for pidgin 2.5.9
diff --git a/pidgin-dbus.el b/pidgin-dbus.el index 8413fdd..48b3893 100644 --- a/pidgin-dbus.el +++ b/pidgin-dbus.el @@ -1,113 +1,113 @@ (require 'dbus) (require 'xml) ;;http://habahaba.jrudevels.org/ (defconst pidgin-icq-protocol "icq") (defconst pidgin-jabber-protocol "xmpp") (defvar pidgin-accounts nil) (defvar pidgin-all-user-list nil) (defvar pidgin-regexp-filter '(("<br>\\|<br/>" "\n") ("<a href='.*'>\\(.*\\)</a>" "\\1"))) (defun pidgin-recieve-signal (account sender text conversation flags) (let* ((protocol (car (rassoc account pidgin-accounts))) (message (pidgin-parse-message text)) (sender-name (car (rassoc (list (car (split-string sender "/"))) (pidgin-user-list protocol))))) (pidgin-chat-recieve (pidgin-protocol-user-name sender-name) (pidgin-protocol-user-name sender-name protocol) message))) (defun pidgin-parse-message (message) (message "%s" (format "from jabber: '%s'" message)) (with-temp-buffer (insert message) (mapc (lambda (regexp-info) (goto-char (point-min)) (apply 'pidgin-replace-regexp regexp-info)) pidgin-regexp-filter) (let* ((body (xml-parse-region (point-min) (point-max))) (xml (cddr (if (assoc 'body body) (assoc 'body body) (assoc 'body (car body))))) (res "")) (labels ((pidgin-visitor (span-list) (cond ((stringp span-list) (setq res (concat res span-list))) ((eq (car span-list) 'span) (pidgin-visitor (cddr span-list))) (t (mapc 'pidgin-visitor span-list))))) (pidgin-visitor xml)) res))) (defun pidgin-init () (ignore-errors (dbus-register-signal :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" "ReceivedImMsg" 'pidgin-recieve-signal)) (setq pidgin-accounts (pidgin-account-list)) (setq pidgin-all-user-list (mapcar (lambda (account-info) (list (car account-info) (pidgin-buddy-list (cdr account-info)))) pidgin-accounts))) (defun pidgin-send-message (to message) (let* ((sender (split-string to pidgin-protocol-delimeter)) (name (car sender)) (protocol (second sender))) (pidgin-dbus-send-message (cdr (assoc protocol pidgin-accounts)) (second (assoc name (pidgin-user-list protocol))) message))) (defmacro pidgin-dbus-purple-call-method (method &rest args) `(dbus-call-method :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" ,method ,@args)) (defun pidgin-account-list () (mapcar (lambda (account) (cons (downcase (pidgin-dbus-purple-call-method "PurpleAccountGetProtocolName" :int32 account)) account)) (pidgin-dbus-purple-call-method "PurpleAccountsGetAllActive"))) (defun pidgin-dbus-send-message (account recipient message) (let* ((conversation (pidgin-dbus-purple-call-method "PurpleConversationNew" - 1 :int32 account recipient)) + :int32 1 :int32 account recipient)) (im (pidgin-dbus-purple-call-method "PurpleConvIm" :int32 conversation))) (pidgin-dbus-purple-call-method "PurpleConvImSend" :int32 im (string-as-unibyte message)))) (defun pidgin-user-list (protocol) (second (assoc protocol pidgin-all-user-list))) (defun pidgin-buddy-list (account) (mapcar (lambda (buddy) (list (pidgin-dbus-purple-call-method "PurpleBuddyGetAlias" :int32 buddy) (pidgin-dbus-purple-call-method "PurpleBuddyGetName" :int32 buddy))) (pidgin-dbus-purple-call-method "PurpleFindBuddies" :int32 account ""))) (provide 'pidgin-dbus)
h1t/emacs-chat
924db34295bff05e1ccd07f4fa6fd3476d2255ef
fixed bug of displaying message like "%#test" added variable for logging directory
diff --git a/README b/README index efdf579..c61e500 100644 --- a/README +++ b/README @@ -1,21 +1,27 @@ Wrapper for pidgin instant messager ~~~~~~~~~~~~~~~~~~~~ run pidgin or finch I prefer run finch in screen: $ screen -dmS "finch" finch ~~~~~~~~~~~~~~~~~~~~ +create directory for store history (default name "~/.messenger"): +$ mkdir ~/.pigin_log_directory +~~~~~~~~~~~~~~~~~~~~ add to your .emacs file: (require 'pidgin) ;;default input method (setq pidgin-default-input-method "russian-computer") +;;set name of existing directory for store history +(setq pidgin-messenger-directory "~/.pigin_log_directory") + (pidgin-connect) ~~~~~~~~~~~~~~~~~~~~ run for chat with jabber protocol: M-x pidgin-chat-with run for chat with icq protocol: M-1 M-x pidgin-chat-with diff --git a/pidgin-chatbuffer.el b/pidgin-chatbuffer.el index ababa1a..6f4d274 100644 --- a/pidgin-chatbuffer.el +++ b/pidgin-chatbuffer.el @@ -1,174 +1,174 @@ (defgroup pidgin-chat nil "Wrapper for pidgin instant messager" :group 'applications) (defface pidgin-chat-my-message-face '((t (:foreground "salmon" :weight bold))) "face for own message" :group 'pidgin-chat) (defface pidgin-chat-foriegn-message-face '((t (:foreground "SteelBlue1" :weight bold))) "face for foriegn message" :group 'pidgin-chat) (defvar pidgin-chat-point-insert nil "Position where the message being composed starts") (defvar pidgin-chat-send-function nil "Function for sending a message from a chat buffer.") (defvar pidgin-chating-with nil) (defconst pidgin-chat-line-dilimeter "----\n") (defun pidgin-chat-mode () (kill-all-local-variables) ;; Make sure to set this variable somewhere (make-local-variable 'pidgin-chat-send-function) (make-local-variable 'scroll-conservatively) (setq scroll-conservatively 5) (make-local-variable 'pidgin-chat-point-insert) (setq pidgin-chat-point-insert (point-min)) (setq major-mode 'pidgin-chat-mode mode-name "chat") (use-local-map pidgin-chat-mode-map) (put 'pidgin-chat-mode 'mode-class 'special)) (defvar pidgin-chat-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map nil) (define-key map "\r" 'pidgin-chat-buffer-send) map)) (defun pidgin-chat-buffer-send () (interactive) (let ((body (delete-and-extract-region (+ (length pidgin-chat-line-dilimeter) pidgin-chat-point-insert) (point-max)))) (unless (zerop (length body)) (funcall pidgin-chat-send-function body)))) (defun pidgin-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) ; (if (not pidgin-chat-point-insert) ; (setq pidgin-chat-point-insert (point-max))) (let ((at-insert-point (eq (point) pidgin-chat-point-insert)) outputp) (save-excursion (goto-char pidgin-chat-point-insert) (setq outputp (pidgin-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) (setq pidgin-chat-point-insert (point)) (set-text-properties pidgin-chat-point-insert (point-max) nil)) (when at-insert-point (goto-char pidgin-chat-point-insert)) outputp)) (defun pidgin-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) (let ((inhibit-read-only t) (beg (point)) (point-insert (set-marker (make-marker) pidgin-chat-point-insert))) (set-marker-insertion-type point-insert t) (dolist (printer output-functions) (funcall printer output-data) (unless (bolp) (insert "\n"))) (unless (eq (point) beg) (let ((end (point-marker))) (unless tail (goto-char beg) (funcall prompt-function prompt-data) (goto-char end)) (put-text-property beg end 'read-only t) (put-text-property beg end 'front-sticky t) (put-text-property beg end 'rear-nonsticky t) ;;add message to history - (write-region beg end (concat "~/.messager/" pidgin-chating-with ".txt") t 'no-echo) + (write-region beg end (concat pidgin-messenger-directory pidgin-chating-with ".txt") t 'no-echo) ;; this is always non-nil, so we return that (setq pidgin-chat-point-insert (marker-position point-insert)))))) (defun pidgin-chat-send (body) - (pidgin-chat-send-message pidgin-chating-with body) + (pidgin-send-message pidgin-chating-with body) (pidgin-chat-buffer-display 'pidgin-chat-self-prompt nil '(insert) (propertize body 'face 'default) nil)) (defun pidgin-chat-recieve(name from body &optional tail) ;;(with-current-buffer (get-buffer-create "*chat-debug*") ;; (insert body)) (let* ((buf-name (pidgin-chat-get-buffer from)) (curr-buf (or (get-buffer buf-name) (pidgin-chat-create-buffer from)))) (with-current-buffer curr-buf (pidgin-chat-buffer-display 'pidgin-chat-foriegn-prompt name '(insert) (propertize body 'face 'default) tail))) (pidgin-activity-add from)) (defun pidgin-chat-self-prompt (timestamp) (insert (propertize (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") 'face 'pidgin-chat-my-message-face))) (defun pidgin-chat-foriegn-prompt (name) (insert (propertize (concat "["(format-time-string "%H:%M") "] " name "> ") 'face 'pidgin-chat-foriegn-message-face))) (defun pidgin-chat-get-buffer (chat-with) (concat "*chat:" chat-with "*")) (defun pidgin-chat-create-buffer (chat-with) (with-current-buffer (get-buffer-create (pidgin-chat-get-buffer chat-with)) (insert pidgin-chat-line-dilimeter) (if (not (eq major-mode 'pidgin-chat-mode)) (pidgin-chat-mode)) (make-local-variable 'pidgin-chating-with) (setq pidgin-chating-with chat-with) (setq pidgin-chat-send-function 'pidgin-chat-send) (make-local-variable 'pidgin-chat-earliest-backlog) (set-input-method pidgin-default-input-method) (current-buffer))) (defun pidgin-protocol-user-name (user &optional protocol) (concat (if user user "unknown") (if protocol (concat pidgin-protocol-delimeter protocol ) ""))) (defun pidgin-user-list (&optional protocol) (pidgin-buddy-list protocol)) (defun pidgin-chat-with (&optional protocol-id) (interactive (list current-prefix-arg)) (let* ((user (let ((protocol (if (and current-prefix-arg (numberp current-prefix-arg) (eq current-prefix-arg 1)) pidgin-icq-protocol pidgin-jabber-protocol))) (pidgin-protocol-user-name (funcall pidgin-completing-read "chat with: " (pidgin-user-list protocol)) protocol))) (curr-buf (or (get-buffer (pidgin-chat-get-buffer user)) (pidgin-chat-create-buffer user)))) (switch-to-buffer curr-buf))) (provide 'pidgin-chatbuffer) diff --git a/pidgin-dbus.el b/pidgin-dbus.el index 29f7261..8413fdd 100644 --- a/pidgin-dbus.el +++ b/pidgin-dbus.el @@ -1,114 +1,113 @@ (require 'dbus) (require 'xml) ;;http://habahaba.jrudevels.org/ (defconst pidgin-icq-protocol "icq") (defconst pidgin-jabber-protocol "xmpp") (defvar pidgin-accounts nil) (defvar pidgin-all-user-list nil) (defvar pidgin-regexp-filter '(("<br>\\|<br/>" "\n") ("<a href='.*'>\\(.*\\)</a>" "\\1"))) (defun pidgin-recieve-signal (account sender text conversation flags) (let* ((protocol (car (rassoc account pidgin-accounts))) (message (pidgin-parse-message text)) (sender-name (car (rassoc (list (car (split-string sender "/"))) (pidgin-user-list protocol))))) (pidgin-chat-recieve (pidgin-protocol-user-name sender-name) (pidgin-protocol-user-name sender-name protocol) message))) (defun pidgin-parse-message (message) - (message (concat "from jabber: '" message "'")) + (message "%s" (format "from jabber: '%s'" message)) (with-temp-buffer (insert message) (mapc (lambda (regexp-info) (goto-char (point-min)) (apply 'pidgin-replace-regexp regexp-info)) pidgin-regexp-filter) (let* ((body (xml-parse-region (point-min) (point-max))) (xml (cddr (if (assoc 'body body) (assoc 'body body) (assoc 'body (car body))))) - (res "")) + (res "")) (labels ((pidgin-visitor (span-list) - (cond ((stringp span-list) (setq res (concat res span-list))) - ((eq (car span-list) 'span) (pidgin-visitor (cddr span-list))) - (t (dolist (elem span-list) - (pidgin-visitor elem)))))) + (cond ((stringp span-list) (setq res (concat res span-list))) + ((eq (car span-list) 'span) (pidgin-visitor (cddr span-list))) + (t (mapc 'pidgin-visitor span-list))))) (pidgin-visitor xml)) res))) (defun pidgin-init () (ignore-errors (dbus-register-signal :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" "ReceivedImMsg" 'pidgin-recieve-signal)) (setq pidgin-accounts (pidgin-account-list)) (setq pidgin-all-user-list (mapcar (lambda (account-info) (list (car account-info) (pidgin-buddy-list (cdr account-info)))) pidgin-accounts))) (defun pidgin-send-message (to message) (let* ((sender (split-string to pidgin-protocol-delimeter)) (name (car sender)) (protocol (second sender))) - (pidgin-dbus-pidgin-send-message + (pidgin-dbus-send-message (cdr (assoc protocol pidgin-accounts)) (second (assoc name (pidgin-user-list protocol))) message))) (defmacro pidgin-dbus-purple-call-method (method &rest args) `(dbus-call-method :session "im.pidgin.purple.PurpleService" - "/im/pidgin/purple/PurpleObject" - "im.pidgin.purple.PurpleInterface" - ,method ,@args)) + "/im/pidgin/purple/PurpleObject" + "im.pidgin.purple.PurpleInterface" + ,method ,@args)) (defun pidgin-account-list () (mapcar (lambda (account) (cons (downcase (pidgin-dbus-purple-call-method "PurpleAccountGetProtocolName" :int32 account)) account)) (pidgin-dbus-purple-call-method "PurpleAccountsGetAllActive"))) -(defun pidgin-dbus-pidgin-send-message (account recipient message) +(defun pidgin-dbus-send-message (account recipient message) (let* ((conversation (pidgin-dbus-purple-call-method "PurpleConversationNew" 1 :int32 account recipient)) (im (pidgin-dbus-purple-call-method "PurpleConvIm" :int32 conversation))) - (pidgin-dbus-purple-call-method - "PurpleConvImSend" - :int32 im (string-as-unibyte message)))) + (pidgin-dbus-purple-call-method + "PurpleConvImSend" + :int32 im (string-as-unibyte message)))) (defun pidgin-user-list (protocol) (second (assoc protocol pidgin-all-user-list))) (defun pidgin-buddy-list (account) (mapcar (lambda (buddy) (list (pidgin-dbus-purple-call-method "PurpleBuddyGetAlias" :int32 buddy) (pidgin-dbus-purple-call-method "PurpleBuddyGetName" :int32 buddy))) (pidgin-dbus-purple-call-method "PurpleFindBuddies" :int32 account ""))) (provide 'pidgin-dbus) diff --git a/pidgin.el b/pidgin.el index 8de4f4c..71c9b76 100644 --- a/pidgin.el +++ b/pidgin.el @@ -1,43 +1,38 @@ (require 'cl) (require 'pidgin-chatbuffer) (require 'pidgin-dbus) (require 'pidgin-chatactivity) (defconst pidgin-protocol-delimeter "-") -(defvar pidgin-default-input-method "russian-computer") +(defvar pidgin-default-input-method default-input-method) (defvar pidgin-completing-read 'completing-read) +(defvar pidgin-messenger-directory "~/.messenger") + (defun pidgin-connect () (when (and (fboundp 'ido-completing-read) ido-mode) (setq pidgin-completing-read 'ido-completing-read))) (pidgin-init) -(defvar pidgin-chat-from nil) -(defvar pidgin-chat-to nil) -(defvar pidgin-chat-message nil) - -(defun pidgin-chat-send-message (to message) - (pidgin-send-message to message)) - (defun pidgin-replace-regexp (regexp to-string) (while (re-search-forward regexp nil t) (replace-match to-string nil nil))) (defun pidgin-string-befor-p (prefix str) (string-match (concat "^" prefix ".*") str)) (defun pidgin-string-after-p (postfix str) (string-match (concat postfix "$") str)) (defun pidgin-delete-if (fn list) (let (res) (mapc (lambda (elem) (unless (funcall fn elem) (setq res (cons elem res)))) list) (nreverse res))) (provide 'pidgin)
h1t/emacs-chat
f6cb9985868849d31f1b0a6381e0920e88370f4e
added completing-read function
diff --git a/README b/README index e7d4f52..efdf579 100644 --- a/README +++ b/README @@ -1,21 +1,21 @@ Wrapper for pidgin instant messager ~~~~~~~~~~~~~~~~~~~~ run pidgin or finch I prefer run finch in screen: $ screen -dmS "finch" finch ~~~~~~~~~~~~~~~~~~~~ add to your .emacs file: -(require 'pidgin-chatcore) +(require 'pidgin) ;;default input method (setq pidgin-default-input-method "russian-computer") -(pidgin-chat-connect) +(pidgin-connect) ~~~~~~~~~~~~~~~~~~~~ run for chat with jabber protocol: M-x pidgin-chat-with run for chat with icq protocol: M-1 M-x pidgin-chat-with diff --git a/pidgin-chatbuffer.el b/pidgin-chatbuffer.el index a019d58..ababa1a 100644 --- a/pidgin-chatbuffer.el +++ b/pidgin-chatbuffer.el @@ -1,174 +1,174 @@ (defgroup pidgin-chat nil "Wrapper for pidgin instant messager" :group 'applications) (defface pidgin-chat-my-message-face '((t (:foreground "salmon" :weight bold))) "face for own message" :group 'pidgin-chat) (defface pidgin-chat-foriegn-message-face '((t (:foreground "SteelBlue1" :weight bold))) "face for foriegn message" :group 'pidgin-chat) (defvar pidgin-chat-point-insert nil "Position where the message being composed starts") (defvar pidgin-chat-send-function nil "Function for sending a message from a chat buffer.") (defvar pidgin-chating-with nil) (defconst pidgin-chat-line-dilimeter "----\n") (defun pidgin-chat-mode () (kill-all-local-variables) ;; Make sure to set this variable somewhere (make-local-variable 'pidgin-chat-send-function) (make-local-variable 'scroll-conservatively) (setq scroll-conservatively 5) (make-local-variable 'pidgin-chat-point-insert) (setq pidgin-chat-point-insert (point-min)) (setq major-mode 'pidgin-chat-mode mode-name "chat") (use-local-map pidgin-chat-mode-map) (put 'pidgin-chat-mode 'mode-class 'special)) (defvar pidgin-chat-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map nil) (define-key map "\r" 'pidgin-chat-buffer-send) map)) (defun pidgin-chat-buffer-send () (interactive) (let ((body (delete-and-extract-region (+ (length pidgin-chat-line-dilimeter) pidgin-chat-point-insert) (point-max)))) (unless (zerop (length body)) (funcall pidgin-chat-send-function body)))) (defun pidgin-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) ; (if (not pidgin-chat-point-insert) ; (setq pidgin-chat-point-insert (point-max))) (let ((at-insert-point (eq (point) pidgin-chat-point-insert)) outputp) (save-excursion (goto-char pidgin-chat-point-insert) (setq outputp (pidgin-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) (setq pidgin-chat-point-insert (point)) (set-text-properties pidgin-chat-point-insert (point-max) nil)) (when at-insert-point (goto-char pidgin-chat-point-insert)) outputp)) (defun pidgin-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) (let ((inhibit-read-only t) (beg (point)) (point-insert (set-marker (make-marker) pidgin-chat-point-insert))) (set-marker-insertion-type point-insert t) (dolist (printer output-functions) (funcall printer output-data) (unless (bolp) (insert "\n"))) (unless (eq (point) beg) (let ((end (point-marker))) (unless tail (goto-char beg) (funcall prompt-function prompt-data) (goto-char end)) (put-text-property beg end 'read-only t) (put-text-property beg end 'front-sticky t) (put-text-property beg end 'rear-nonsticky t) ;;add message to history (write-region beg end (concat "~/.messager/" pidgin-chating-with ".txt") t 'no-echo) ;; this is always non-nil, so we return that (setq pidgin-chat-point-insert (marker-position point-insert)))))) (defun pidgin-chat-send (body) (pidgin-chat-send-message pidgin-chating-with body) (pidgin-chat-buffer-display 'pidgin-chat-self-prompt nil '(insert) (propertize body 'face 'default) nil)) (defun pidgin-chat-recieve(name from body &optional tail) ;;(with-current-buffer (get-buffer-create "*chat-debug*") ;; (insert body)) (let* ((buf-name (pidgin-chat-get-buffer from)) (curr-buf (or (get-buffer buf-name) (pidgin-chat-create-buffer from)))) (with-current-buffer curr-buf (pidgin-chat-buffer-display 'pidgin-chat-foriegn-prompt name '(insert) (propertize body 'face 'default) tail))) (pidgin-activity-add from)) (defun pidgin-chat-self-prompt (timestamp) (insert (propertize (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") 'face 'pidgin-chat-my-message-face))) (defun pidgin-chat-foriegn-prompt (name) (insert (propertize (concat "["(format-time-string "%H:%M") "] " name "> ") 'face 'pidgin-chat-foriegn-message-face))) (defun pidgin-chat-get-buffer (chat-with) (concat "*chat:" chat-with "*")) (defun pidgin-chat-create-buffer (chat-with) (with-current-buffer (get-buffer-create (pidgin-chat-get-buffer chat-with)) (insert pidgin-chat-line-dilimeter) (if (not (eq major-mode 'pidgin-chat-mode)) (pidgin-chat-mode)) (make-local-variable 'pidgin-chating-with) (setq pidgin-chating-with chat-with) (setq pidgin-chat-send-function 'pidgin-chat-send) (make-local-variable 'pidgin-chat-earliest-backlog) (set-input-method pidgin-default-input-method) (current-buffer))) (defun pidgin-protocol-user-name (user &optional protocol) (concat (if user user "unknown") (if protocol (concat pidgin-protocol-delimeter protocol ) ""))) (defun pidgin-user-list (&optional protocol) (pidgin-buddy-list protocol)) (defun pidgin-chat-with (&optional protocol-id) (interactive (list current-prefix-arg)) (let* ((user (let ((protocol (if (and current-prefix-arg (numberp current-prefix-arg) (eq current-prefix-arg 1)) pidgin-icq-protocol pidgin-jabber-protocol))) (pidgin-protocol-user-name - (ido-completing-read "chat with: " (pidgin-user-list protocol)) + (funcall pidgin-completing-read "chat with: " (pidgin-user-list protocol)) protocol))) (curr-buf (or (get-buffer (pidgin-chat-get-buffer user)) (pidgin-chat-create-buffer user)))) (switch-to-buffer curr-buf))) (provide 'pidgin-chatbuffer) diff --git a/pidgin-chatcore.el b/pidgin.el similarity index 78% rename from pidgin-chatcore.el rename to pidgin.el index aef7f9c..8de4f4c 100644 --- a/pidgin-chatcore.el +++ b/pidgin.el @@ -1,38 +1,43 @@ (require 'cl) (require 'pidgin-chatbuffer) (require 'pidgin-dbus) (require 'pidgin-chatactivity) (defconst pidgin-protocol-delimeter "-") (defvar pidgin-default-input-method "russian-computer") -(defun pidgin-chat-connect () - (pidgin-init)) +(defvar pidgin-completing-read 'completing-read) + +(defun pidgin-connect () + (when (and (fboundp 'ido-completing-read) + ido-mode) + (setq pidgin-completing-read 'ido-completing-read))) + (pidgin-init) (defvar pidgin-chat-from nil) (defvar pidgin-chat-to nil) (defvar pidgin-chat-message nil) (defun pidgin-chat-send-message (to message) (pidgin-send-message to message)) (defun pidgin-replace-regexp (regexp to-string) (while (re-search-forward regexp nil t) (replace-match to-string nil nil))) (defun pidgin-string-befor-p (prefix str) (string-match (concat "^" prefix ".*") str)) (defun pidgin-string-after-p (postfix str) (string-match (concat postfix "$") str)) (defun pidgin-delete-if (fn list) (let (res) (mapc (lambda (elem) (unless (funcall fn elem) (setq res (cons elem res)))) list) (nreverse res))) -(provide 'pidgin-chatcore) +(provide 'pidgin)
h1t/emacs-chat
42b93aaa7c7808a42aaaeb31b5d123ae2f1dcbc1
replace prefix shem to pidgin
diff --git a/README b/README index cdac261..e7d4f52 100644 --- a/README +++ b/README @@ -1,21 +1,21 @@ Wrapper for pidgin instant messager ~~~~~~~~~~~~~~~~~~~~ run pidgin or finch I prefer run finch in screen: $ screen -dmS "finch" finch ~~~~~~~~~~~~~~~~~~~~ add to your .emacs file: -(require 'shem-chatcore) +(require 'pidgin-chatcore) ;;default input method -(setq shem-default-input-method "russian-computer") +(setq pidgin-default-input-method "russian-computer") -(shem-chat-connect) +(pidgin-chat-connect) ~~~~~~~~~~~~~~~~~~~~ run for chat with jabber protocol: -M-x shem-chat-with +M-x pidgin-chat-with run for chat with icq protocol: -M-1 M-x shem-chat-with +M-1 M-x pidgin-chat-with diff --git a/pidgin-chatactivity.el b/pidgin-chatactivity.el new file mode 100644 index 0000000..a4c96b6 --- /dev/null +++ b/pidgin-chatactivity.el @@ -0,0 +1,73 @@ +(defface pidgin-chat-activity-face + '((t (:foreground "firebrick" :weight bold))) + "face for activity message" + :group 'pidgin-chat) + +(defvar pidgin-activity-mode-string "") + +(defvar pidgin-activity-list nil) + +(put 'pidgin-activity-mode-string 'risky-local-variable t) + +(defun pidgin-activity-show-p (from) + (let ((buffer (get-buffer (pidgin-chat-get-buffer from)))) + (get-buffer-window buffer 'visible))) + +(defun pidgin-activity-add (from) + (unless (pidgin-activity-show-p from) + (add-to-list 'pidgin-activity-list from) + (pidgin-activity-mode-line-update))) + +(defun pidgin-activity-clean () + (when pidgin-activity-list + (setq pidgin-activity-list + (pidgin-delete-if 'pidgin-activity-show-p pidgin-activity-list)) + (pidgin-activity-mode-line-update))) + + +(defun pidgin-activity-switch-to (user) + (interactive) + (switch-to-buffer (pidgin-chat-get-buffer user)) + (pidgin-activity-clean)) + + +(defun pidgin-activity-mode-line-update () + (setq pidgin-activity-mode-string + (if pidgin-activity-list + (concat "----" + (mapconcat + (lambda (x) + (propertize + x + 'face 'pidgin-chat-activity-face + 'local-map (make-mode-line-mouse-map + 'mouse-1 `(lambda () + (interactive) + (pidgin-activity-switch-to ,x))) + 'help-echo (concat "Jump to " x "'s buffer"))) + pidgin-activity-list ",")) + "")) + (force-mode-line-update 'all)) + + +;;;###autoload +(define-minor-mode pidgin-activity-mode + :global t + :init-value t + (if pidgin-activity-mode + (progn + (add-hook 'window-configuration-change-hook + 'pidgin-activity-clean) + (setq global-mode-string (append global-mode-string + (list '(t pidgin-activity-mode-string))))) + (progn + (remove-hook 'window-configuration-change-hook + 'pidgin-activity-clean) + (setq global-mode-string (delete '(t pidgin-activity-mode-string) + global-mode-string))))) + + +(if pidgin-activity-mode (pidgin-activity-mode 1)) + + +(provide 'pidgin-chatactivity) \ No newline at end of file diff --git a/pidgin-chatbuffer.el b/pidgin-chatbuffer.el new file mode 100644 index 0000000..a019d58 --- /dev/null +++ b/pidgin-chatbuffer.el @@ -0,0 +1,174 @@ +(defgroup pidgin-chat nil "Wrapper for pidgin instant messager" + :group 'applications) + + +(defface pidgin-chat-my-message-face + '((t (:foreground "salmon" :weight bold))) + "face for own message" + :group 'pidgin-chat) + +(defface pidgin-chat-foriegn-message-face + '((t (:foreground "SteelBlue1" :weight bold))) + "face for foriegn message" + :group 'pidgin-chat) + +(defvar pidgin-chat-point-insert nil + "Position where the message being composed starts") + +(defvar pidgin-chat-send-function nil + "Function for sending a message from a chat buffer.") + +(defvar pidgin-chating-with nil) + + +(defconst pidgin-chat-line-dilimeter "----\n") + +(defun pidgin-chat-mode () + (kill-all-local-variables) + ;; Make sure to set this variable somewhere + (make-local-variable 'pidgin-chat-send-function) + + (make-local-variable 'scroll-conservatively) + (setq scroll-conservatively 5) + + (make-local-variable 'pidgin-chat-point-insert) + (setq pidgin-chat-point-insert (point-min)) + + (setq major-mode 'pidgin-chat-mode + mode-name "chat") + (use-local-map pidgin-chat-mode-map) + + (put 'pidgin-chat-mode 'mode-class 'special)) + +(defvar pidgin-chat-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map nil) + (define-key map "\r" 'pidgin-chat-buffer-send) + map)) + +(defun pidgin-chat-buffer-send () + (interactive) + (let ((body (delete-and-extract-region + (+ (length pidgin-chat-line-dilimeter) pidgin-chat-point-insert) (point-max)))) + (unless (zerop (length body)) + (funcall pidgin-chat-send-function body)))) + +(defun pidgin-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) + ; (if (not pidgin-chat-point-insert) + ; (setq pidgin-chat-point-insert (point-max))) + (let ((at-insert-point (eq (point) pidgin-chat-point-insert)) + outputp) + (save-excursion + (goto-char pidgin-chat-point-insert) + (setq outputp + (pidgin-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) + (setq pidgin-chat-point-insert (point)) + (set-text-properties pidgin-chat-point-insert (point-max) nil)) + + (when at-insert-point + (goto-char pidgin-chat-point-insert)) + outputp)) + +(defun pidgin-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) + (let ((inhibit-read-only t) + (beg (point)) + (point-insert (set-marker (make-marker) pidgin-chat-point-insert))) + (set-marker-insertion-type point-insert t) + + (dolist (printer output-functions) + (funcall printer output-data) + (unless (bolp) + (insert "\n"))) + + (unless (eq (point) beg) + (let ((end (point-marker))) + (unless tail + (goto-char beg) + (funcall prompt-function prompt-data) + (goto-char end)) + (put-text-property beg end 'read-only t) + (put-text-property beg end 'front-sticky t) + (put-text-property beg end 'rear-nonsticky t) + + ;;add message to history + (write-region beg end (concat "~/.messager/" pidgin-chating-with ".txt") t 'no-echo) + + ;; this is always non-nil, so we return that + (setq pidgin-chat-point-insert (marker-position point-insert)))))) + + +(defun pidgin-chat-send (body) + (pidgin-chat-send-message pidgin-chating-with body) + (pidgin-chat-buffer-display 'pidgin-chat-self-prompt + nil + '(insert) + (propertize + body + 'face 'default) + nil)) + +(defun pidgin-chat-recieve(name from body &optional tail) + ;;(with-current-buffer (get-buffer-create "*chat-debug*") + ;; (insert body)) + + (let* ((buf-name (pidgin-chat-get-buffer from)) + (curr-buf (or (get-buffer buf-name) (pidgin-chat-create-buffer from)))) + (with-current-buffer curr-buf + (pidgin-chat-buffer-display 'pidgin-chat-foriegn-prompt + name + '(insert) + (propertize + body + 'face 'default) + tail))) + (pidgin-activity-add from)) + +(defun pidgin-chat-self-prompt (timestamp) + (insert (propertize + (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") + 'face 'pidgin-chat-my-message-face))) + +(defun pidgin-chat-foriegn-prompt (name) + (insert (propertize + (concat "["(format-time-string "%H:%M") "] " name "> ") + 'face 'pidgin-chat-foriegn-message-face))) + +(defun pidgin-chat-get-buffer (chat-with) + (concat "*chat:" chat-with "*")) + +(defun pidgin-chat-create-buffer (chat-with) + (with-current-buffer (get-buffer-create (pidgin-chat-get-buffer chat-with)) + (insert pidgin-chat-line-dilimeter) + (if (not (eq major-mode 'pidgin-chat-mode)) (pidgin-chat-mode)) + (make-local-variable 'pidgin-chating-with) + (setq pidgin-chating-with chat-with) + (setq pidgin-chat-send-function 'pidgin-chat-send) + (make-local-variable 'pidgin-chat-earliest-backlog) + (set-input-method pidgin-default-input-method) + (current-buffer))) + + + +(defun pidgin-protocol-user-name (user &optional protocol) + (concat (if user user "unknown") (if protocol (concat pidgin-protocol-delimeter protocol ) ""))) + +(defun pidgin-user-list (&optional protocol) + (pidgin-buddy-list protocol)) + +(defun pidgin-chat-with (&optional protocol-id) + (interactive (list current-prefix-arg)) + (let* ((user (let ((protocol (if (and current-prefix-arg + (numberp current-prefix-arg) + (eq current-prefix-arg 1)) + pidgin-icq-protocol + pidgin-jabber-protocol))) + (pidgin-protocol-user-name + (ido-completing-read "chat with: " (pidgin-user-list protocol)) + protocol))) + (curr-buf (or (get-buffer (pidgin-chat-get-buffer user)) (pidgin-chat-create-buffer user)))) + (switch-to-buffer curr-buf))) + +(provide 'pidgin-chatbuffer) + + + diff --git a/pidgin-chatcore.el b/pidgin-chatcore.el new file mode 100644 index 0000000..aef7f9c --- /dev/null +++ b/pidgin-chatcore.el @@ -0,0 +1,38 @@ +(require 'cl) +(require 'pidgin-chatbuffer) +(require 'pidgin-dbus) +(require 'pidgin-chatactivity) + +(defconst pidgin-protocol-delimeter "-") + +(defvar pidgin-default-input-method "russian-computer") + +(defun pidgin-chat-connect () + (pidgin-init)) + +(defvar pidgin-chat-from nil) +(defvar pidgin-chat-to nil) +(defvar pidgin-chat-message nil) + +(defun pidgin-chat-send-message (to message) + (pidgin-send-message to message)) + +(defun pidgin-replace-regexp (regexp to-string) + (while (re-search-forward regexp nil t) + (replace-match to-string nil nil))) + +(defun pidgin-string-befor-p (prefix str) + (string-match (concat "^" prefix ".*") str)) + +(defun pidgin-string-after-p (postfix str) + (string-match (concat postfix "$") str)) + +(defun pidgin-delete-if (fn list) + (let (res) + (mapc (lambda (elem) + (unless (funcall fn elem) + (setq res (cons elem res)))) + list) + (nreverse res))) + +(provide 'pidgin-chatcore) diff --git a/pidgin-dbus.el b/pidgin-dbus.el new file mode 100644 index 0000000..29f7261 --- /dev/null +++ b/pidgin-dbus.el @@ -0,0 +1,114 @@ +(require 'dbus) +(require 'xml) + +;;http://habahaba.jrudevels.org/ + +(defconst pidgin-icq-protocol "icq") + +(defconst pidgin-jabber-protocol "xmpp") + +(defvar pidgin-accounts nil) + +(defvar pidgin-all-user-list nil) + +(defvar pidgin-regexp-filter + '(("<br>\\|<br/>" "\n") + ("<a href='.*'>\\(.*\\)</a>" "\\1"))) + +(defun pidgin-recieve-signal (account sender text conversation flags) + (let* ((protocol (car (rassoc account pidgin-accounts))) + (message (pidgin-parse-message text)) + (sender-name (car (rassoc (list (car (split-string sender "/"))) + (pidgin-user-list protocol))))) + (pidgin-chat-recieve + (pidgin-protocol-user-name sender-name) + (pidgin-protocol-user-name sender-name protocol) + message))) + + +(defun pidgin-parse-message (message) + (message (concat "from jabber: '" message "'")) + (with-temp-buffer + (insert message) + (mapc (lambda (regexp-info) + (goto-char (point-min)) + (apply 'pidgin-replace-regexp regexp-info)) + pidgin-regexp-filter) + (let* ((body (xml-parse-region (point-min) (point-max))) + (xml (cddr (if (assoc 'body body) + (assoc 'body body) + (assoc 'body (car body))))) + (res "")) + (labels ((pidgin-visitor (span-list) + (cond ((stringp span-list) (setq res (concat res span-list))) + ((eq (car span-list) 'span) (pidgin-visitor (cddr span-list))) + (t (dolist (elem span-list) + (pidgin-visitor elem)))))) + (pidgin-visitor xml)) + res))) + +(defun pidgin-init () + (ignore-errors + (dbus-register-signal :session "im.pidgin.purple.PurpleService" + "/im/pidgin/purple/PurpleObject" + "im.pidgin.purple.PurpleInterface" + "ReceivedImMsg" + 'pidgin-recieve-signal)) + (setq pidgin-accounts (pidgin-account-list)) + (setq pidgin-all-user-list + (mapcar (lambda (account-info) + (list (car account-info) + (pidgin-buddy-list (cdr account-info)))) + pidgin-accounts))) + + + +(defun pidgin-send-message (to message) + (let* ((sender (split-string to pidgin-protocol-delimeter)) + (name (car sender)) + (protocol (second sender))) + (pidgin-dbus-pidgin-send-message + (cdr (assoc protocol pidgin-accounts)) + (second (assoc name (pidgin-user-list protocol))) + message))) + +(defmacro pidgin-dbus-purple-call-method (method &rest args) + `(dbus-call-method :session "im.pidgin.purple.PurpleService" + "/im/pidgin/purple/PurpleObject" + "im.pidgin.purple.PurpleInterface" + ,method ,@args)) + +(defun pidgin-account-list () + (mapcar (lambda (account) + (cons (downcase + (pidgin-dbus-purple-call-method + "PurpleAccountGetProtocolName" + :int32 account)) + account)) + (pidgin-dbus-purple-call-method "PurpleAccountsGetAllActive"))) + + + +(defun pidgin-dbus-pidgin-send-message (account recipient message) + (let* ((conversation (pidgin-dbus-purple-call-method + "PurpleConversationNew" + 1 :int32 account recipient)) + (im (pidgin-dbus-purple-call-method + "PurpleConvIm" + :int32 conversation))) + (pidgin-dbus-purple-call-method + "PurpleConvImSend" + :int32 im (string-as-unibyte message)))) + + +(defun pidgin-user-list (protocol) + (second (assoc protocol pidgin-all-user-list))) + +(defun pidgin-buddy-list (account) + (mapcar (lambda (buddy) + (list (pidgin-dbus-purple-call-method "PurpleBuddyGetAlias" :int32 buddy) + (pidgin-dbus-purple-call-method "PurpleBuddyGetName" :int32 buddy))) + (pidgin-dbus-purple-call-method "PurpleFindBuddies" :int32 account ""))) + +(provide 'pidgin-dbus) + diff --git a/shem-chatactivity.el b/shem-chatactivity.el deleted file mode 100644 index ec3be0e..0000000 --- a/shem-chatactivity.el +++ /dev/null @@ -1,73 +0,0 @@ -(defface shem-chat-activity-face - '((t (:foreground "firebrick" :weight bold))) - "face for activity message" - :group 'shem-chat) - -(defvar shem-activity-mode-string "") - -(defvar shem-activity-list nil) - -(put 'shem-activity-mode-string 'risky-local-variable t) - -(defun shem-activity-show-p (from) - (let ((buffer (get-buffer (shem-chat-get-buffer from)))) - (get-buffer-window buffer 'visible))) - -(defun shem-activity-add (from) - (unless (shem-activity-show-p from) - (add-to-list 'shem-activity-list from) - (shem-activity-mode-line-update))) - -(defun shem-activity-clean () - (when shem-activity-list - (setq shem-activity-list - (shem-delete-if 'shem-activity-show-p shem-activity-list)) - (shem-activity-mode-line-update))) - - -(defun shem-activity-switch-to (user) - (interactive) - (switch-to-buffer (shem-chat-get-buffer user)) - (shem-activity-clean)) - - -(defun shem-activity-mode-line-update () - (setq shem-activity-mode-string - (if shem-activity-list - (concat "----" - (mapconcat - (lambda (x) - (propertize - x - 'face 'shem-chat-activity-face - 'local-map (make-mode-line-mouse-map - 'mouse-1 `(lambda () - (interactive) - (shem-activity-switch-to ,x))) - 'help-echo (concat "Jump to " x "'s buffer"))) - shem-activity-list ",")) - "")) - (force-mode-line-update 'all)) - - -;;;###autoload -(define-minor-mode shem-activity-mode - :global t - :init-value t - (if shem-activity-mode - (progn - (add-hook 'window-configuration-change-hook - 'shem-activity-clean) - (setq global-mode-string (append global-mode-string - (list '(t shem-activity-mode-string))))) - (progn - (remove-hook 'window-configuration-change-hook - 'shem-activity-clean) - (setq global-mode-string (delete '(t shem-activity-mode-string) - global-mode-string))))) - - -(if shem-activity-mode (shem-activity-mode 1)) - - -(provide 'shem-chatactivity) \ No newline at end of file diff --git a/shem-chatbuffer.el b/shem-chatbuffer.el deleted file mode 100644 index 523eb49..0000000 --- a/shem-chatbuffer.el +++ /dev/null @@ -1,174 +0,0 @@ -(defgroup shem-chat nil "Wrapper for pidgin instant messager" - :group 'applications) - - -(defface shem-chat-my-message-face - '((t (:foreground "salmon" :weight bold))) - "face for own message" - :group 'shem-chat) - -(defface shem-chat-foriegn-message-face - '((t (:foreground "SteelBlue1" :weight bold))) - "face for foriegn message" - :group 'shem-chat) - -(defvar shem-chat-point-insert nil - "Position where the message being composed starts") - -(defvar shem-chat-send-function nil - "Function for sending a message from a chat buffer.") - -(defvar shem-chating-with nil) - - -(defconst shem-chat-line-dilimeter "----\n") - -(defun shem-chat-mode () - (kill-all-local-variables) - ;; Make sure to set this variable somewhere - (make-local-variable 'shem-chat-send-function) - - (make-local-variable 'scroll-conservatively) - (setq scroll-conservatively 5) - - (make-local-variable 'shem-chat-point-insert) - (setq shem-chat-point-insert (point-min)) - - (setq major-mode 'shem-chat-mode - mode-name "chat") - (use-local-map shem-chat-mode-map) - - (put 'shem-chat-mode 'mode-class 'special)) - -(defvar shem-chat-mode-map - (let ((map (make-sparse-keymap))) - (set-keymap-parent map nil) - (define-key map "\r" 'shem-chat-buffer-send) - map)) - -(defun shem-chat-buffer-send () - (interactive) - (let ((body (delete-and-extract-region - (+ (length shem-chat-line-dilimeter) shem-chat-point-insert) (point-max)))) - (unless (zerop (length body)) - (funcall shem-chat-send-function body)))) - -(defun shem-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) - ; (if (not shem-chat-point-insert) - ; (setq shem-chat-point-insert (point-max))) - (let ((at-insert-point (eq (point) shem-chat-point-insert)) - outputp) - (save-excursion - (goto-char shem-chat-point-insert) - (setq outputp - (shem-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) - (setq shem-chat-point-insert (point)) - (set-text-properties shem-chat-point-insert (point-max) nil)) - - (when at-insert-point - (goto-char shem-chat-point-insert)) - outputp)) - -(defun shem-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) - (let ((inhibit-read-only t) - (beg (point)) - (point-insert (set-marker (make-marker) shem-chat-point-insert))) - (set-marker-insertion-type point-insert t) - - (dolist (printer output-functions) - (funcall printer output-data) - (unless (bolp) - (insert "\n"))) - - (unless (eq (point) beg) - (let ((end (point-marker))) - (unless tail - (goto-char beg) - (funcall prompt-function prompt-data) - (goto-char end)) - (put-text-property beg end 'read-only t) - (put-text-property beg end 'front-sticky t) - (put-text-property beg end 'rear-nonsticky t) - - ;;add message to history - (write-region beg end (concat "~/.messager/" shem-chating-with ".txt") t 'no-echo) - - ;; this is always non-nil, so we return that - (setq shem-chat-point-insert (marker-position point-insert)))))) - - -(defun shem-chat-send (body) - (shem-chat-send-message shem-chating-with body) - (shem-chat-buffer-display 'shem-chat-self-prompt - nil - '(insert) - (propertize - body - 'face 'default) - nil)) - -(defun shem-chat-recieve(name from body &optional tail) - ;;(with-current-buffer (get-buffer-create "*chat-debug*") - ;; (insert body)) - - (let* ((buf-name (shem-chat-get-buffer from)) - (curr-buf (or (get-buffer buf-name) (shem-chat-create-buffer from)))) - (with-current-buffer curr-buf - (shem-chat-buffer-display 'shem-chat-foriegn-prompt - name - '(insert) - (propertize - body - 'face 'default) - tail))) - (shem-activity-add from)) - -(defun shem-chat-self-prompt (timestamp) - (insert (propertize - (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") - 'face 'shem-chat-my-message-face))) - -(defun shem-chat-foriegn-prompt (name) - (insert (propertize - (concat "["(format-time-string "%H:%M") "] " name "> ") - 'face 'shem-chat-foriegn-message-face))) - -(defun shem-chat-get-buffer (chat-with) - (concat "*chat:" chat-with "*")) - -(defun shem-chat-create-buffer (chat-with) - (with-current-buffer (get-buffer-create (shem-chat-get-buffer chat-with)) - (insert shem-chat-line-dilimeter) - (if (not (eq major-mode 'shem-chat-mode)) (shem-chat-mode)) - (make-local-variable 'shem-chating-with) - (setq shem-chating-with chat-with) - (setq shem-chat-send-function 'shem-chat-send) - (make-local-variable 'shem-chat-earliest-backlog) - (set-input-method shem-default-input-method) - (current-buffer))) - - - -(defun shem-protocol-user-name (user &optional protocol) - (concat (if user user "unknown") (if protocol (concat shem-protocol-delimeter protocol ) ""))) - -(defun shem-user-list (&optional protocol) - (shem-pidgin-buddy-list protocol)) - -(defun shem-chat-with (&optional protocol-id) - (interactive (list current-prefix-arg)) - (let* ((user (let ((protocol (if (and current-prefix-arg - (numberp current-prefix-arg) - (eq current-prefix-arg 1)) - shem-icq-protocol - shem-jabber-protocol))) - (shem-protocol-user-name - (ido-completing-read "chat with: " (shem-pidgin-user-list protocol)) - protocol))) - (curr-buf (or (get-buffer (shem-chat-get-buffer user)) (shem-chat-create-buffer user)))) - (switch-to-buffer curr-buf))) - -(provide 'shem-chatbuffer) - - - diff --git a/shem-chatcore.el b/shem-chatcore.el deleted file mode 100644 index 5ec9061..0000000 --- a/shem-chatcore.el +++ /dev/null @@ -1,38 +0,0 @@ -(require 'cl) -(require 'shem-chatbuffer) -(require 'shem-pidgin) -(require 'shem-chatactivity) - -(defconst shem-protocol-delimeter "-") - -(defvar shem-default-input-method "russian-computer") - -(defun shem-chat-connect () - (shem-pidgin-init)) - -(defvar shem-chat-from nil) -(defvar shem-chat-to nil) -(defvar shem-chat-message nil) - -(defun shem-chat-send-message (to message) - (shem-pidgin-send-message to message)) - -(defun shem-replace-regexp (regexp to-string) - (while (re-search-forward regexp nil t) - (replace-match to-string nil nil))) - -(defun shem-string-befor-p (prefix str) - (string-match (concat "^" prefix ".*") str)) - -(defun shem-string-after-p (postfix str) - (string-match (concat postfix "$") str)) - -(defun shem-delete-if (fn list) - (let (res) - (mapc (lambda (elem) - (unless (funcall fn elem) - (setq res (cons elem res)))) - list) - (nreverse res))) - -(provide 'shem-chatcore) diff --git a/shem-pidgin.el b/shem-pidgin.el deleted file mode 100644 index abab5ad..0000000 --- a/shem-pidgin.el +++ /dev/null @@ -1,114 +0,0 @@ -(require 'dbus) -(require 'xml) - -;;http://habahaba.jrudevels.org/ - -(defconst shem-icq-protocol "icq") - -(defconst shem-jabber-protocol "xmpp") - -(defvar shem-pidgin-accounts nil) - -(defvar shem-pidgin-all-user-list nil) - -(defvar shem-pidgin-regexp-filter - '(("<br>\\|<br/>" "\n") - ("<a href='.*'>\\(.*\\)</a>" "\\1"))) - -(defun shem-pidgin-recieve-signal (account sender text conversation flags) - (let* ((protocol (car (rassoc account shem-pidgin-accounts))) - (message (shem-pidgin-parse-message text)) - (sender-name (car (rassoc (list (car (split-string sender "/"))) - (shem-pidgin-user-list protocol))))) - (shem-chat-recieve - (shem-protocol-user-name sender-name) - (shem-protocol-user-name sender-name protocol) - message))) - - -(defun shem-pidgin-parse-message (message) - (message (concat "from jabber: '" message "'")) - (with-temp-buffer - (insert message) - (mapc (lambda (regexp-info) - (goto-char (point-min)) - (apply 'shem-replace-regexp regexp-info)) - shem-pidgin-regexp-filter) - (let* ((body (xml-parse-region (point-min) (point-max))) - (xml (cddr (if (assoc 'body body) - (assoc 'body body) - (assoc 'body (car body))))) - (res "")) - (labels ((shem-visitor (span-list) - (cond ((stringp span-list) (setq res (concat res span-list))) - ((eq (car span-list) 'span) (shem-visitor (cddr span-list))) - (t (dolist (elem span-list) - (shem-visitor elem)))))) - (shem-visitor xml)) - res))) - -(defun shem-pidgin-init () - (ignore-errors - (dbus-register-signal :session "im.pidgin.purple.PurpleService" - "/im/pidgin/purple/PurpleObject" - "im.pidgin.purple.PurpleInterface" - "ReceivedImMsg" - 'shem-pidgin-recieve-signal)) - (setq shem-pidgin-accounts (shem-pidgin-account-list)) - (setq shem-pidgin-all-user-list - (mapcar (lambda (account-info) - (list (car account-info) - (shem-pidgin-buddy-list (cdr account-info)))) - shem-pidgin-accounts))) - - - -(defun shem-pidgin-send-message (to message) - (let* ((sender (split-string to shem-protocol-delimeter)) - (name (car sender)) - (protocol (second sender))) - (shem-dbus-pidgin-send-message - (cdr (assoc protocol shem-pidgin-accounts)) - (second (assoc name (shem-pidgin-user-list protocol))) - message))) - -(defmacro shem-dbus-purple-call-method (method &rest args) - `(dbus-call-method :session "im.pidgin.purple.PurpleService" - "/im/pidgin/purple/PurpleObject" - "im.pidgin.purple.PurpleInterface" - ,method ,@args)) - -(defun shem-pidgin-account-list () - (mapcar (lambda (account) - (cons (downcase - (shem-dbus-purple-call-method - "PurpleAccountGetProtocolName" - :int32 account)) - account)) - (shem-dbus-purple-call-method "PurpleAccountsGetAllActive"))) - - - -(defun shem-dbus-pidgin-send-message (account recipient message) - (let* ((conversation (shem-dbus-purple-call-method - "PurpleConversationNew" - 1 :int32 account recipient)) - (im (shem-dbus-purple-call-method - "PurpleConvIm" - :int32 conversation))) - (shem-dbus-purple-call-method - "PurpleConvImSend" - :int32 im (string-as-unibyte message)))) - - -(defun shem-pidgin-user-list (protocol) - (second (assoc protocol shem-pidgin-all-user-list))) - -(defun shem-pidgin-buddy-list (account) - (mapcar (lambda (buddy) - (list (shem-dbus-purple-call-method "PurpleBuddyGetAlias" :int32 buddy) - (shem-dbus-purple-call-method "PurpleBuddyGetName" :int32 buddy))) - (shem-dbus-purple-call-method "PurpleFindBuddies" :int32 account ""))) - -(provide 'shem-pidgin) -
h1t/emacs-chat
5408094e31ce35356a49693709df9ad5f72117d4
added require of cl package
diff --git a/shem-chatcore.el b/shem-chatcore.el index 8dc4851..5ec9061 100644 --- a/shem-chatcore.el +++ b/shem-chatcore.el @@ -1,37 +1,38 @@ +(require 'cl) (require 'shem-chatbuffer) (require 'shem-pidgin) (require 'shem-chatactivity) (defconst shem-protocol-delimeter "-") (defvar shem-default-input-method "russian-computer") (defun shem-chat-connect () (shem-pidgin-init)) (defvar shem-chat-from nil) (defvar shem-chat-to nil) (defvar shem-chat-message nil) (defun shem-chat-send-message (to message) (shem-pidgin-send-message to message)) (defun shem-replace-regexp (regexp to-string) (while (re-search-forward regexp nil t) (replace-match to-string nil nil))) (defun shem-string-befor-p (prefix str) (string-match (concat "^" prefix ".*") str)) (defun shem-string-after-p (postfix str) (string-match (concat postfix "$") str)) (defun shem-delete-if (fn list) (let (res) (mapc (lambda (elem) (unless (funcall fn elem) (setq res (cons elem res)))) list) (nreverse res))) (provide 'shem-chatcore)
h1t/emacs-chat
a96a40ff5ad826e40f46bac1fb7c7b44fa01ef32
fixed documentation
diff --git a/README b/README index 45337ff..cdac261 100644 --- a/README +++ b/README @@ -1,15 +1,21 @@ +Wrapper for pidgin instant messager +~~~~~~~~~~~~~~~~~~~~ +run pidgin or finch +I prefer run finch in screen: +$ screen -dmS "finch" finch +~~~~~~~~~~~~~~~~~~~~ add to your .emacs file: (require 'shem-chatcore) ;;default input method (setq shem-default-input-method "russian-computer") (shem-chat-connect) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~ run for chat with jabber protocol: M-x shem-chat-with run for chat with icq protocol: M-1 M-x shem-chat-with diff --git a/shem-chatbuffer.el b/shem-chatbuffer.el index 3cc38c7..523eb49 100644 --- a/shem-chatbuffer.el +++ b/shem-chatbuffer.el @@ -1,174 +1,174 @@ -(defgroup shem-chat nil "Wrapper for pidgin instant messaging" +(defgroup shem-chat nil "Wrapper for pidgin instant messager" :group 'applications) (defface shem-chat-my-message-face '((t (:foreground "salmon" :weight bold))) "face for own message" :group 'shem-chat) (defface shem-chat-foriegn-message-face '((t (:foreground "SteelBlue1" :weight bold))) "face for foriegn message" :group 'shem-chat) (defvar shem-chat-point-insert nil "Position where the message being composed starts") (defvar shem-chat-send-function nil "Function for sending a message from a chat buffer.") (defvar shem-chating-with nil) (defconst shem-chat-line-dilimeter "----\n") (defun shem-chat-mode () (kill-all-local-variables) ;; Make sure to set this variable somewhere (make-local-variable 'shem-chat-send-function) (make-local-variable 'scroll-conservatively) (setq scroll-conservatively 5) (make-local-variable 'shem-chat-point-insert) (setq shem-chat-point-insert (point-min)) (setq major-mode 'shem-chat-mode mode-name "chat") (use-local-map shem-chat-mode-map) (put 'shem-chat-mode 'mode-class 'special)) (defvar shem-chat-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map nil) (define-key map "\r" 'shem-chat-buffer-send) map)) (defun shem-chat-buffer-send () (interactive) (let ((body (delete-and-extract-region (+ (length shem-chat-line-dilimeter) shem-chat-point-insert) (point-max)))) (unless (zerop (length body)) (funcall shem-chat-send-function body)))) (defun shem-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) ; (if (not shem-chat-point-insert) ; (setq shem-chat-point-insert (point-max))) (let ((at-insert-point (eq (point) shem-chat-point-insert)) outputp) (save-excursion (goto-char shem-chat-point-insert) (setq outputp (shem-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) (setq shem-chat-point-insert (point)) (set-text-properties shem-chat-point-insert (point-max) nil)) (when at-insert-point (goto-char shem-chat-point-insert)) outputp)) (defun shem-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) (let ((inhibit-read-only t) (beg (point)) (point-insert (set-marker (make-marker) shem-chat-point-insert))) (set-marker-insertion-type point-insert t) (dolist (printer output-functions) (funcall printer output-data) (unless (bolp) (insert "\n"))) (unless (eq (point) beg) (let ((end (point-marker))) (unless tail (goto-char beg) (funcall prompt-function prompt-data) (goto-char end)) (put-text-property beg end 'read-only t) (put-text-property beg end 'front-sticky t) (put-text-property beg end 'rear-nonsticky t) ;;add message to history (write-region beg end (concat "~/.messager/" shem-chating-with ".txt") t 'no-echo) ;; this is always non-nil, so we return that (setq shem-chat-point-insert (marker-position point-insert)))))) (defun shem-chat-send (body) (shem-chat-send-message shem-chating-with body) (shem-chat-buffer-display 'shem-chat-self-prompt nil '(insert) (propertize body 'face 'default) nil)) (defun shem-chat-recieve(name from body &optional tail) ;;(with-current-buffer (get-buffer-create "*chat-debug*") ;; (insert body)) (let* ((buf-name (shem-chat-get-buffer from)) (curr-buf (or (get-buffer buf-name) (shem-chat-create-buffer from)))) (with-current-buffer curr-buf (shem-chat-buffer-display 'shem-chat-foriegn-prompt name '(insert) (propertize body 'face 'default) tail))) (shem-activity-add from)) (defun shem-chat-self-prompt (timestamp) (insert (propertize (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") 'face 'shem-chat-my-message-face))) (defun shem-chat-foriegn-prompt (name) (insert (propertize (concat "["(format-time-string "%H:%M") "] " name "> ") 'face 'shem-chat-foriegn-message-face))) (defun shem-chat-get-buffer (chat-with) (concat "*chat:" chat-with "*")) (defun shem-chat-create-buffer (chat-with) (with-current-buffer (get-buffer-create (shem-chat-get-buffer chat-with)) (insert shem-chat-line-dilimeter) (if (not (eq major-mode 'shem-chat-mode)) (shem-chat-mode)) (make-local-variable 'shem-chating-with) (setq shem-chating-with chat-with) (setq shem-chat-send-function 'shem-chat-send) (make-local-variable 'shem-chat-earliest-backlog) (set-input-method shem-default-input-method) (current-buffer))) (defun shem-protocol-user-name (user &optional protocol) (concat (if user user "unknown") (if protocol (concat shem-protocol-delimeter protocol ) ""))) (defun shem-user-list (&optional protocol) (shem-pidgin-buddy-list protocol)) (defun shem-chat-with (&optional protocol-id) (interactive (list current-prefix-arg)) (let* ((user (let ((protocol (if (and current-prefix-arg (numberp current-prefix-arg) (eq current-prefix-arg 1)) shem-icq-protocol shem-jabber-protocol))) (shem-protocol-user-name (ido-completing-read "chat with: " (shem-pidgin-user-list protocol)) protocol))) (curr-buf (or (get-buffer (shem-chat-get-buffer user)) (shem-chat-create-buffer user)))) (switch-to-buffer curr-buf))) (provide 'shem-chatbuffer)
h1t/emacs-chat
b5cb52d61ca61f068c463678ae2eb2d1de878f5d
removed shem-util
diff --git a/shem-chatactivity.el b/shem-chatactivity.el index ecbee1f..ec3be0e 100644 --- a/shem-chatactivity.el +++ b/shem-chatactivity.el @@ -1,72 +1,73 @@ (defface shem-chat-activity-face '((t (:foreground "firebrick" :weight bold))) "face for activity message" :group 'shem-chat) (defvar shem-activity-mode-string "") (defvar shem-activity-list nil) (put 'shem-activity-mode-string 'risky-local-variable t) (defun shem-activity-show-p (from) (let ((buffer (get-buffer (shem-chat-get-buffer from)))) - (not (get-buffer-window buffer 'visible)))) + (get-buffer-window buffer 'visible))) (defun shem-activity-add (from) - (when (shem-activity-show-p from) + (unless (shem-activity-show-p from) (add-to-list 'shem-activity-list from) (shem-activity-mode-line-update))) (defun shem-activity-clean () - (setq shem-activity-list (delete-if-not #'shem-activity-show-p - shem-activity-list)) - (shem-activity-mode-line-update)) + (when shem-activity-list + (setq shem-activity-list + (shem-delete-if 'shem-activity-show-p shem-activity-list)) + (shem-activity-mode-line-update))) (defun shem-activity-switch-to (user) (interactive) (switch-to-buffer (shem-chat-get-buffer user)) (shem-activity-clean)) (defun shem-activity-mode-line-update () (setq shem-activity-mode-string (if shem-activity-list (concat "----" (mapconcat (lambda (x) (propertize x 'face 'shem-chat-activity-face 'local-map (make-mode-line-mouse-map 'mouse-1 `(lambda () (interactive) (shem-activity-switch-to ,x))) 'help-echo (concat "Jump to " x "'s buffer"))) shem-activity-list ",")) "")) (force-mode-line-update 'all)) ;;;###autoload (define-minor-mode shem-activity-mode :global t :init-value t (if shem-activity-mode (progn (add-hook 'window-configuration-change-hook 'shem-activity-clean) (setq global-mode-string (append global-mode-string (list '(t shem-activity-mode-string))))) (progn (remove-hook 'window-configuration-change-hook 'shem-activity-clean) (setq global-mode-string (delete '(t shem-activity-mode-string) global-mode-string))))) (if shem-activity-mode (shem-activity-mode 1)) (provide 'shem-chatactivity) \ No newline at end of file diff --git a/shem-chatbuffer.el b/shem-chatbuffer.el index 0618c55..3cc38c7 100644 --- a/shem-chatbuffer.el +++ b/shem-chatbuffer.el @@ -1,172 +1,174 @@ -(defgroup shem-chat nil "Herocraft instant messaging" +(defgroup shem-chat nil "Wrapper for pidgin instant messaging" :group 'applications) (defface shem-chat-my-message-face '((t (:foreground "salmon" :weight bold))) "face for own message" :group 'shem-chat) (defface shem-chat-foriegn-message-face '((t (:foreground "SteelBlue1" :weight bold))) "face for foriegn message" :group 'shem-chat) (defvar shem-chat-point-insert nil "Position where the message being composed starts") (defvar shem-chat-send-function nil "Function for sending a message from a chat buffer.") +(defvar shem-chating-with nil) + (defconst shem-chat-line-dilimeter "----\n") (defun shem-chat-mode () (kill-all-local-variables) ;; Make sure to set this variable somewhere (make-local-variable 'shem-chat-send-function) (make-local-variable 'scroll-conservatively) (setq scroll-conservatively 5) (make-local-variable 'shem-chat-point-insert) (setq shem-chat-point-insert (point-min)) (setq major-mode 'shem-chat-mode mode-name "chat") (use-local-map shem-chat-mode-map) (put 'shem-chat-mode 'mode-class 'special)) (defvar shem-chat-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map nil) (define-key map "\r" 'shem-chat-buffer-send) map)) (defun shem-chat-buffer-send () (interactive) (let ((body (delete-and-extract-region (+ (length shem-chat-line-dilimeter) shem-chat-point-insert) (point-max)))) (unless (zerop (length body)) (funcall shem-chat-send-function body)))) (defun shem-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) ; (if (not shem-chat-point-insert) ; (setq shem-chat-point-insert (point-max))) (let ((at-insert-point (eq (point) shem-chat-point-insert)) outputp) (save-excursion (goto-char shem-chat-point-insert) (setq outputp (shem-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) (setq shem-chat-point-insert (point)) (set-text-properties shem-chat-point-insert (point-max) nil)) (when at-insert-point (goto-char shem-chat-point-insert)) outputp)) (defun shem-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) (let ((inhibit-read-only t) (beg (point)) (point-insert (set-marker (make-marker) shem-chat-point-insert))) (set-marker-insertion-type point-insert t) (dolist (printer output-functions) (funcall printer output-data) (unless (bolp) (insert "\n"))) (unless (eq (point) beg) (let ((end (point-marker))) (unless tail (goto-char beg) (funcall prompt-function prompt-data) (goto-char end)) (put-text-property beg end 'read-only t) (put-text-property beg end 'front-sticky t) (put-text-property beg end 'rear-nonsticky t) ;;add message to history - (write-region beg end (concat "~/.messager/" shem-chatting-with ".txt") t 'no-echo) + (write-region beg end (concat "~/.messager/" shem-chating-with ".txt") t 'no-echo) ;; this is always non-nil, so we return that (setq shem-chat-point-insert (marker-position point-insert)))))) (defun shem-chat-send (body) - (shem-chat-send-message shem-chatting-with body) + (shem-chat-send-message shem-chating-with body) (shem-chat-buffer-display 'shem-chat-self-prompt nil '(insert) (propertize body 'face 'default) nil)) (defun shem-chat-recieve(name from body &optional tail) ;;(with-current-buffer (get-buffer-create "*chat-debug*") ;; (insert body)) (let* ((buf-name (shem-chat-get-buffer from)) (curr-buf (or (get-buffer buf-name) (shem-chat-create-buffer from)))) (with-current-buffer curr-buf (shem-chat-buffer-display 'shem-chat-foriegn-prompt name '(insert) (propertize body 'face 'default) tail))) (shem-activity-add from)) (defun shem-chat-self-prompt (timestamp) (insert (propertize (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") 'face 'shem-chat-my-message-face))) (defun shem-chat-foriegn-prompt (name) (insert (propertize (concat "["(format-time-string "%H:%M") "] " name "> ") 'face 'shem-chat-foriegn-message-face))) (defun shem-chat-get-buffer (chat-with) (concat "*chat:" chat-with "*")) (defun shem-chat-create-buffer (chat-with) (with-current-buffer (get-buffer-create (shem-chat-get-buffer chat-with)) (insert shem-chat-line-dilimeter) (if (not (eq major-mode 'shem-chat-mode)) (shem-chat-mode)) - (make-local-variable 'shem-chatting-with) - (setq shem-chatting-with chat-with) + (make-local-variable 'shem-chating-with) + (setq shem-chating-with chat-with) (setq shem-chat-send-function 'shem-chat-send) (make-local-variable 'shem-chat-earliest-backlog) (set-input-method shem-default-input-method) (current-buffer))) (defun shem-protocol-user-name (user &optional protocol) (concat (if user user "unknown") (if protocol (concat shem-protocol-delimeter protocol ) ""))) (defun shem-user-list (&optional protocol) (shem-pidgin-buddy-list protocol)) (defun shem-chat-with (&optional protocol-id) (interactive (list current-prefix-arg)) (let* ((user (let ((protocol (if (and current-prefix-arg (numberp current-prefix-arg) (eq current-prefix-arg 1)) shem-icq-protocol shem-jabber-protocol))) (shem-protocol-user-name (ido-completing-read "chat with: " (shem-pidgin-user-list protocol)) protocol))) (curr-buf (or (get-buffer (shem-chat-get-buffer user)) (shem-chat-create-buffer user)))) (switch-to-buffer curr-buf))) (provide 'shem-chatbuffer) diff --git a/shem-chatcore.el b/shem-chatcore.el index ef4ed90..8dc4851 100644 --- a/shem-chatcore.el +++ b/shem-chatcore.el @@ -1,21 +1,37 @@ -(require 'cl) (require 'shem-chatbuffer) (require 'shem-pidgin) (require 'shem-chatactivity) -(require 'shem-util) (defconst shem-protocol-delimeter "-") (defvar shem-default-input-method "russian-computer") (defun shem-chat-connect () (shem-pidgin-init)) (defvar shem-chat-from nil) (defvar shem-chat-to nil) (defvar shem-chat-message nil) (defun shem-chat-send-message (to message) (shem-pidgin-send-message to message)) + +(defun shem-replace-regexp (regexp to-string) + (while (re-search-forward regexp nil t) + (replace-match to-string nil nil))) + +(defun shem-string-befor-p (prefix str) + (string-match (concat "^" prefix ".*") str)) + +(defun shem-string-after-p (postfix str) + (string-match (concat postfix "$") str)) + +(defun shem-delete-if (fn list) + (let (res) + (mapc (lambda (elem) + (unless (funcall fn elem) + (setq res (cons elem res)))) + list) + (nreverse res))) (provide 'shem-chatcore) diff --git a/shem-pidgin.el b/shem-pidgin.el index a032ec6..abab5ad 100644 --- a/shem-pidgin.el +++ b/shem-pidgin.el @@ -1,115 +1,114 @@ (require 'dbus) (require 'xml) ;;http://habahaba.jrudevels.org/ (defconst shem-icq-protocol "icq") (defconst shem-jabber-protocol "xmpp") (defvar shem-pidgin-accounts nil) (defvar shem-pidgin-all-user-list nil) (defvar shem-pidgin-regexp-filter '(("<br>\\|<br/>" "\n") ("<a href='.*'>\\(.*\\)</a>" "\\1"))) (defun shem-pidgin-recieve-signal (account sender text conversation flags) (let* ((protocol (car (rassoc account shem-pidgin-accounts))) (message (shem-pidgin-parse-message text)) - (sender-name (car (rassoc (list (car (split-string sender "/"))) (shem-pidgin-user-list protocol))))) + (sender-name (car (rassoc (list (car (split-string sender "/"))) + (shem-pidgin-user-list protocol))))) (shem-chat-recieve (shem-protocol-user-name sender-name) (shem-protocol-user-name sender-name protocol) message))) (defun shem-pidgin-parse-message (message) (message (concat "from jabber: '" message "'")) (with-temp-buffer (insert message) (mapc (lambda (regexp-info) (goto-char (point-min)) (apply 'shem-replace-regexp regexp-info)) shem-pidgin-regexp-filter) (let* ((body (xml-parse-region (point-min) (point-max))) (xml (cddr (if (assoc 'body body) (assoc 'body body) (assoc 'body (car body))))) (res "")) (labels ((shem-visitor (span-list) (cond ((stringp span-list) (setq res (concat res span-list))) ((eq (car span-list) 'span) (shem-visitor (cddr span-list))) (t (dolist (elem span-list) (shem-visitor elem)))))) (shem-visitor xml)) res))) (defun shem-pidgin-init () (ignore-errors - ;; (shem-dbus-purple-call-method "ReceivedImMsg" - ;; 'shem-pidgin-recieve-signal) (dbus-register-signal :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" "ReceivedImMsg" 'shem-pidgin-recieve-signal)) (setq shem-pidgin-accounts (shem-pidgin-account-list)) (setq shem-pidgin-all-user-list (mapcar (lambda (account-info) (list (car account-info) (shem-pidgin-buddy-list (cdr account-info)))) shem-pidgin-accounts))) (defun shem-pidgin-send-message (to message) (let* ((sender (split-string to shem-protocol-delimeter)) (name (car sender)) (protocol (second sender))) (shem-dbus-pidgin-send-message (cdr (assoc protocol shem-pidgin-accounts)) (second (assoc name (shem-pidgin-user-list protocol))) message))) (defmacro shem-dbus-purple-call-method (method &rest args) `(dbus-call-method :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" ,method ,@args)) (defun shem-pidgin-account-list () (mapcar (lambda (account) (cons (downcase (shem-dbus-purple-call-method "PurpleAccountGetProtocolName" :int32 account)) account)) (shem-dbus-purple-call-method "PurpleAccountsGetAllActive"))) (defun shem-dbus-pidgin-send-message (account recipient message) (let* ((conversation (shem-dbus-purple-call-method "PurpleConversationNew" 1 :int32 account recipient)) (im (shem-dbus-purple-call-method "PurpleConvIm" :int32 conversation))) (shem-dbus-purple-call-method "PurpleConvImSend" :int32 im (string-as-unibyte message)))) (defun shem-pidgin-user-list (protocol) (second (assoc protocol shem-pidgin-all-user-list))) (defun shem-pidgin-buddy-list (account) (mapcar (lambda (buddy) (list (shem-dbus-purple-call-method "PurpleBuddyGetAlias" :int32 buddy) (shem-dbus-purple-call-method "PurpleBuddyGetName" :int32 buddy))) - (shem-dbus-purple-call-method "PurpleFindBuddies" :int32 account ""))) + (shem-dbus-purple-call-method "PurpleFindBuddies" :int32 account ""))) (provide 'shem-pidgin) diff --git a/shem-util.el b/shem-util.el deleted file mode 100644 index fb9345c..0000000 --- a/shem-util.el +++ /dev/null @@ -1,11 +0,0 @@ -(defun shem-replace-regexp (regexp to-string) - (while (re-search-forward regexp nil t) - (replace-match to-string nil nil))) - -(defun shem-string-befor-p (prefix str) - (string-match (concat "^" prefix ".*") str)) - -(defun shem-string-after-p (postfix str) - (string-match (concat postfix "$") str)) - -(provide 'shem-util)
h1t/emacs-chat
0f21fd6d343d1f021b8af8852c64534426bb7fbf
added autodetecting of buddy list
diff --git a/README b/README index 47b395d..45337ff 100644 --- a/README +++ b/README @@ -1,23 +1,15 @@ add to your .emacs file: (require 'shem-chatcore) -;; jabber user list -(setq shem-jabber-name-list - (list '("testJabberBuddy1" "[email protected]") - '("testJabberBuddy2" "[email protected]"))) -;; icq user list -(setq shem-icq-name-list - (list '("testICQBuddy1" "777777") - '("testICQBuddy2" "777777"))) ;;default input method (setq shem-default-input-method "russian-computer") (shem-chat-connect) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ run for chat with jabber protocol: M-x shem-chat-with run for chat with icq protocol: M-1 M-x shem-chat-with diff --git a/shem-chatbuffer.el b/shem-chatbuffer.el index 08aeb14..0618c55 100644 --- a/shem-chatbuffer.el +++ b/shem-chatbuffer.el @@ -1,172 +1,172 @@ (defgroup shem-chat nil "Herocraft instant messaging" :group 'applications) (defface shem-chat-my-message-face '((t (:foreground "salmon" :weight bold))) "face for own message" :group 'shem-chat) (defface shem-chat-foriegn-message-face '((t (:foreground "SteelBlue1" :weight bold))) "face for foriegn message" :group 'shem-chat) (defvar shem-chat-point-insert nil "Position where the message being composed starts") (defvar shem-chat-send-function nil "Function for sending a message from a chat buffer.") (defconst shem-chat-line-dilimeter "----\n") (defun shem-chat-mode () (kill-all-local-variables) ;; Make sure to set this variable somewhere (make-local-variable 'shem-chat-send-function) (make-local-variable 'scroll-conservatively) (setq scroll-conservatively 5) (make-local-variable 'shem-chat-point-insert) (setq shem-chat-point-insert (point-min)) (setq major-mode 'shem-chat-mode mode-name "chat") (use-local-map shem-chat-mode-map) (put 'shem-chat-mode 'mode-class 'special)) (defvar shem-chat-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map nil) (define-key map "\r" 'shem-chat-buffer-send) map)) (defun shem-chat-buffer-send () (interactive) (let ((body (delete-and-extract-region (+ (length shem-chat-line-dilimeter) shem-chat-point-insert) (point-max)))) (unless (zerop (length body)) (funcall shem-chat-send-function body)))) (defun shem-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) ; (if (not shem-chat-point-insert) ; (setq shem-chat-point-insert (point-max))) (let ((at-insert-point (eq (point) shem-chat-point-insert)) outputp) (save-excursion (goto-char shem-chat-point-insert) (setq outputp (shem-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) (setq shem-chat-point-insert (point)) (set-text-properties shem-chat-point-insert (point-max) nil)) (when at-insert-point (goto-char shem-chat-point-insert)) outputp)) (defun shem-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) (let ((inhibit-read-only t) (beg (point)) (point-insert (set-marker (make-marker) shem-chat-point-insert))) (set-marker-insertion-type point-insert t) (dolist (printer output-functions) (funcall printer output-data) (unless (bolp) (insert "\n"))) (unless (eq (point) beg) (let ((end (point-marker))) (unless tail (goto-char beg) (funcall prompt-function prompt-data) (goto-char end)) (put-text-property beg end 'read-only t) (put-text-property beg end 'front-sticky t) (put-text-property beg end 'rear-nonsticky t) ;;add message to history (write-region beg end (concat "~/.messager/" shem-chatting-with ".txt") t 'no-echo) ;; this is always non-nil, so we return that (setq shem-chat-point-insert (marker-position point-insert)))))) (defun shem-chat-send (body) (shem-chat-send-message shem-chatting-with body) (shem-chat-buffer-display 'shem-chat-self-prompt nil '(insert) (propertize body 'face 'default) nil)) (defun shem-chat-recieve(name from body &optional tail) ;;(with-current-buffer (get-buffer-create "*chat-debug*") ;; (insert body)) (let* ((buf-name (shem-chat-get-buffer from)) (curr-buf (or (get-buffer buf-name) (shem-chat-create-buffer from)))) (with-current-buffer curr-buf (shem-chat-buffer-display 'shem-chat-foriegn-prompt name '(insert) (propertize body 'face 'default) tail))) (shem-activity-add from)) (defun shem-chat-self-prompt (timestamp) (insert (propertize (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") 'face 'shem-chat-my-message-face))) (defun shem-chat-foriegn-prompt (name) (insert (propertize (concat "["(format-time-string "%H:%M") "] " name "> ") 'face 'shem-chat-foriegn-message-face))) (defun shem-chat-get-buffer (chat-with) (concat "*chat:" chat-with "*")) (defun shem-chat-create-buffer (chat-with) (with-current-buffer (get-buffer-create (shem-chat-get-buffer chat-with)) (insert shem-chat-line-dilimeter) (if (not (eq major-mode 'shem-chat-mode)) (shem-chat-mode)) (make-local-variable 'shem-chatting-with) (setq shem-chatting-with chat-with) (setq shem-chat-send-function 'shem-chat-send) (make-local-variable 'shem-chat-earliest-backlog) (set-input-method shem-default-input-method) (current-buffer))) (defun shem-protocol-user-name (user &optional protocol) (concat (if user user "unknown") (if protocol (concat shem-protocol-delimeter protocol ) ""))) (defun shem-user-list (&optional protocol) (shem-pidgin-buddy-list protocol)) (defun shem-chat-with (&optional protocol-id) (interactive (list current-prefix-arg)) (let* ((user (let ((protocol (if (and current-prefix-arg (numberp current-prefix-arg) (eq current-prefix-arg 1)) shem-icq-protocol shem-jabber-protocol))) (shem-protocol-user-name - (ido-completing-read "chat with: " (shem-user-list protocol)) + (ido-completing-read "chat with: " (shem-pidgin-user-list protocol)) protocol))) (curr-buf (or (get-buffer (shem-chat-get-buffer user)) (shem-chat-create-buffer user)))) (switch-to-buffer curr-buf))) (provide 'shem-chatbuffer) diff --git a/shem-pidgin.el b/shem-pidgin.el index e7e48e4..a032ec6 100644 --- a/shem-pidgin.el +++ b/shem-pidgin.el @@ -1,119 +1,115 @@ (require 'dbus) (require 'xml) ;;http://habahaba.jrudevels.org/ (defconst shem-icq-protocol "icq") (defconst shem-jabber-protocol "xmpp") (defvar shem-pidgin-accounts nil) -(defvar shem-icq-name-list nil) - -(defvar shem-jabber-name-list nil) +(defvar shem-pidgin-all-user-list nil) (defvar shem-pidgin-regexp-filter '(("<br>\\|<br/>" "\n") ("<a href='.*'>\\(.*\\)</a>" "\\1"))) (defun shem-pidgin-recieve-signal (account sender text conversation flags) - (let* ((protocol (cdr (assoc account shem-pidgin-accounts))) - (message (if (string-equal protocol shem-jabber-protocol) - (shem-pidgin-parse-jabber-message text) - text))) + (let* ((protocol (car (rassoc account shem-pidgin-accounts))) + (message (shem-pidgin-parse-message text)) + (sender-name (car (rassoc (list (car (split-string sender "/"))) (shem-pidgin-user-list protocol))))) (shem-chat-recieve - (shem-pidgin-sender-name protocol sender t) - (shem-pidgin-sender-name protocol sender) message))) - - -(defun shem-pidgin-sender-name (protocol sender-id &optional only-name) - (shem-protocol-user-name - (car (find sender-id - (shem-pidgin-buddy-list protocol) - :key #'second - :test (if (string-equal protocol shem-jabber-protocol) - #'shem-pidgin-jabber-user-compare - #'string-equal))) - (unless only-name protocol))) - -(defun shem-pidgin-jabber-user-compare (user1 user2) - (string-equal (car (split-string user1 "/")) - (car (split-string user2 "/")))) + (shem-protocol-user-name sender-name) + (shem-protocol-user-name sender-name protocol) + message))) -(defun shem-pidgin-parse-jabber-message (message) +(defun shem-pidgin-parse-message (message) (message (concat "from jabber: '" message "'")) (with-temp-buffer (insert message) (mapc (lambda (regexp-info) (goto-char (point-min)) - (shem-replace-regexp (car regexp-info) (cadr regexp-info))) + (apply 'shem-replace-regexp regexp-info)) shem-pidgin-regexp-filter) (let* ((body (xml-parse-region (point-min) (point-max))) (xml (cddr (if (assoc 'body body) (assoc 'body body) (assoc 'body (car body))))) (res "")) (labels ((shem-visitor (span-list) (cond ((stringp span-list) (setq res (concat res span-list))) ((eq (car span-list) 'span) (shem-visitor (cddr span-list))) (t (dolist (elem span-list) (shem-visitor elem)))))) (shem-visitor xml)) res))) (defun shem-pidgin-init () (ignore-errors + ;; (shem-dbus-purple-call-method "ReceivedImMsg" + ;; 'shem-pidgin-recieve-signal) (dbus-register-signal :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" "ReceivedImMsg" 'shem-pidgin-recieve-signal)) - (setq shem-pidgin-accounts (get-account-list))) + (setq shem-pidgin-accounts (shem-pidgin-account-list)) + (setq shem-pidgin-all-user-list + (mapcar (lambda (account-info) + (list (car account-info) + (shem-pidgin-buddy-list (cdr account-info)))) + shem-pidgin-accounts))) + (defun shem-pidgin-send-message (to message) - (let ((sender (split-string to shem-protocol-delimeter))) + (let* ((sender (split-string to shem-protocol-delimeter)) + (name (car sender)) + (protocol (second sender))) (shem-dbus-pidgin-send-message - (car (find (second sender) shem-pidgin-accounts :test #'string-equal :key #'cdr)) - (second (assoc (car sender) (shem-pidgin-buddy-list (second sender)))) + (cdr (assoc protocol shem-pidgin-accounts)) + (second (assoc name (shem-pidgin-user-list protocol))) message))) (defmacro shem-dbus-purple-call-method (method &rest args) `(dbus-call-method :session "im.pidgin.purple.PurpleService" "/im/pidgin/purple/PurpleObject" "im.pidgin.purple.PurpleInterface" ,method ,@args)) -(defun get-account-list () +(defun shem-pidgin-account-list () (mapcar (lambda (account) - (cons account (downcase - (shem-dbus-purple-call-method - "PurpleAccountGetProtocolName" - :int32 account)))) + (cons (downcase + (shem-dbus-purple-call-method + "PurpleAccountGetProtocolName" + :int32 account)) + account)) (shem-dbus-purple-call-method "PurpleAccountsGetAllActive"))) (defun shem-dbus-pidgin-send-message (account recipient message) - ;; (message (number-to-string account)) - ;; (message (number-to-string recipient)) - ;;(message message) (let* ((conversation (shem-dbus-purple-call-method "PurpleConversationNew" 1 :int32 account recipient)) (im (shem-dbus-purple-call-method "PurpleConvIm" :int32 conversation))) (shem-dbus-purple-call-method "PurpleConvImSend" :int32 im (string-as-unibyte message)))) -(defun shem-pidgin-buddy-list (protocol) - (if (string-equal protocol shem-icq-protocol) - shem-icq-name-list - shem-jabber-name-list)) +(defun shem-pidgin-user-list (protocol) + (second (assoc protocol shem-pidgin-all-user-list))) + +(defun shem-pidgin-buddy-list (account) + (mapcar (lambda (buddy) + (list (shem-dbus-purple-call-method "PurpleBuddyGetAlias" :int32 buddy) + (shem-dbus-purple-call-method "PurpleBuddyGetName" :int32 buddy))) + (shem-dbus-purple-call-method "PurpleFindBuddies" :int32 account ""))) + +(provide 'shem-pidgin) -(provide 'shem-pidgin) \ No newline at end of file
h1t/emacs-chat
6ac8986cc32e845822e9c2fa8219c30a8ea2532d
added ido-completing-read instead of completing-read
diff --git a/shem-chatbuffer.el b/shem-chatbuffer.el index f026de3..08aeb14 100644 --- a/shem-chatbuffer.el +++ b/shem-chatbuffer.el @@ -1,172 +1,172 @@ (defgroup shem-chat nil "Herocraft instant messaging" :group 'applications) (defface shem-chat-my-message-face '((t (:foreground "salmon" :weight bold))) "face for own message" :group 'shem-chat) (defface shem-chat-foriegn-message-face '((t (:foreground "SteelBlue1" :weight bold))) "face for foriegn message" :group 'shem-chat) (defvar shem-chat-point-insert nil "Position where the message being composed starts") (defvar shem-chat-send-function nil "Function for sending a message from a chat buffer.") (defconst shem-chat-line-dilimeter "----\n") (defun shem-chat-mode () (kill-all-local-variables) ;; Make sure to set this variable somewhere (make-local-variable 'shem-chat-send-function) (make-local-variable 'scroll-conservatively) (setq scroll-conservatively 5) (make-local-variable 'shem-chat-point-insert) (setq shem-chat-point-insert (point-min)) (setq major-mode 'shem-chat-mode mode-name "chat") (use-local-map shem-chat-mode-map) (put 'shem-chat-mode 'mode-class 'special)) (defvar shem-chat-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map nil) (define-key map "\r" 'shem-chat-buffer-send) map)) (defun shem-chat-buffer-send () (interactive) (let ((body (delete-and-extract-region (+ (length shem-chat-line-dilimeter) shem-chat-point-insert) (point-max)))) (unless (zerop (length body)) (funcall shem-chat-send-function body)))) (defun shem-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) ; (if (not shem-chat-point-insert) ; (setq shem-chat-point-insert (point-max))) (let ((at-insert-point (eq (point) shem-chat-point-insert)) outputp) (save-excursion (goto-char shem-chat-point-insert) (setq outputp (shem-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) (setq shem-chat-point-insert (point)) (set-text-properties shem-chat-point-insert (point-max) nil)) (when at-insert-point (goto-char shem-chat-point-insert)) outputp)) (defun shem-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) (let ((inhibit-read-only t) (beg (point)) (point-insert (set-marker (make-marker) shem-chat-point-insert))) (set-marker-insertion-type point-insert t) (dolist (printer output-functions) (funcall printer output-data) (unless (bolp) (insert "\n"))) (unless (eq (point) beg) (let ((end (point-marker))) (unless tail (goto-char beg) (funcall prompt-function prompt-data) (goto-char end)) (put-text-property beg end 'read-only t) (put-text-property beg end 'front-sticky t) (put-text-property beg end 'rear-nonsticky t) ;;add message to history (write-region beg end (concat "~/.messager/" shem-chatting-with ".txt") t 'no-echo) ;; this is always non-nil, so we return that (setq shem-chat-point-insert (marker-position point-insert)))))) (defun shem-chat-send (body) (shem-chat-send-message shem-chatting-with body) (shem-chat-buffer-display 'shem-chat-self-prompt nil '(insert) (propertize body 'face 'default) nil)) (defun shem-chat-recieve(name from body &optional tail) ;;(with-current-buffer (get-buffer-create "*chat-debug*") ;; (insert body)) (let* ((buf-name (shem-chat-get-buffer from)) (curr-buf (or (get-buffer buf-name) (shem-chat-create-buffer from)))) (with-current-buffer curr-buf (shem-chat-buffer-display 'shem-chat-foriegn-prompt name '(insert) (propertize body 'face 'default) tail))) (shem-activity-add from)) (defun shem-chat-self-prompt (timestamp) (insert (propertize (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") 'face 'shem-chat-my-message-face))) (defun shem-chat-foriegn-prompt (name) (insert (propertize (concat "["(format-time-string "%H:%M") "] " name "> ") 'face 'shem-chat-foriegn-message-face))) (defun shem-chat-get-buffer (chat-with) (concat "*chat:" chat-with "*")) (defun shem-chat-create-buffer (chat-with) (with-current-buffer (get-buffer-create (shem-chat-get-buffer chat-with)) (insert shem-chat-line-dilimeter) (if (not (eq major-mode 'shem-chat-mode)) (shem-chat-mode)) (make-local-variable 'shem-chatting-with) (setq shem-chatting-with chat-with) (setq shem-chat-send-function 'shem-chat-send) (make-local-variable 'shem-chat-earliest-backlog) (set-input-method shem-default-input-method) (current-buffer))) (defun shem-protocol-user-name (user &optional protocol) (concat (if user user "unknown") (if protocol (concat shem-protocol-delimeter protocol ) ""))) (defun shem-user-list (&optional protocol) (shem-pidgin-buddy-list protocol)) (defun shem-chat-with (&optional protocol-id) (interactive (list current-prefix-arg)) (let* ((user (let ((protocol (if (and current-prefix-arg (numberp current-prefix-arg) (eq current-prefix-arg 1)) shem-icq-protocol shem-jabber-protocol))) (shem-protocol-user-name - (completing-read "chat with: " (shem-user-list protocol)) + (ido-completing-read "chat with: " (shem-user-list protocol)) protocol))) (curr-buf (or (get-buffer (shem-chat-get-buffer user)) (shem-chat-create-buffer user)))) (switch-to-buffer curr-buf))) (provide 'shem-chatbuffer)
h1t/emacs-chat
29eecc5fdda54a2aa9240eda970bef7b5212c7f2
added cl package; added default input method
diff --git a/README b/README index 7f86315..47b395d 100644 --- a/README +++ b/README @@ -1,14 +1,23 @@ add to your .emacs file: (require 'shem-chatcore) +;; jabber user list (setq shem-jabber-name-list - (list '("testJabberBuddy" "[email protected]"))) + (list '("testJabberBuddy1" "[email protected]") + '("testJabberBuddy2" "[email protected]"))) +;; icq user list (setq shem-icq-name-list - (list '("testICQBuddy" "777777"))) + (list '("testICQBuddy1" "777777") + '("testICQBuddy2" "777777"))) + +;;default input method +(setq shem-default-input-method "russian-computer") + (shem-chat-connect) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ run for chat with jabber protocol: M-x shem-chat-with run for chat with icq protocol: M-1 M-x shem-chat-with diff --git a/shem-chatbuffer.el b/shem-chatbuffer.el index 0dc6fe0..f026de3 100644 --- a/shem-chatbuffer.el +++ b/shem-chatbuffer.el @@ -1,172 +1,172 @@ (defgroup shem-chat nil "Herocraft instant messaging" :group 'applications) (defface shem-chat-my-message-face '((t (:foreground "salmon" :weight bold))) "face for own message" :group 'shem-chat) (defface shem-chat-foriegn-message-face '((t (:foreground "SteelBlue1" :weight bold))) "face for foriegn message" :group 'shem-chat) (defvar shem-chat-point-insert nil "Position where the message being composed starts") (defvar shem-chat-send-function nil "Function for sending a message from a chat buffer.") (defconst shem-chat-line-dilimeter "----\n") (defun shem-chat-mode () (kill-all-local-variables) ;; Make sure to set this variable somewhere (make-local-variable 'shem-chat-send-function) (make-local-variable 'scroll-conservatively) (setq scroll-conservatively 5) (make-local-variable 'shem-chat-point-insert) (setq shem-chat-point-insert (point-min)) (setq major-mode 'shem-chat-mode mode-name "chat") (use-local-map shem-chat-mode-map) (put 'shem-chat-mode 'mode-class 'special)) (defvar shem-chat-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map nil) (define-key map "\r" 'shem-chat-buffer-send) map)) (defun shem-chat-buffer-send () (interactive) (let ((body (delete-and-extract-region (+ (length shem-chat-line-dilimeter) shem-chat-point-insert) (point-max)))) (unless (zerop (length body)) (funcall shem-chat-send-function body)))) (defun shem-chat-buffer-display (prompt-function prompt-data output-functions output-data tail) ; (if (not shem-chat-point-insert) ; (setq shem-chat-point-insert (point-max))) (let ((at-insert-point (eq (point) shem-chat-point-insert)) outputp) (save-excursion (goto-char shem-chat-point-insert) (setq outputp (shem-chat-buffer-display-at-point prompt-function prompt-data output-functions output-data tail)) (setq shem-chat-point-insert (point)) (set-text-properties shem-chat-point-insert (point-max) nil)) (when at-insert-point (goto-char shem-chat-point-insert)) outputp)) (defun shem-chat-buffer-display-at-point (prompt-function prompt-data output-functions output-data tail) (let ((inhibit-read-only t) (beg (point)) (point-insert (set-marker (make-marker) shem-chat-point-insert))) (set-marker-insertion-type point-insert t) (dolist (printer output-functions) (funcall printer output-data) (unless (bolp) (insert "\n"))) (unless (eq (point) beg) (let ((end (point-marker))) (unless tail (goto-char beg) (funcall prompt-function prompt-data) (goto-char end)) (put-text-property beg end 'read-only t) (put-text-property beg end 'front-sticky t) (put-text-property beg end 'rear-nonsticky t) ;;add message to history (write-region beg end (concat "~/.messager/" shem-chatting-with ".txt") t 'no-echo) ;; this is always non-nil, so we return that (setq shem-chat-point-insert (marker-position point-insert)))))) (defun shem-chat-send (body) (shem-chat-send-message shem-chatting-with body) (shem-chat-buffer-display 'shem-chat-self-prompt nil '(insert) (propertize body 'face 'default) nil)) (defun shem-chat-recieve(name from body &optional tail) ;;(with-current-buffer (get-buffer-create "*chat-debug*") ;; (insert body)) (let* ((buf-name (shem-chat-get-buffer from)) (curr-buf (or (get-buffer buf-name) (shem-chat-create-buffer from)))) (with-current-buffer curr-buf (shem-chat-buffer-display 'shem-chat-foriegn-prompt name '(insert) (propertize body 'face 'default) tail))) (shem-activity-add from)) (defun shem-chat-self-prompt (timestamp) (insert (propertize (concat "["(format-time-string "%H:%M") "] " (system-name) "> ") 'face 'shem-chat-my-message-face))) (defun shem-chat-foriegn-prompt (name) (insert (propertize (concat "["(format-time-string "%H:%M") "] " name "> ") 'face 'shem-chat-foriegn-message-face))) (defun shem-chat-get-buffer (chat-with) (concat "*chat:" chat-with "*")) (defun shem-chat-create-buffer (chat-with) (with-current-buffer (get-buffer-create (shem-chat-get-buffer chat-with)) (insert shem-chat-line-dilimeter) (if (not (eq major-mode 'shem-chat-mode)) (shem-chat-mode)) (make-local-variable 'shem-chatting-with) (setq shem-chatting-with chat-with) (setq shem-chat-send-function 'shem-chat-send) (make-local-variable 'shem-chat-earliest-backlog) - (set-input-method "russian-dvorak") + (set-input-method shem-default-input-method) (current-buffer))) (defun shem-protocol-user-name (user &optional protocol) (concat (if user user "unknown") (if protocol (concat shem-protocol-delimeter protocol ) ""))) (defun shem-user-list (&optional protocol) (shem-pidgin-buddy-list protocol)) (defun shem-chat-with (&optional protocol-id) (interactive (list current-prefix-arg)) (let* ((user (let ((protocol (if (and current-prefix-arg (numberp current-prefix-arg) (eq current-prefix-arg 1)) shem-icq-protocol shem-jabber-protocol))) (shem-protocol-user-name - (ido-completing-read "chat with: " (shem-user-list protocol)) + (completing-read "chat with: " (shem-user-list protocol)) protocol))) (curr-buf (or (get-buffer (shem-chat-get-buffer user)) (shem-chat-create-buffer user)))) (switch-to-buffer curr-buf))) (provide 'shem-chatbuffer) diff --git a/shem-chatcore.el b/shem-chatcore.el index c0b280c..ef4ed90 100644 --- a/shem-chatcore.el +++ b/shem-chatcore.el @@ -1,16 +1,21 @@ +(require 'cl) (require 'shem-chatbuffer) (require 'shem-pidgin) (require 'shem-chatactivity) (require 'shem-util) +(defconst shem-protocol-delimeter "-") + +(defvar shem-default-input-method "russian-computer") + (defun shem-chat-connect () (shem-pidgin-init)) (defvar shem-chat-from nil) (defvar shem-chat-to nil) (defvar shem-chat-message nil) (defun shem-chat-send-message (to message) (shem-pidgin-send-message to message)) (provide 'shem-chatcore) diff --git a/shem-util.el b/shem-util.el new file mode 100644 index 0000000..fb9345c --- /dev/null +++ b/shem-util.el @@ -0,0 +1,11 @@ +(defun shem-replace-regexp (regexp to-string) + (while (re-search-forward regexp nil t) + (replace-match to-string nil nil))) + +(defun shem-string-befor-p (prefix str) + (string-match (concat "^" prefix ".*") str)) + +(defun shem-string-after-p (postfix str) + (string-match (concat postfix "$") str)) + +(provide 'shem-util)
h1t/emacs-chat
b87b9b39965f373f7a4785e5e59fd8eddb0c7dd4
added shem-util dependence
diff --git a/shem-chatcore.el b/shem-chatcore.el index 8605dca..c0b280c 100644 --- a/shem-chatcore.el +++ b/shem-chatcore.el @@ -1,15 +1,16 @@ (require 'shem-chatbuffer) (require 'shem-pidgin) (require 'shem-chatactivity) +(require 'shem-util) (defun shem-chat-connect () (shem-pidgin-init)) (defvar shem-chat-from nil) (defvar shem-chat-to nil) (defvar shem-chat-message nil) (defun shem-chat-send-message (to message) (shem-pidgin-send-message to message)) (provide 'shem-chatcore)
jtadeulopes/Rails-Env-Automatic-Install
a583be0828a71baf209148d43bbe1411482e2e48
Added gem shoulda and mocha.
diff --git a/development-rails-setup.sh b/development-rails-setup.sh index 8bb4329..221048c 100644 --- a/development-rails-setup.sh +++ b/development-rails-setup.sh @@ -1,227 +1,229 @@ #!/bin/bash if [ "$(whoami)" != "root" ]; then echo "You need to be root to run this!" exit 2 fi echo "" echo "================================================================" echo "\tBASIC RAILS DEVELOPMENT SETUP" echo "\tAuthor: Junio Vitorino" echo "\tEmail: [email protected]" echo "\tBlog: http://www.lamiscela.net" echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" echo "================================================================" echo "" echo "" echo "" echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" read START if [ $START = "q" ]; then echo "Installation not started" exit 2 fi echo "" echo "" echo " Starting..." echo "" echo "" echo "" echo "================================================================" echo "\tInstalling compilers" echo "================================================================" echo "" apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev echo "" echo "================================================================" echo "\tInstalling required libraries and packages" echo "================================================================" echo "" apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg libapr1-dev libaprutil1-dev memcached echo "" echo "================================================================" echo "\tRuby 1.8.7 Patch Level 72" echo "================================================================" echo "" if [ -d /src ] then cd /src else mkdir /src cd /src fi wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null cd ruby-1.8.7-p72 ./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr make make install ln -s /usr/local/bin/ruby /usr/bin/ruby /usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" cd / rm /src/ruby-1.8.7-p72.tar.gz rm -rf /src/ruby-1.8.7-p72 echo "" echo "================================================================" echo "\tRubyGems 1.3.5" echo "================================================================" echo "" cd /src wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5/ ruby setup.rb cd / rm /src/rubygems-1.3.5.tgz rm -rf /src/rubygems-1.3.5 echo "" echo "================================================================" echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" echo "================================================================" echo "" apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev echo "" echo "================================================================" echo "\tGIT" echo "================================================================" echo "" cd /src wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz tar -xzvf git-1.6.5.2.tar.gz cd git-1.6.5.2/ ./configure make make install ln -s /usr/local/bin/git /usr/bin/git cd / rm /src/git-1.6.5.2.tar.gz rm -rf /src/git-1.6.5.2 gem sources -a http://gemcutter.org gem sources -a http://gems.github.com gem install --no-rdoc --no-ri rails echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" read WANTS_GEMS_PACK if [ $WANTS_GEMS_PACK = "y" ]; then echo "" echo "================================================================" echo "\tInstalling GEMS" echo "================================================================" echo "" gem install --no-rdoc --no-ri authlogic gem install --no-rdoc --no-ri paperclip gem install --no-rdoc --no-ri mysql gem install --no-ri --no-rdoc rmagick gem install --no-ri --no-rdoc chronic gem install --no-ri --no-rdoc geoip gem install --no-ri --no-rdoc daemons gem install --no-ri --no-rdoc hoe gem install --no-ri --no-rdoc echoe gem install --no-ri --no-rdoc ruby-yadis gem install --no-ri --no-rdoc ruby-openid gem install --no-ri --no-rdoc mime-types gem install --no-ri --no-rdoc diff-lcs gem install --no-ri --no-rdoc json gem install --no-ri --no-rdoc rack gem install --no-ri --no-rdoc ruby-hmac gem install --no-ri --no-rdoc rake gem install --no-ri --no-rdoc stompserver gem install --no-ri --no-rdoc passenger gem install --no-ri --no-rdoc hpricot gem install --no-ri --no-rdoc ruby-debug gem install --no-ri --no-rdoc capistrano gem install --no-ri --no-rdoc rspec gem install --no-ri --no-rdoc ZenTest gem install --no-ri --no-rdoc webrat gem install --no-ri --no-rdoc image_science gem install --no-ri --no-rdoc mini_magick gem install --no-ri --no-rdoc mechanize gem install --no-ri --no-rdoc RedCloth gem install --no-ri --no-rdoc fastercsv gem install --no-ri --no-rdoc piston gem install --no-ri --no-rdoc sashimi gem install --no-ri --no-rdoc ruport gem install --no-ri --no-rdoc open4 gem install --no-ri --no-rdoc rubigen gem install --no-ri --no-rdoc sqlite3-ruby gem install --no-ri --no-rdoc mongrel gem install --no-ri --no-rdoc mongrel_service gem install --no-ri --no-rdoc oniguruma gem install --no-ri --no-rdoc ultraviolet gem install --no-ri --no-rdoc libxml-ruby gem install --no-ri --no-rdoc faker gem install --no-ri --no-rdoc populator gem install --no-ri --no-rdoc remarkable_rails gem install --no-ri --no-rdoc brazilian-rails gem install --no-ri --no-rdoc grit gem install --no-ri --no-rdoc gravtastic gem install --no-ri --no-rdoc formtastic gem install --no-ri --no-rdoc annotate + gem install --no-ri --no-rdoc shoulda + gem install --no-ri --no-rdoc mocha fi echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" read WANTS_GMATE if [ $WANTS_GMATE = 'y' ]; then echo "" echo "================================================================" echo "\tInstalling GMATE Plugins" echo "================================================================" echo "" cd /srv git clone git://github.com/lexrupy/gmate.git cd gmate sh install.sh cd / rm -rf /src/gmate fi echo "Do you'd like setup Apache to works with Passenger? (y/n)" read WANTS_PASSENGER if [ $WANTS_PASSENGER = 'y' ]; then echo "" echo "================================================================" echo "\tEnable Passenger" echo "================================================================" echo "" gem install --no-ri --no-rdoc passenger passenger-install-apache2-module echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load a2enmod passenger a2enmod rewrite /etc/init.d/apache2 restart fi echo "" echo "" echo "==================================================" echo "\tServer installation finished" echo "=================================================="
jtadeulopes/Rails-Env-Automatic-Install
32d59424b705e4d3f25630bc1037e5b489a74ada
Added gem flog, flay, reek, roodi, rcov and gruff.
diff --git a/development-rails-setup.sh b/development-rails-setup.sh index 8bb4329..d16e5e5 100644 --- a/development-rails-setup.sh +++ b/development-rails-setup.sh @@ -1,227 +1,233 @@ #!/bin/bash if [ "$(whoami)" != "root" ]; then echo "You need to be root to run this!" exit 2 fi echo "" echo "================================================================" echo "\tBASIC RAILS DEVELOPMENT SETUP" echo "\tAuthor: Junio Vitorino" echo "\tEmail: [email protected]" echo "\tBlog: http://www.lamiscela.net" echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" echo "================================================================" echo "" echo "" echo "" echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" read START if [ $START = "q" ]; then echo "Installation not started" exit 2 fi echo "" echo "" echo " Starting..." echo "" echo "" echo "" echo "================================================================" echo "\tInstalling compilers" echo "================================================================" echo "" apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev echo "" echo "================================================================" echo "\tInstalling required libraries and packages" echo "================================================================" echo "" apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg libapr1-dev libaprutil1-dev memcached echo "" echo "================================================================" echo "\tRuby 1.8.7 Patch Level 72" echo "================================================================" echo "" if [ -d /src ] then cd /src else mkdir /src cd /src fi wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null cd ruby-1.8.7-p72 ./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr make make install ln -s /usr/local/bin/ruby /usr/bin/ruby /usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" cd / rm /src/ruby-1.8.7-p72.tar.gz rm -rf /src/ruby-1.8.7-p72 echo "" echo "================================================================" echo "\tRubyGems 1.3.5" echo "================================================================" echo "" cd /src wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5/ ruby setup.rb cd / rm /src/rubygems-1.3.5.tgz rm -rf /src/rubygems-1.3.5 echo "" echo "================================================================" echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" echo "================================================================" echo "" apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev echo "" echo "================================================================" echo "\tGIT" echo "================================================================" echo "" cd /src wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz tar -xzvf git-1.6.5.2.tar.gz cd git-1.6.5.2/ ./configure make make install ln -s /usr/local/bin/git /usr/bin/git cd / rm /src/git-1.6.5.2.tar.gz rm -rf /src/git-1.6.5.2 gem sources -a http://gemcutter.org gem sources -a http://gems.github.com gem install --no-rdoc --no-ri rails echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" read WANTS_GEMS_PACK if [ $WANTS_GEMS_PACK = "y" ]; then echo "" echo "================================================================" echo "\tInstalling GEMS" echo "================================================================" echo "" gem install --no-rdoc --no-ri authlogic gem install --no-rdoc --no-ri paperclip gem install --no-rdoc --no-ri mysql gem install --no-ri --no-rdoc rmagick gem install --no-ri --no-rdoc chronic gem install --no-ri --no-rdoc geoip gem install --no-ri --no-rdoc daemons gem install --no-ri --no-rdoc hoe gem install --no-ri --no-rdoc echoe gem install --no-ri --no-rdoc ruby-yadis gem install --no-ri --no-rdoc ruby-openid gem install --no-ri --no-rdoc mime-types gem install --no-ri --no-rdoc diff-lcs gem install --no-ri --no-rdoc json gem install --no-ri --no-rdoc rack gem install --no-ri --no-rdoc ruby-hmac gem install --no-ri --no-rdoc rake gem install --no-ri --no-rdoc stompserver gem install --no-ri --no-rdoc passenger gem install --no-ri --no-rdoc hpricot gem install --no-ri --no-rdoc ruby-debug gem install --no-ri --no-rdoc capistrano gem install --no-ri --no-rdoc rspec gem install --no-ri --no-rdoc ZenTest gem install --no-ri --no-rdoc webrat gem install --no-ri --no-rdoc image_science gem install --no-ri --no-rdoc mini_magick gem install --no-ri --no-rdoc mechanize gem install --no-ri --no-rdoc RedCloth gem install --no-ri --no-rdoc fastercsv gem install --no-ri --no-rdoc piston gem install --no-ri --no-rdoc sashimi gem install --no-ri --no-rdoc ruport gem install --no-ri --no-rdoc open4 gem install --no-ri --no-rdoc rubigen gem install --no-ri --no-rdoc sqlite3-ruby gem install --no-ri --no-rdoc mongrel gem install --no-ri --no-rdoc mongrel_service gem install --no-ri --no-rdoc oniguruma gem install --no-ri --no-rdoc ultraviolet gem install --no-ri --no-rdoc libxml-ruby gem install --no-ri --no-rdoc faker gem install --no-ri --no-rdoc populator gem install --no-ri --no-rdoc remarkable_rails gem install --no-ri --no-rdoc brazilian-rails gem install --no-ri --no-rdoc grit gem install --no-ri --no-rdoc gravtastic gem install --no-ri --no-rdoc formtastic gem install --no-ri --no-rdoc annotate + gem install --no-ri --no-rdoc flog + gem install --no-ri --no-rdoc flay + gem install --no-ri --no-rdoc reek + gem install --no-ri --no-rdoc roodi + gem install --no-ri --no-rdoc rcov + gem install --no-ri --no-rdoc gruff fi echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" read WANTS_GMATE if [ $WANTS_GMATE = 'y' ]; then echo "" echo "================================================================" echo "\tInstalling GMATE Plugins" echo "================================================================" echo "" cd /srv git clone git://github.com/lexrupy/gmate.git cd gmate sh install.sh cd / rm -rf /src/gmate fi echo "Do you'd like setup Apache to works with Passenger? (y/n)" read WANTS_PASSENGER if [ $WANTS_PASSENGER = 'y' ]; then echo "" echo "================================================================" echo "\tEnable Passenger" echo "================================================================" echo "" gem install --no-ri --no-rdoc passenger passenger-install-apache2-module echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load a2enmod passenger a2enmod rewrite /etc/init.d/apache2 restart fi echo "" echo "" echo "==================================================" echo "\tServer installation finished" echo "=================================================="
jtadeulopes/Rails-Env-Automatic-Install
1b6e2a072331194ee24f82a89d72a535bc738f40
Added gem annotate
diff --git a/development-rails-setup.sh b/development-rails-setup.sh index fcfcc0b..8bb4329 100644 --- a/development-rails-setup.sh +++ b/development-rails-setup.sh @@ -1,226 +1,227 @@ #!/bin/bash if [ "$(whoami)" != "root" ]; then echo "You need to be root to run this!" exit 2 fi echo "" echo "================================================================" echo "\tBASIC RAILS DEVELOPMENT SETUP" echo "\tAuthor: Junio Vitorino" echo "\tEmail: [email protected]" echo "\tBlog: http://www.lamiscela.net" echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" echo "================================================================" echo "" echo "" echo "" echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" read START if [ $START = "q" ]; then echo "Installation not started" exit 2 fi echo "" echo "" echo " Starting..." echo "" echo "" echo "" echo "================================================================" echo "\tInstalling compilers" echo "================================================================" echo "" apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev echo "" echo "================================================================" echo "\tInstalling required libraries and packages" echo "================================================================" echo "" apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg libapr1-dev libaprutil1-dev memcached echo "" echo "================================================================" echo "\tRuby 1.8.7 Patch Level 72" echo "================================================================" echo "" if [ -d /src ] then cd /src else mkdir /src cd /src fi wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null cd ruby-1.8.7-p72 ./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr make make install ln -s /usr/local/bin/ruby /usr/bin/ruby /usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" cd / rm /src/ruby-1.8.7-p72.tar.gz rm -rf /src/ruby-1.8.7-p72 echo "" echo "================================================================" echo "\tRubyGems 1.3.5" echo "================================================================" echo "" cd /src wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5/ ruby setup.rb cd / rm /src/rubygems-1.3.5.tgz rm -rf /src/rubygems-1.3.5 echo "" echo "================================================================" echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" echo "================================================================" echo "" apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev echo "" echo "================================================================" echo "\tGIT" echo "================================================================" echo "" cd /src wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz tar -xzvf git-1.6.5.2.tar.gz cd git-1.6.5.2/ ./configure make make install ln -s /usr/local/bin/git /usr/bin/git cd / rm /src/git-1.6.5.2.tar.gz rm -rf /src/git-1.6.5.2 gem sources -a http://gemcutter.org gem sources -a http://gems.github.com gem install --no-rdoc --no-ri rails echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" read WANTS_GEMS_PACK if [ $WANTS_GEMS_PACK = "y" ]; then echo "" echo "================================================================" echo "\tInstalling GEMS" echo "================================================================" echo "" gem install --no-rdoc --no-ri authlogic gem install --no-rdoc --no-ri paperclip gem install --no-rdoc --no-ri mysql gem install --no-ri --no-rdoc rmagick gem install --no-ri --no-rdoc chronic gem install --no-ri --no-rdoc geoip gem install --no-ri --no-rdoc daemons gem install --no-ri --no-rdoc hoe gem install --no-ri --no-rdoc echoe gem install --no-ri --no-rdoc ruby-yadis gem install --no-ri --no-rdoc ruby-openid gem install --no-ri --no-rdoc mime-types gem install --no-ri --no-rdoc diff-lcs gem install --no-ri --no-rdoc json gem install --no-ri --no-rdoc rack gem install --no-ri --no-rdoc ruby-hmac gem install --no-ri --no-rdoc rake gem install --no-ri --no-rdoc stompserver gem install --no-ri --no-rdoc passenger gem install --no-ri --no-rdoc hpricot gem install --no-ri --no-rdoc ruby-debug gem install --no-ri --no-rdoc capistrano gem install --no-ri --no-rdoc rspec gem install --no-ri --no-rdoc ZenTest gem install --no-ri --no-rdoc webrat gem install --no-ri --no-rdoc image_science gem install --no-ri --no-rdoc mini_magick gem install --no-ri --no-rdoc mechanize gem install --no-ri --no-rdoc RedCloth gem install --no-ri --no-rdoc fastercsv gem install --no-ri --no-rdoc piston gem install --no-ri --no-rdoc sashimi gem install --no-ri --no-rdoc ruport gem install --no-ri --no-rdoc open4 gem install --no-ri --no-rdoc rubigen gem install --no-ri --no-rdoc sqlite3-ruby gem install --no-ri --no-rdoc mongrel gem install --no-ri --no-rdoc mongrel_service gem install --no-ri --no-rdoc oniguruma gem install --no-ri --no-rdoc ultraviolet gem install --no-ri --no-rdoc libxml-ruby gem install --no-ri --no-rdoc faker gem install --no-ri --no-rdoc populator gem install --no-ri --no-rdoc remarkable_rails gem install --no-ri --no-rdoc brazilian-rails gem install --no-ri --no-rdoc grit gem install --no-ri --no-rdoc gravtastic gem install --no-ri --no-rdoc formtastic + gem install --no-ri --no-rdoc annotate fi echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" read WANTS_GMATE if [ $WANTS_GMATE = 'y' ]; then echo "" echo "================================================================" echo "\tInstalling GMATE Plugins" echo "================================================================" echo "" cd /srv git clone git://github.com/lexrupy/gmate.git cd gmate sh install.sh cd / rm -rf /src/gmate fi echo "Do you'd like setup Apache to works with Passenger? (y/n)" read WANTS_PASSENGER if [ $WANTS_PASSENGER = 'y' ]; then echo "" echo "================================================================" echo "\tEnable Passenger" echo "================================================================" echo "" gem install --no-ri --no-rdoc passenger passenger-install-apache2-module echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load a2enmod passenger a2enmod rewrite /etc/init.d/apache2 restart fi echo "" echo "" echo "==================================================" echo "\tServer installation finished" echo "=================================================="
jtadeulopes/Rails-Env-Automatic-Install
1a5670a73ae1215b4821fc119eddddec8c4024bf
added gem faker, populator, remarkable_rails, brazilian-rails, grit, gravtastic and formtastic.
diff --git a/development-rails-setup.sh b/development-rails-setup.sh index e528e22..fcfcc0b 100644 --- a/development-rails-setup.sh +++ b/development-rails-setup.sh @@ -1,219 +1,226 @@ #!/bin/bash if [ "$(whoami)" != "root" ]; then echo "You need to be root to run this!" exit 2 fi echo "" echo "================================================================" echo "\tBASIC RAILS DEVELOPMENT SETUP" echo "\tAuthor: Junio Vitorino" echo "\tEmail: [email protected]" echo "\tBlog: http://www.lamiscela.net" echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" echo "================================================================" echo "" echo "" echo "" echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" read START if [ $START = "q" ]; then echo "Installation not started" exit 2 fi echo "" echo "" echo " Starting..." echo "" echo "" echo "" echo "================================================================" echo "\tInstalling compilers" echo "================================================================" echo "" apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev echo "" echo "================================================================" echo "\tInstalling required libraries and packages" echo "================================================================" echo "" apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg libapr1-dev libaprutil1-dev memcached echo "" echo "================================================================" echo "\tRuby 1.8.7 Patch Level 72" echo "================================================================" echo "" if [ -d /src ] then cd /src else mkdir /src cd /src fi wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null cd ruby-1.8.7-p72 ./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr make make install ln -s /usr/local/bin/ruby /usr/bin/ruby /usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" cd / rm /src/ruby-1.8.7-p72.tar.gz rm -rf /src/ruby-1.8.7-p72 echo "" echo "================================================================" echo "\tRubyGems 1.3.5" echo "================================================================" echo "" cd /src wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5/ ruby setup.rb cd / rm /src/rubygems-1.3.5.tgz rm -rf /src/rubygems-1.3.5 echo "" echo "================================================================" echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" echo "================================================================" echo "" apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev echo "" echo "================================================================" echo "\tGIT" echo "================================================================" echo "" cd /src wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz tar -xzvf git-1.6.5.2.tar.gz cd git-1.6.5.2/ ./configure make make install ln -s /usr/local/bin/git /usr/bin/git cd / rm /src/git-1.6.5.2.tar.gz rm -rf /src/git-1.6.5.2 gem sources -a http://gemcutter.org gem sources -a http://gems.github.com gem install --no-rdoc --no-ri rails echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" read WANTS_GEMS_PACK if [ $WANTS_GEMS_PACK = "y" ]; then echo "" echo "================================================================" echo "\tInstalling GEMS" echo "================================================================" echo "" gem install --no-rdoc --no-ri authlogic gem install --no-rdoc --no-ri paperclip gem install --no-rdoc --no-ri mysql gem install --no-ri --no-rdoc rmagick gem install --no-ri --no-rdoc chronic gem install --no-ri --no-rdoc geoip gem install --no-ri --no-rdoc daemons gem install --no-ri --no-rdoc hoe gem install --no-ri --no-rdoc echoe gem install --no-ri --no-rdoc ruby-yadis gem install --no-ri --no-rdoc ruby-openid gem install --no-ri --no-rdoc mime-types gem install --no-ri --no-rdoc diff-lcs gem install --no-ri --no-rdoc json gem install --no-ri --no-rdoc rack gem install --no-ri --no-rdoc ruby-hmac gem install --no-ri --no-rdoc rake gem install --no-ri --no-rdoc stompserver gem install --no-ri --no-rdoc passenger gem install --no-ri --no-rdoc hpricot gem install --no-ri --no-rdoc ruby-debug gem install --no-ri --no-rdoc capistrano gem install --no-ri --no-rdoc rspec gem install --no-ri --no-rdoc ZenTest gem install --no-ri --no-rdoc webrat gem install --no-ri --no-rdoc image_science gem install --no-ri --no-rdoc mini_magick gem install --no-ri --no-rdoc mechanize gem install --no-ri --no-rdoc RedCloth gem install --no-ri --no-rdoc fastercsv gem install --no-ri --no-rdoc piston gem install --no-ri --no-rdoc sashimi gem install --no-ri --no-rdoc ruport gem install --no-ri --no-rdoc open4 gem install --no-ri --no-rdoc rubigen gem install --no-ri --no-rdoc sqlite3-ruby gem install --no-ri --no-rdoc mongrel gem install --no-ri --no-rdoc mongrel_service gem install --no-ri --no-rdoc oniguruma gem install --no-ri --no-rdoc ultraviolet gem install --no-ri --no-rdoc libxml-ruby + gem install --no-ri --no-rdoc faker + gem install --no-ri --no-rdoc populator + gem install --no-ri --no-rdoc remarkable_rails + gem install --no-ri --no-rdoc brazilian-rails + gem install --no-ri --no-rdoc grit + gem install --no-ri --no-rdoc gravtastic + gem install --no-ri --no-rdoc formtastic fi echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" read WANTS_GMATE if [ $WANTS_GMATE = 'y' ]; then echo "" echo "================================================================" echo "\tInstalling GMATE Plugins" echo "================================================================" echo "" cd /srv git clone git://github.com/lexrupy/gmate.git cd gmate sh install.sh cd / rm -rf /src/gmate fi echo "Do you'd like setup Apache to works with Passenger? (y/n)" read WANTS_PASSENGER if [ $WANTS_PASSENGER = 'y' ]; then echo "" echo "================================================================" echo "\tEnable Passenger" echo "================================================================" echo "" gem install --no-ri --no-rdoc passenger passenger-install-apache2-module echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load a2enmod passenger a2enmod rewrite /etc/init.d/apache2 restart fi echo "" echo "" echo "==================================================" echo "\tServer installation finished" -echo "==================================================" \ No newline at end of file +echo "=================================================="
jtadeulopes/Rails-Env-Automatic-Install
ebe7a5a64dbdc85b4208f11234d26c0639c663fb
Fix operator at start conditional
diff --git a/development-rails-setup.sh b/development-rails-setup.sh index 020f506..e528e22 100644 --- a/development-rails-setup.sh +++ b/development-rails-setup.sh @@ -1,219 +1,219 @@ #!/bin/bash if [ "$(whoami)" != "root" ]; then echo "You need to be root to run this!" exit 2 fi echo "" echo "================================================================" echo "\tBASIC RAILS DEVELOPMENT SETUP" echo "\tAuthor: Junio Vitorino" echo "\tEmail: [email protected]" echo "\tBlog: http://www.lamiscela.net" echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" echo "================================================================" echo "" echo "" echo "" echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" read START -if [ $START == "q" ]; then +if [ $START = "q" ]; then echo "Installation not started" exit 2 fi echo "" echo "" echo " Starting..." echo "" echo "" echo "" echo "================================================================" echo "\tInstalling compilers" echo "================================================================" echo "" apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev echo "" echo "================================================================" echo "\tInstalling required libraries and packages" echo "================================================================" echo "" apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg libapr1-dev libaprutil1-dev memcached echo "" echo "================================================================" echo "\tRuby 1.8.7 Patch Level 72" echo "================================================================" echo "" if [ -d /src ] then cd /src else mkdir /src cd /src fi wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null cd ruby-1.8.7-p72 ./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr make make install ln -s /usr/local/bin/ruby /usr/bin/ruby /usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" cd / rm /src/ruby-1.8.7-p72.tar.gz rm -rf /src/ruby-1.8.7-p72 echo "" echo "================================================================" echo "\tRubyGems 1.3.5" echo "================================================================" echo "" cd /src wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5/ ruby setup.rb cd / rm /src/rubygems-1.3.5.tgz rm -rf /src/rubygems-1.3.5 echo "" echo "================================================================" echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" echo "================================================================" echo "" apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev echo "" echo "================================================================" echo "\tGIT" echo "================================================================" echo "" cd /src wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz tar -xzvf git-1.6.5.2.tar.gz cd git-1.6.5.2/ ./configure make make install ln -s /usr/local/bin/git /usr/bin/git cd / rm /src/git-1.6.5.2.tar.gz rm -rf /src/git-1.6.5.2 gem sources -a http://gemcutter.org gem sources -a http://gems.github.com gem install --no-rdoc --no-ri rails echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" read WANTS_GEMS_PACK if [ $WANTS_GEMS_PACK = "y" ]; then echo "" echo "================================================================" echo "\tInstalling GEMS" echo "================================================================" echo "" gem install --no-rdoc --no-ri authlogic gem install --no-rdoc --no-ri paperclip gem install --no-rdoc --no-ri mysql gem install --no-ri --no-rdoc rmagick gem install --no-ri --no-rdoc chronic gem install --no-ri --no-rdoc geoip gem install --no-ri --no-rdoc daemons gem install --no-ri --no-rdoc hoe gem install --no-ri --no-rdoc echoe gem install --no-ri --no-rdoc ruby-yadis gem install --no-ri --no-rdoc ruby-openid gem install --no-ri --no-rdoc mime-types gem install --no-ri --no-rdoc diff-lcs gem install --no-ri --no-rdoc json gem install --no-ri --no-rdoc rack gem install --no-ri --no-rdoc ruby-hmac gem install --no-ri --no-rdoc rake gem install --no-ri --no-rdoc stompserver gem install --no-ri --no-rdoc passenger gem install --no-ri --no-rdoc hpricot gem install --no-ri --no-rdoc ruby-debug gem install --no-ri --no-rdoc capistrano gem install --no-ri --no-rdoc rspec gem install --no-ri --no-rdoc ZenTest gem install --no-ri --no-rdoc webrat gem install --no-ri --no-rdoc image_science gem install --no-ri --no-rdoc mini_magick gem install --no-ri --no-rdoc mechanize gem install --no-ri --no-rdoc RedCloth gem install --no-ri --no-rdoc fastercsv gem install --no-ri --no-rdoc piston gem install --no-ri --no-rdoc sashimi gem install --no-ri --no-rdoc ruport gem install --no-ri --no-rdoc open4 gem install --no-ri --no-rdoc rubigen gem install --no-ri --no-rdoc sqlite3-ruby gem install --no-ri --no-rdoc mongrel gem install --no-ri --no-rdoc mongrel_service gem install --no-ri --no-rdoc oniguruma gem install --no-ri --no-rdoc ultraviolet gem install --no-ri --no-rdoc libxml-ruby fi echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" read WANTS_GMATE if [ $WANTS_GMATE = 'y' ]; then echo "" echo "================================================================" echo "\tInstalling GMATE Plugins" echo "================================================================" echo "" cd /srv git clone git://github.com/lexrupy/gmate.git cd gmate sh install.sh cd / rm -rf /src/gmate fi echo "Do you'd like setup Apache to works with Passenger? (y/n)" read WANTS_PASSENGER if [ $WANTS_PASSENGER = 'y' ]; then echo "" echo "================================================================" echo "\tEnable Passenger" echo "================================================================" echo "" gem install --no-ri --no-rdoc passenger passenger-install-apache2-module echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load a2enmod passenger a2enmod rewrite /etc/init.d/apache2 restart fi echo "" echo "" echo "==================================================" echo "\tServer installation finished" echo "==================================================" \ No newline at end of file
jtadeulopes/Rails-Env-Automatic-Install
7123883bfe1f64f0b2e747041d4967091140af4d
Fix the rm command on clean the old files, on RubyGems and Git installations
diff --git a/development-rails-setup.sh b/development-rails-setup.sh index ad249f3..020f506 100644 --- a/development-rails-setup.sh +++ b/development-rails-setup.sh @@ -1,219 +1,219 @@ #!/bin/bash if [ "$(whoami)" != "root" ]; then echo "You need to be root to run this!" exit 2 fi echo "" echo "================================================================" echo "\tBASIC RAILS DEVELOPMENT SETUP" echo "\tAuthor: Junio Vitorino" echo "\tEmail: [email protected]" echo "\tBlog: http://www.lamiscela.net" echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" echo "================================================================" echo "" echo "" echo "" echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" read START if [ $START == "q" ]; then echo "Installation not started" exit 2 fi echo "" echo "" echo " Starting..." echo "" echo "" echo "" echo "================================================================" echo "\tInstalling compilers" echo "================================================================" echo "" apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev echo "" echo "================================================================" echo "\tInstalling required libraries and packages" echo "================================================================" echo "" apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg libapr1-dev libaprutil1-dev memcached echo "" echo "================================================================" echo "\tRuby 1.8.7 Patch Level 72" echo "================================================================" echo "" if [ -d /src ] then cd /src else mkdir /src cd /src fi wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null cd ruby-1.8.7-p72 ./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr make make install ln -s /usr/local/bin/ruby /usr/bin/ruby /usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" cd / rm /src/ruby-1.8.7-p72.tar.gz rm -rf /src/ruby-1.8.7-p72 echo "" echo "================================================================" echo "\tRubyGems 1.3.5" echo "================================================================" echo "" cd /src wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5/ ruby setup.rb cd / rm /src/rubygems-1.3.5.tgz -rm /src/-rf rubygems-1.3.5 +rm -rf /src/rubygems-1.3.5 echo "" echo "================================================================" echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" echo "================================================================" echo "" apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev echo "" echo "================================================================" echo "\tGIT" echo "================================================================" echo "" cd /src wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz tar -xzvf git-1.6.5.2.tar.gz cd git-1.6.5.2/ ./configure make make install ln -s /usr/local/bin/git /usr/bin/git cd / rm /src/git-1.6.5.2.tar.gz -rm /src/-rf git-1.6.5.2 +rm -rf /src/git-1.6.5.2 gem sources -a http://gemcutter.org gem sources -a http://gems.github.com gem install --no-rdoc --no-ri rails echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" read WANTS_GEMS_PACK if [ $WANTS_GEMS_PACK = "y" ]; then echo "" echo "================================================================" echo "\tInstalling GEMS" echo "================================================================" echo "" gem install --no-rdoc --no-ri authlogic gem install --no-rdoc --no-ri paperclip gem install --no-rdoc --no-ri mysql gem install --no-ri --no-rdoc rmagick gem install --no-ri --no-rdoc chronic gem install --no-ri --no-rdoc geoip gem install --no-ri --no-rdoc daemons gem install --no-ri --no-rdoc hoe gem install --no-ri --no-rdoc echoe gem install --no-ri --no-rdoc ruby-yadis gem install --no-ri --no-rdoc ruby-openid gem install --no-ri --no-rdoc mime-types gem install --no-ri --no-rdoc diff-lcs gem install --no-ri --no-rdoc json gem install --no-ri --no-rdoc rack gem install --no-ri --no-rdoc ruby-hmac gem install --no-ri --no-rdoc rake gem install --no-ri --no-rdoc stompserver gem install --no-ri --no-rdoc passenger gem install --no-ri --no-rdoc hpricot gem install --no-ri --no-rdoc ruby-debug gem install --no-ri --no-rdoc capistrano gem install --no-ri --no-rdoc rspec gem install --no-ri --no-rdoc ZenTest gem install --no-ri --no-rdoc webrat gem install --no-ri --no-rdoc image_science gem install --no-ri --no-rdoc mini_magick gem install --no-ri --no-rdoc mechanize gem install --no-ri --no-rdoc RedCloth gem install --no-ri --no-rdoc fastercsv gem install --no-ri --no-rdoc piston gem install --no-ri --no-rdoc sashimi gem install --no-ri --no-rdoc ruport gem install --no-ri --no-rdoc open4 gem install --no-ri --no-rdoc rubigen gem install --no-ri --no-rdoc sqlite3-ruby gem install --no-ri --no-rdoc mongrel gem install --no-ri --no-rdoc mongrel_service gem install --no-ri --no-rdoc oniguruma gem install --no-ri --no-rdoc ultraviolet gem install --no-ri --no-rdoc libxml-ruby fi echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" read WANTS_GMATE if [ $WANTS_GMATE = 'y' ]; then echo "" echo "================================================================" echo "\tInstalling GMATE Plugins" echo "================================================================" echo "" cd /srv git clone git://github.com/lexrupy/gmate.git cd gmate sh install.sh cd / rm -rf /src/gmate fi echo "Do you'd like setup Apache to works with Passenger? (y/n)" read WANTS_PASSENGER if [ $WANTS_PASSENGER = 'y' ]; then echo "" echo "================================================================" echo "\tEnable Passenger" echo "================================================================" echo "" gem install --no-ri --no-rdoc passenger passenger-install-apache2-module echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load a2enmod passenger a2enmod rewrite /etc/init.d/apache2 restart fi echo "" echo "" echo "==================================================" echo "\tServer installation finished" echo "==================================================" \ No newline at end of file
jtadeulopes/Rails-Env-Automatic-Install
c3b6da1f7fa01e3939e940255e732af7de8091c4
Fix equally operator on GMATE, PASSENGER and GEMS conditionals
diff --git a/development-rails-setup.sh b/development-rails-setup.sh index ba8a977..ad249f3 100644 --- a/development-rails-setup.sh +++ b/development-rails-setup.sh @@ -1,219 +1,219 @@ #!/bin/bash if [ "$(whoami)" != "root" ]; then echo "You need to be root to run this!" exit 2 fi echo "" echo "================================================================" echo "\tBASIC RAILS DEVELOPMENT SETUP" echo "\tAuthor: Junio Vitorino" echo "\tEmail: [email protected]" echo "\tBlog: http://www.lamiscela.net" echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" echo "================================================================" echo "" echo "" echo "" echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" read START if [ $START == "q" ]; then echo "Installation not started" exit 2 fi echo "" echo "" echo " Starting..." echo "" echo "" echo "" echo "================================================================" echo "\tInstalling compilers" echo "================================================================" echo "" apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev echo "" echo "================================================================" echo "\tInstalling required libraries and packages" echo "================================================================" echo "" apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg libapr1-dev libaprutil1-dev memcached echo "" echo "================================================================" echo "\tRuby 1.8.7 Patch Level 72" echo "================================================================" echo "" if [ -d /src ] then cd /src else mkdir /src cd /src fi wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null cd ruby-1.8.7-p72 ./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr make make install ln -s /usr/local/bin/ruby /usr/bin/ruby /usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" cd / rm /src/ruby-1.8.7-p72.tar.gz rm -rf /src/ruby-1.8.7-p72 echo "" echo "================================================================" echo "\tRubyGems 1.3.5" echo "================================================================" echo "" cd /src wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5/ ruby setup.rb cd / rm /src/rubygems-1.3.5.tgz rm /src/-rf rubygems-1.3.5 echo "" echo "================================================================" echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" echo "================================================================" echo "" apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev echo "" echo "================================================================" echo "\tGIT" echo "================================================================" echo "" cd /src wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz tar -xzvf git-1.6.5.2.tar.gz cd git-1.6.5.2/ ./configure make make install ln -s /usr/local/bin/git /usr/bin/git cd / rm /src/git-1.6.5.2.tar.gz rm /src/-rf git-1.6.5.2 gem sources -a http://gemcutter.org gem sources -a http://gems.github.com gem install --no-rdoc --no-ri rails echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" read WANTS_GEMS_PACK -if [ $WANTS_GEMS_PACK == "y" ]; then +if [ $WANTS_GEMS_PACK = "y" ]; then echo "" echo "================================================================" echo "\tInstalling GEMS" echo "================================================================" echo "" gem install --no-rdoc --no-ri authlogic gem install --no-rdoc --no-ri paperclip gem install --no-rdoc --no-ri mysql gem install --no-ri --no-rdoc rmagick gem install --no-ri --no-rdoc chronic gem install --no-ri --no-rdoc geoip gem install --no-ri --no-rdoc daemons gem install --no-ri --no-rdoc hoe gem install --no-ri --no-rdoc echoe gem install --no-ri --no-rdoc ruby-yadis gem install --no-ri --no-rdoc ruby-openid gem install --no-ri --no-rdoc mime-types gem install --no-ri --no-rdoc diff-lcs gem install --no-ri --no-rdoc json gem install --no-ri --no-rdoc rack gem install --no-ri --no-rdoc ruby-hmac gem install --no-ri --no-rdoc rake gem install --no-ri --no-rdoc stompserver gem install --no-ri --no-rdoc passenger gem install --no-ri --no-rdoc hpricot gem install --no-ri --no-rdoc ruby-debug gem install --no-ri --no-rdoc capistrano gem install --no-ri --no-rdoc rspec gem install --no-ri --no-rdoc ZenTest gem install --no-ri --no-rdoc webrat gem install --no-ri --no-rdoc image_science gem install --no-ri --no-rdoc mini_magick gem install --no-ri --no-rdoc mechanize gem install --no-ri --no-rdoc RedCloth gem install --no-ri --no-rdoc fastercsv gem install --no-ri --no-rdoc piston gem install --no-ri --no-rdoc sashimi gem install --no-ri --no-rdoc ruport gem install --no-ri --no-rdoc open4 gem install --no-ri --no-rdoc rubigen gem install --no-ri --no-rdoc sqlite3-ruby gem install --no-ri --no-rdoc mongrel gem install --no-ri --no-rdoc mongrel_service gem install --no-ri --no-rdoc oniguruma gem install --no-ri --no-rdoc ultraviolet gem install --no-ri --no-rdoc libxml-ruby fi echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" read WANTS_GMATE -if [ $WANTS_GMATE == 'y' ]; then +if [ $WANTS_GMATE = 'y' ]; then echo "" echo "================================================================" echo "\tInstalling GMATE Plugins" echo "================================================================" echo "" cd /srv git clone git://github.com/lexrupy/gmate.git cd gmate sh install.sh cd / rm -rf /src/gmate fi echo "Do you'd like setup Apache to works with Passenger? (y/n)" read WANTS_PASSENGER -if [ $WANTS_PASSENGER == 'y' ]; then +if [ $WANTS_PASSENGER = 'y' ]; then echo "" echo "================================================================" echo "\tEnable Passenger" echo "================================================================" echo "" gem install --no-ri --no-rdoc passenger passenger-install-apache2-module echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load a2enmod passenger a2enmod rewrite /etc/init.d/apache2 restart fi echo "" echo "" echo "==================================================" echo "\tServer installation finished" echo "==================================================" \ No newline at end of file
jtadeulopes/Rails-Env-Automatic-Install
be02ecaeee563ae87fdf0b2098c602123fd1ab0d
Remove pyinotify and passenger-install-apache2-module, no longer necessary anymore with karmic koala
diff --git a/development-rails-setup.sh b/development-rails-setup.sh index 304d8c5..ba8a977 100644 --- a/development-rails-setup.sh +++ b/development-rails-setup.sh @@ -1,219 +1,219 @@ #!/bin/bash if [ "$(whoami)" != "root" ]; then echo "You need to be root to run this!" exit 2 fi echo "" echo "================================================================" echo "\tBASIC RAILS DEVELOPMENT SETUP" echo "\tAuthor: Junio Vitorino" echo "\tEmail: [email protected]" echo "\tBlog: http://www.lamiscela.net" echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" echo "================================================================" echo "" echo "" echo "" echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" read START if [ $START == "q" ]; then echo "Installation not started" exit 2 fi echo "" echo "" echo " Starting..." echo "" echo "" echo "" echo "================================================================" echo "\tInstalling compilers" echo "================================================================" echo "" apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev echo "" echo "================================================================" echo "\tInstalling required libraries and packages" echo "================================================================" echo "" -apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg pyinotify passenger-install-apache2-module libapr1-dev libaprutil1-dev memcached +apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg libapr1-dev libaprutil1-dev memcached echo "" echo "================================================================" echo "\tRuby 1.8.7 Patch Level 72" echo "================================================================" echo "" if [ -d /src ] then cd /src else mkdir /src cd /src fi wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null cd ruby-1.8.7-p72 ./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr make make install ln -s /usr/local/bin/ruby /usr/bin/ruby /usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" cd / rm /src/ruby-1.8.7-p72.tar.gz rm -rf /src/ruby-1.8.7-p72 echo "" echo "================================================================" echo "\tRubyGems 1.3.5" echo "================================================================" echo "" cd /src wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz tar xzvf rubygems-1.3.5.tgz cd rubygems-1.3.5/ ruby setup.rb cd / rm /src/rubygems-1.3.5.tgz rm /src/-rf rubygems-1.3.5 echo "" echo "================================================================" echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" echo "================================================================" echo "" apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev echo "" echo "================================================================" echo "\tGIT" echo "================================================================" echo "" cd /src wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz tar -xzvf git-1.6.5.2.tar.gz cd git-1.6.5.2/ ./configure make make install ln -s /usr/local/bin/git /usr/bin/git cd / rm /src/git-1.6.5.2.tar.gz rm /src/-rf git-1.6.5.2 gem sources -a http://gemcutter.org gem sources -a http://gems.github.com gem install --no-rdoc --no-ri rails echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" read WANTS_GEMS_PACK if [ $WANTS_GEMS_PACK == "y" ]; then echo "" echo "================================================================" echo "\tInstalling GEMS" echo "================================================================" echo "" gem install --no-rdoc --no-ri authlogic gem install --no-rdoc --no-ri paperclip gem install --no-rdoc --no-ri mysql gem install --no-ri --no-rdoc rmagick gem install --no-ri --no-rdoc chronic gem install --no-ri --no-rdoc geoip gem install --no-ri --no-rdoc daemons gem install --no-ri --no-rdoc hoe gem install --no-ri --no-rdoc echoe gem install --no-ri --no-rdoc ruby-yadis gem install --no-ri --no-rdoc ruby-openid gem install --no-ri --no-rdoc mime-types gem install --no-ri --no-rdoc diff-lcs gem install --no-ri --no-rdoc json gem install --no-ri --no-rdoc rack gem install --no-ri --no-rdoc ruby-hmac gem install --no-ri --no-rdoc rake gem install --no-ri --no-rdoc stompserver gem install --no-ri --no-rdoc passenger gem install --no-ri --no-rdoc hpricot gem install --no-ri --no-rdoc ruby-debug gem install --no-ri --no-rdoc capistrano gem install --no-ri --no-rdoc rspec gem install --no-ri --no-rdoc ZenTest gem install --no-ri --no-rdoc webrat gem install --no-ri --no-rdoc image_science gem install --no-ri --no-rdoc mini_magick gem install --no-ri --no-rdoc mechanize gem install --no-ri --no-rdoc RedCloth gem install --no-ri --no-rdoc fastercsv gem install --no-ri --no-rdoc piston gem install --no-ri --no-rdoc sashimi gem install --no-ri --no-rdoc ruport gem install --no-ri --no-rdoc open4 gem install --no-ri --no-rdoc rubigen gem install --no-ri --no-rdoc sqlite3-ruby gem install --no-ri --no-rdoc mongrel gem install --no-ri --no-rdoc mongrel_service gem install --no-ri --no-rdoc oniguruma gem install --no-ri --no-rdoc ultraviolet gem install --no-ri --no-rdoc libxml-ruby fi echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" read WANTS_GMATE if [ $WANTS_GMATE == 'y' ]; then echo "" echo "================================================================" echo "\tInstalling GMATE Plugins" echo "================================================================" echo "" cd /srv git clone git://github.com/lexrupy/gmate.git cd gmate sh install.sh cd / rm -rf /src/gmate fi echo "Do you'd like setup Apache to works with Passenger? (y/n)" read WANTS_PASSENGER if [ $WANTS_PASSENGER == 'y' ]; then echo "" echo "================================================================" echo "\tEnable Passenger" echo "================================================================" echo "" gem install --no-ri --no-rdoc passenger passenger-install-apache2-module echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load a2enmod passenger a2enmod rewrite /etc/init.d/apache2 restart fi echo "" echo "" echo "==================================================" echo "\tServer installation finished" echo "==================================================" \ No newline at end of file
jtadeulopes/Rails-Env-Automatic-Install
7e0e16c0d167854e0cfa38839b5e663fe33988f1
First version of script tested
diff --git a/development-rails-setup.sh b/development-rails-setup.sh new file mode 100644 index 0000000..304d8c5 --- /dev/null +++ b/development-rails-setup.sh @@ -0,0 +1,219 @@ +#!/bin/bash + +if [ "$(whoami)" != "root" ]; then +echo "You need to be root to run this!" + exit 2 +fi + +echo "" +echo "================================================================" +echo "\tBASIC RAILS DEVELOPMENT SETUP" +echo "\tAuthor: Junio Vitorino" +echo "\tEmail: [email protected]" +echo "\tBlog: http://www.lamiscela.net" +echo "\tDescription: Basic setup of a Rails development environment using Ubuntu 9.10" +echo "================================================================" +echo "" +echo "" +echo "" + +echo "Do you'd like continue the installation? (y) for condinue or (q) to quit:" +read START +if [ $START == "q" ]; then + echo "Installation not started" + exit 2 +fi + +echo "" +echo "" +echo " Starting..." +echo "" +echo "" + +echo "" +echo "================================================================" +echo "\tInstalling compilers" +echo "================================================================" +echo "" + +apt-get -y install build-essential libssl-dev libreadline6-dev zlib1g zlib1g-dev + + +echo "" +echo "================================================================" +echo "\tInstalling required libraries and packages" +echo "================================================================" +echo "" + +apt-get -y install tcl-dev libexpat-dev libcurl4-openssl-dev apg geoip-bin libgeoip1 libgeoip-dev libsqlite3-dev libpcre3 libpcre3-dev libyaml-dev libmysqlclient15-dev libonig-dev libopenssl-ruby libdbd-mysql-ruby libmysql-ruby libmagick++-dev zip unzip libxml2-dev libxslt1-dev libxslt-ruby libxslt-ruby1.8 libxslt1.1 libxslt1-dev libxslt1-dbg pyinotify passenger-install-apache2-module libapr1-dev libaprutil1-dev memcached + +echo "" +echo "================================================================" +echo "\tRuby 1.8.7 Patch Level 72" +echo "================================================================" +echo "" + +if [ -d /src ] +then + cd /src +else + mkdir /src + cd /src +fi + +wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz +tar -xzvf ruby-1.8.7-p72.tar.gz >> /dev/null +cd ruby-1.8.7-p72 +./configure --prefix=/usr/local --with-openssl-dir=/usr --with-readline-dir=/usr --with-zlib-dir=/usr +make +make install +ln -s /usr/local/bin/ruby /usr/bin/ruby +/usr/local/bin/ruby -ropenssl -rzlib -rreadline -e "puts :success" +cd / +rm /src/ruby-1.8.7-p72.tar.gz +rm -rf /src/ruby-1.8.7-p72 + + +echo "" +echo "================================================================" +echo "\tRubyGems 1.3.5" +echo "================================================================" +echo "" + +cd /src +wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz +tar xzvf rubygems-1.3.5.tgz +cd rubygems-1.3.5/ +ruby setup.rb +cd / +rm /src/rubygems-1.3.5.tgz +rm /src/-rf rubygems-1.3.5 + +echo "" +echo "================================================================" +echo "\tApache2, SQLite3, MySQL5.1, ImageMagick e PHP5" +echo "================================================================" +echo "" + +apt-get -y install mysql-server-5.1 mysql-client-5.1 apache2 php5 php5-mysql sqlite3 php5-sqlite imagemagick libfcgi-dev + +echo "" +echo "================================================================" +echo "\tGIT" +echo "================================================================" +echo "" + +cd /src +wget http://kernel.org/pub/software/scm/git/git-1.6.5.2.tar.gz +tar -xzvf git-1.6.5.2.tar.gz +cd git-1.6.5.2/ +./configure +make +make install +ln -s /usr/local/bin/git /usr/bin/git +cd / +rm /src/git-1.6.5.2.tar.gz +rm /src/-rf git-1.6.5.2 + +gem sources -a http://gemcutter.org +gem sources -a http://gems.github.com + +gem install --no-rdoc --no-ri rails + +echo "Do you would like install a set of gems than in my opinion is very important for a Rails development server? (y/n)" +read WANTS_GEMS_PACK + +if [ $WANTS_GEMS_PACK == "y" ]; then + + echo "" + echo "================================================================" + echo "\tInstalling GEMS" + echo "================================================================" + echo "" + + gem install --no-rdoc --no-ri authlogic + gem install --no-rdoc --no-ri paperclip + gem install --no-rdoc --no-ri mysql + gem install --no-ri --no-rdoc rmagick + gem install --no-ri --no-rdoc chronic + gem install --no-ri --no-rdoc geoip + gem install --no-ri --no-rdoc daemons + gem install --no-ri --no-rdoc hoe + gem install --no-ri --no-rdoc echoe + gem install --no-ri --no-rdoc ruby-yadis + gem install --no-ri --no-rdoc ruby-openid + gem install --no-ri --no-rdoc mime-types + gem install --no-ri --no-rdoc diff-lcs + gem install --no-ri --no-rdoc json + gem install --no-ri --no-rdoc rack + gem install --no-ri --no-rdoc ruby-hmac + gem install --no-ri --no-rdoc rake + gem install --no-ri --no-rdoc stompserver + gem install --no-ri --no-rdoc passenger + gem install --no-ri --no-rdoc hpricot + gem install --no-ri --no-rdoc ruby-debug + gem install --no-ri --no-rdoc capistrano + gem install --no-ri --no-rdoc rspec + gem install --no-ri --no-rdoc ZenTest + gem install --no-ri --no-rdoc webrat + gem install --no-ri --no-rdoc image_science + gem install --no-ri --no-rdoc mini_magick + gem install --no-ri --no-rdoc mechanize + gem install --no-ri --no-rdoc RedCloth + gem install --no-ri --no-rdoc fastercsv + gem install --no-ri --no-rdoc piston + gem install --no-ri --no-rdoc sashimi + gem install --no-ri --no-rdoc ruport + gem install --no-ri --no-rdoc open4 + gem install --no-ri --no-rdoc rubigen + gem install --no-ri --no-rdoc sqlite3-ruby + gem install --no-ri --no-rdoc mongrel + gem install --no-ri --no-rdoc mongrel_service + gem install --no-ri --no-rdoc oniguruma + gem install --no-ri --no-rdoc ultraviolet + gem install --no-ri --no-rdoc libxml-ruby +fi + +echo "Do you'd like install GMATE set of plugins for GEdit editor? (y/n)" +read WANTS_GMATE + +if [ $WANTS_GMATE == 'y' ]; then + echo "" + echo "================================================================" + echo "\tInstalling GMATE Plugins" + echo "================================================================" + echo "" + cd /srv + git clone git://github.com/lexrupy/gmate.git + cd gmate + sh install.sh + cd / + rm -rf /src/gmate +fi + +echo "Do you'd like setup Apache to works with Passenger? (y/n)" +read WANTS_PASSENGER + +if [ $WANTS_PASSENGER == 'y' ]; then + + echo "" + echo "================================================================" + echo "\tEnable Passenger" + echo "================================================================" + echo "" + + gem install --no-ri --no-rdoc passenger + passenger-install-apache2-module + echo "LoadModule passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so + PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5 + PassengerRuby /usr/local/bin/ruby" >> /etc/apache2/mods-available/passenger.load + a2enmod passenger + a2enmod rewrite + /etc/init.d/apache2 restart +fi + +echo "" +echo "" +echo "==================================================" +echo "\tServer installation finished" +echo "==================================================" \ No newline at end of file
radekp/qdictopia
49f857ef8bc2568e105e9259a2e9e9bed51b2570
Debian package
diff --git a/debian/README.Debian b/debian/README.Debian new file mode 100644 index 0000000..4773f72 --- /dev/null +++ b/debian/README.Debian @@ -0,0 +1,6 @@ +qtmoko for Debian +----------------- + +<possible notes regarding this package - if none, delete this file> + + -- Radek Polak <[email protected]> Sat, 05 Feb 2011 20:23:56 +0100 diff --git a/debian/README.source b/debian/README.source new file mode 100644 index 0000000..863f73e --- /dev/null +++ b/debian/README.source @@ -0,0 +1,9 @@ +qtmoko for Debian +----------------- + +<this file describes information about the source package, see Debian policy +manual section 4.14. You WILL either need to modify or delete this file> + + + + diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..c4d704e --- /dev/null +++ b/debian/changelog @@ -0,0 +1,5 @@ +qtmoko-dictopia (32-1) unstable; urgency=low + + * Initial release + + -- Radek Polak <[email protected]> Sat, 05 Feb 2011 20:23:56 +0100 diff --git a/debian/compat b/debian/compat new file mode 100644 index 0000000..7f8f011 --- /dev/null +++ b/debian/compat @@ -0,0 +1 @@ +7 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..0abdf17 --- /dev/null +++ b/debian/control @@ -0,0 +1,14 @@ +Source: qtmoko-dictopia +Section: comm +Priority: optional +Maintainer: Radek Polak <[email protected]> +Build-Depends: debhelper (>= 7.0.50~) +Standards-Version: 3.8.4 +Homepage: http://www.qtmoko.org +Vcs-Git: git://github.com/radekp/qtmoko.git +Vcs-Browser: https://github.com/radekp/qtmoko + +Package: qtmoko-dictopia +Architecture: any +Depends: +Description: Offline English dictionary compatible with StarDict diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..5421fbc --- /dev/null +++ b/debian/copyright @@ -0,0 +1,27 @@ +This work was packaged for Debian by: + + Radek Polak <[email protected]> on Sat, 05 Feb 2011 20:23:56 +0100 + +It was downloaded from: + + http://sourceforge.net/projects/qtmoko/files + +Upstream Author(s): + + Radek Polak <[email protected]> + +Copyright: + + Copyright (C) 2009 Trolltech ASA. <[email protected]> + Copyright (C) 2011 Radek Polak <[email protected]> + +License: + + GPL-2+ + +The Debian packaging is: + + Copyright (C) 2011 Radek Polak <[email protected]> + +and is licensed under the GPL version 2, +see "/usr/share/common-licenses/GPL-2". diff --git a/debian/docs b/debian/docs new file mode 100644 index 0000000..e69de29 diff --git a/debian/emacsen-install.ex b/debian/emacsen-install.ex new file mode 100644 index 0000000..797f539 --- /dev/null +++ b/debian/emacsen-install.ex @@ -0,0 +1,45 @@ +#! /bin/sh -e +# /usr/lib/emacsen-common/packages/install/qtmoko + +# Written by Jim Van Zandt <[email protected]>, borrowing heavily +# from the install scripts for gettext by Santiago Vila +# <[email protected]> and octave by Dirk Eddelbuettel <[email protected]>. + +FLAVOR=$1 +PACKAGE=qtmoko + +if [ ${FLAVOR} = emacs ]; then exit 0; fi + +echo install/${PACKAGE}: Handling install for emacsen flavor ${FLAVOR} + +#FLAVORTEST=`echo $FLAVOR | cut -c-6` +#if [ ${FLAVORTEST} = xemacs ] ; then +# SITEFLAG="-no-site-file" +#else +# SITEFLAG="--no-site-file" +#fi +FLAGS="${SITEFLAG} -q -batch -l path.el -f batch-byte-compile" + +ELDIR=/usr/share/emacs/site-lisp/${PACKAGE} +ELCDIR=/usr/share/${FLAVOR}/site-lisp/${PACKAGE} + +# Install-info-altdir does not actually exist. +# Maybe somebody will write it. +if test -x /usr/sbin/install-info-altdir; then + echo install/${PACKAGE}: install Info links for ${FLAVOR} + install-info-altdir --quiet --section "" "" --dirname=${FLAVOR} /usr/share/info/${PACKAGE}.info.gz +fi + +install -m 755 -d ${ELCDIR} +cd ${ELDIR} +FILES=`echo *.el` +cp ${FILES} ${ELCDIR} +cd ${ELCDIR} + +cat << EOF > path.el +(setq load-path (cons "." load-path) byte-compile-warnings nil) +EOF +${FLAVOR} ${FLAGS} ${FILES} +rm -f *.el path.el + +exit 0 diff --git a/debian/emacsen-remove.ex b/debian/emacsen-remove.ex new file mode 100644 index 0000000..393d7e5 --- /dev/null +++ b/debian/emacsen-remove.ex @@ -0,0 +1,15 @@ +#!/bin/sh -e +# /usr/lib/emacsen-common/packages/remove/qtmoko + +FLAVOR=$1 +PACKAGE=qtmoko + +if [ ${FLAVOR} != emacs ]; then + if test -x /usr/sbin/install-info-altdir; then + echo remove/${PACKAGE}: removing Info links for ${FLAVOR} + install-info-altdir --quiet --remove --dirname=${FLAVOR} /usr/share/info/qtmoko.info.gz + fi + + echo remove/${PACKAGE}: purging byte-compiled files for ${FLAVOR} + rm -rf /usr/share/${FLAVOR}/site-lisp/${PACKAGE} +fi diff --git a/debian/emacsen-startup.ex b/debian/emacsen-startup.ex new file mode 100644 index 0000000..b961daa --- /dev/null +++ b/debian/emacsen-startup.ex @@ -0,0 +1,25 @@ +;; -*-emacs-lisp-*- +;; +;; Emacs startup file, e.g. /etc/emacs/site-start.d/50qtmoko.el +;; for the Debian qtmoko package +;; +;; Originally contributed by Nils Naumann <[email protected]> +;; Modified by Dirk Eddelbuettel <[email protected]> +;; Adapted for dh-make by Jim Van Zandt <[email protected]> + +;; The qtmoko package follows the Debian/GNU Linux 'emacsen' policy and +;; byte-compiles its elisp files for each 'emacs flavor' (emacs19, +;; xemacs19, emacs20, xemacs20...). The compiled code is then +;; installed in a subdirectory of the respective site-lisp directory. +;; We have to add this to the load-path: +(let ((package-dir (concat "/usr/share/" + (symbol-name flavor) + "/site-lisp/qtmoko"))) +;; If package-dir does not exist, the qtmoko package must have +;; removed but not purged, and we should skip the setup. + (when (file-directory-p package-dir) + (setq load-path (cons package-dir load-path)) + (autoload 'qtmoko-mode "qtmoko-mode" + "Major mode for editing qtmoko files." t) + (add-to-list 'auto-mode-alist '("\\.qtmoko$" . qtmoko-mode)))) + diff --git a/debian/init.d.ex b/debian/init.d.ex new file mode 100644 index 0000000..12d0e51 --- /dev/null +++ b/debian/init.d.ex @@ -0,0 +1,154 @@ +#!/bin/sh +### BEGIN INIT INFO +# Provides: qtmoko +# Required-Start: $network $local_fs +# Required-Stop: +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: <Enter a short description of the sortware> +# Description: <Enter a long description of the software> +# <...> +# <...> +### END INIT INFO + +# Author: Radek Polak <[email protected]> + +# PATH should only include /usr/* if it runs after the mountnfs.sh script +PATH=/sbin:/usr/sbin:/bin:/usr/bin +DESC=qtmoko # Introduce a short description here +NAME=qtmoko # Introduce the short server's name here +DAEMON=/usr/sbin/qtmoko # Introduce the server's location here +DAEMON_ARGS="" # Arguments to run the daemon with +PIDFILE=/var/run/$NAME.pid +SCRIPTNAME=/etc/init.d/$NAME + +# Exit if the package is not installed +[ -x $DAEMON ] || exit 0 + +# Read configuration variable file if it is present +[ -r /etc/default/$NAME ] && . /etc/default/$NAME + +# Load the VERBOSE setting and other rcS variables +. /lib/init/vars.sh + +# Define LSB log_* functions. +# Depend on lsb-base (>= 3.0-6) to ensure that this file is present. +. /lib/lsb/init-functions + +# +# Function that starts the daemon/service +# +do_start() +{ + # Return + # 0 if daemon has been started + # 1 if daemon was already running + # 2 if daemon could not be started + start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \ + || return 1 + start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \ + $DAEMON_ARGS \ + || return 2 + # Add code here, if necessary, that waits for the process to be ready + # to handle requests from services started subsequently which depend + # on this one. As a last resort, sleep for some time. +} + +# +# Function that stops the daemon/service +# +do_stop() +{ + # Return + # 0 if daemon has been stopped + # 1 if daemon was already stopped + # 2 if daemon could not be stopped + # other if a failure occurred + start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME + RETVAL="$?" + [ "$RETVAL" = 2 ] && return 2 + # Wait for children to finish too if this is a daemon that forks + # and if the daemon is only ever run from this initscript. + # If the above conditions are not satisfied then add some other code + # that waits for the process to drop all resources that could be + # needed by services started subsequently. A last resort is to + # sleep for some time. + start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON + [ "$?" = 2 ] && return 2 + # Many daemons don't delete their pidfiles when they exit. + rm -f $PIDFILE + return "$RETVAL" +} + +# +# Function that sends a SIGHUP to the daemon/service +# +do_reload() { + # + # If the daemon can reload its configuration without + # restarting (for example, when it is sent a SIGHUP), + # then implement that here. + # + start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME + return 0 +} + +case "$1" in + start) + [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC " "$NAME" + do_start + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + stop) + [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" + do_stop + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + status) + status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? + ;; + #reload|force-reload) + # + # If do_reload() is not implemented then leave this commented out + # and leave 'force-reload' as an alias for 'restart'. + # + #log_daemon_msg "Reloading $DESC" "$NAME" + #do_reload + #log_end_msg $? + #;; + restart|force-reload) + # + # If the "reload" option is implemented then remove the + # 'force-reload' alias + # + log_daemon_msg "Restarting $DESC" "$NAME" + do_stop + case "$?" in + 0|1) + do_start + case "$?" in + 0) log_end_msg 0 ;; + 1) log_end_msg 1 ;; # Old process is still running + *) log_end_msg 1 ;; # Failed to start + esac + ;; + *) + # Failed to stop + log_end_msg 1 + ;; + esac + ;; + *) + #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 + echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 + exit 3 + ;; +esac + +: diff --git a/debian/manpage.1.ex b/debian/manpage.1.ex new file mode 100644 index 0000000..d9febf1 --- /dev/null +++ b/debian/manpage.1.ex @@ -0,0 +1,59 @@ +.\" Hey, EMACS: -*- nroff -*- +.\" First parameter, NAME, should be all caps +.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection +.\" other parameters are allowed: see man(7), man(1) +.TH QTMOKO SECTION "February 5, 2011" +.\" Please adjust this date whenever revising the manpage. +.\" +.\" Some roff macros, for reference: +.\" .nh disable hyphenation +.\" .hy enable hyphenation +.\" .ad l left justify +.\" .ad b justify to both left and right margins +.\" .nf disable filling +.\" .fi enable filling +.\" .br insert line break +.\" .sp <n> insert n+1 empty lines +.\" for manpage-specific macros, see man(7) +.SH NAME +qtmoko \- program to do something +.SH SYNOPSIS +.B qtmoko +.RI [ options ] " files" ... +.br +.B bar +.RI [ options ] " files" ... +.SH DESCRIPTION +This manual page documents briefly the +.B qtmoko +and +.B bar +commands. +.PP +.\" TeX users may be more comfortable with the \fB<whatever>\fP and +.\" \fI<whatever>\fP escape sequences to invode bold face and italics, +.\" respectively. +\fBqtmoko\fP is a program that... +.SH OPTIONS +These programs follow the usual GNU command line syntax, with long +options starting with two dashes (`-'). +A summary of options is included below. +For a complete description, see the Info files. +.TP +.B \-h, \-\-help +Show summary of options. +.TP +.B \-v, \-\-version +Show version of program. +.SH SEE ALSO +.BR bar (1), +.BR baz (1). +.br +The programs are documented fully by +.IR "The Rise and Fall of a Fooish Bar" , +available via the Info system. +.SH AUTHOR +qtmoko was written by <upstream author>. +.PP +This manual page was written by Radek Polak <[email protected]>, +for the Debian project (and may be used by others). diff --git a/debian/manpage.sgml.ex b/debian/manpage.sgml.ex new file mode 100644 index 0000000..d58bc1a --- /dev/null +++ b/debian/manpage.sgml.ex @@ -0,0 +1,154 @@ +<!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN" [ + +<!-- Process this file with docbook-to-man to generate an nroff manual + page: `docbook-to-man manpage.sgml > manpage.1'. You may view + the manual page with: `docbook-to-man manpage.sgml | nroff -man | + less'. A typical entry in a Makefile or Makefile.am is: + +manpage.1: manpage.sgml + docbook-to-man $< > $@ + + + The docbook-to-man binary is found in the docbook-to-man package. + Please remember that if you create the nroff version in one of the + debian/rules file targets (such as build), you will need to include + docbook-to-man in your Build-Depends control field. + + --> + + <!-- Fill in your name for FIRSTNAME and SURNAME. --> + <!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>"> + <!ENTITY dhsurname "<surname>SURNAME</surname>"> + <!-- Please adjust the date whenever revising the manpage. --> + <!ENTITY dhdate "<date>February 5, 2011</date>"> + <!-- SECTION should be 1-8, maybe w/ subsection other parameters are + allowed: see man(7), man(1). --> + <!ENTITY dhsection "<manvolnum>SECTION</manvolnum>"> + <!ENTITY dhemail "<email>[email protected]</email>"> + <!ENTITY dhusername "Radek Polak"> + <!ENTITY dhucpackage "<refentrytitle>QTMOKO</refentrytitle>"> + <!ENTITY dhpackage "qtmoko"> + + <!ENTITY debian "<productname>Debian</productname>"> + <!ENTITY gnu "<acronym>GNU</acronym>"> + <!ENTITY gpl "&gnu; <acronym>GPL</acronym>"> +]> + +<refentry> + <refentryinfo> + <address> + &dhemail; + </address> + <author> + &dhfirstname; + &dhsurname; + </author> + <copyright> + <year>2003</year> + <holder>&dhusername;</holder> + </copyright> + &dhdate; + </refentryinfo> + <refmeta> + &dhucpackage; + + &dhsection; + </refmeta> + <refnamediv> + <refname>&dhpackage;</refname> + + <refpurpose>program to do something</refpurpose> + </refnamediv> + <refsynopsisdiv> + <cmdsynopsis> + <command>&dhpackage;</command> + + <arg><option>-e <replaceable>this</replaceable></option></arg> + + <arg><option>--example <replaceable>that</replaceable></option></arg> + </cmdsynopsis> + </refsynopsisdiv> + <refsect1> + <title>DESCRIPTION</title> + + <para>This manual page documents briefly the + <command>&dhpackage;</command> and <command>bar</command> + commands.</para> + + <para>This manual page was written for the &debian; distribution + because the original program does not have a manual page. + Instead, it has documentation in the &gnu; + <application>Info</application> format; see below.</para> + + <para><command>&dhpackage;</command> is a program that...</para> + + </refsect1> + <refsect1> + <title>OPTIONS</title> + + <para>These programs follow the usual &gnu; command line syntax, + with long options starting with two dashes (`-'). A summary of + options is included below. For a complete description, see the + <application>Info</application> files.</para> + + <variablelist> + <varlistentry> + <term><option>-h</option> + <option>--help</option> + </term> + <listitem> + <para>Show summary of options.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><option>-v</option> + <option>--version</option> + </term> + <listitem> + <para>Show version of program.</para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + <refsect1> + <title>SEE ALSO</title> + + <para>bar (1), baz (1).</para> + + <para>The programs are documented fully by <citetitle>The Rise and + Fall of a Fooish Bar</citetitle> available via the + <application>Info</application> system.</para> + </refsect1> + <refsect1> + <title>AUTHOR</title> + + <para>This manual page was written by &dhusername; &dhemail; for + the &debian; system (and may be used by others). Permission is + granted to copy, distribute and/or modify this document under + the terms of the &gnu; General Public License, Version 2 any + later version published by the Free Software Foundation. + </para> + <para> + On Debian systems, the complete text of the GNU General Public + License can be found in /usr/share/common-licenses/GPL. + </para> + + </refsect1> +</refentry> + +<!-- Keep this comment at the end of the file +Local variables: +mode: sgml +sgml-omittag:t +sgml-shorttag:t +sgml-minimize-attributes:nil +sgml-always-quote-attributes:t +sgml-indent-step:2 +sgml-indent-data:t +sgml-parent-document:nil +sgml-default-dtd-file:nil +sgml-exposed-tags:nil +sgml-local-catalogs:nil +sgml-local-ecat-files:nil +End: +--> diff --git a/debian/manpage.xml.ex b/debian/manpage.xml.ex new file mode 100644 index 0000000..ae3d100 --- /dev/null +++ b/debian/manpage.xml.ex @@ -0,0 +1,291 @@ +<?xml version='1.0' encoding='UTF-8'?> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" +"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ + +<!-- + +`xsltproc -''-nonet \ + -''-param man.charmap.use.subset "0" \ + -''-param make.year.ranges "1" \ + -''-param make.single.year.ranges "1" \ + /usr/share/xml/docbook/stylesheet/docbook-xsl/manpages/docbook.xsl \ + manpage.xml' + +A manual page <package>.<section> will be generated. You may view the +manual page with: nroff -man <package>.<section> | less'. A typical entry +in a Makefile or Makefile.am is: + +DB2MAN = /usr/share/sgml/docbook/stylesheet/xsl/docbook-xsl/manpages/docbook.xsl +XP = xsltproc -''-nonet -''-param man.charmap.use.subset "0" + +manpage.1: manpage.xml + $(XP) $(DB2MAN) $< + +The xsltproc binary is found in the xsltproc package. The XSL files are in +docbook-xsl. A description of the parameters you can use can be found in the +docbook-xsl-doc-* packages. Please remember that if you create the nroff +version in one of the debian/rules file targets (such as build), you will need +to include xsltproc and docbook-xsl in your Build-Depends control field. +Alternatively use the xmlto command/package. That will also automatically +pull in xsltproc and docbook-xsl. + +Notes for using docbook2x: docbook2x-man does not automatically create the +AUTHOR(S) and COPYRIGHT sections. In this case, please add them manually as +<refsect1> ... </refsect1>. + +To disable the automatic creation of the AUTHOR(S) and COPYRIGHT sections +read /usr/share/doc/docbook-xsl/doc/manpages/authors.html. This file can be +found in the docbook-xsl-doc-html package. + +Validation can be done using: `xmllint -''-noout -''-valid manpage.xml` + +General documentation about man-pages and man-page-formatting: +man(1), man(7), http://www.tldp.org/HOWTO/Man-Page/ + +--> + + <!-- Fill in your name for FIRSTNAME and SURNAME. --> + <!ENTITY dhfirstname "FIRSTNAME"> + <!ENTITY dhsurname "SURNAME"> + <!-- dhusername could also be set to "&dhfirstname; &dhsurname;". --> + <!ENTITY dhusername "Radek Polak"> + <!ENTITY dhemail "[email protected]"> + <!-- SECTION should be 1-8, maybe w/ subsection other parameters are + allowed: see man(7), man(1) and + http://www.tldp.org/HOWTO/Man-Page/q2.html. --> + <!ENTITY dhsection "SECTION"> + <!-- TITLE should be something like "User commands" or similar (see + http://www.tldp.org/HOWTO/Man-Page/q2.html). --> + <!ENTITY dhtitle "qtmoko User Manual"> + <!ENTITY dhucpackage "QTMOKO"> + <!ENTITY dhpackage "qtmoko"> +]> + +<refentry> + <refentryinfo> + <title>&dhtitle;</title> + <productname>&dhpackage;</productname> + <authorgroup> + <author> + <firstname>&dhfirstname;</firstname> + <surname>&dhsurname;</surname> + <contrib>Wrote this manpage for the Debian system.</contrib> + <address> + <email>&dhemail;</email> + </address> + </author> + </authorgroup> + <copyright> + <year>2007</year> + <holder>&dhusername;</holder> + </copyright> + <legalnotice> + <para>This manual page was written for the Debian system + (and may be used by others).</para> + <para>Permission is granted to copy, distribute and/or modify this + document under the terms of the GNU General Public License, + Version 2 or (at your option) any later version published by + the Free Software Foundation.</para> + <para>On Debian systems, the complete text of the GNU General Public + License can be found in + <filename>/usr/share/common-licenses/GPL</filename>.</para> + </legalnotice> + </refentryinfo> + <refmeta> + <refentrytitle>&dhucpackage;</refentrytitle> + <manvolnum>&dhsection;</manvolnum> + </refmeta> + <refnamediv> + <refname>&dhpackage;</refname> + <refpurpose>program to do something</refpurpose> + </refnamediv> + <refsynopsisdiv> + <cmdsynopsis> + <command>&dhpackage;</command> + <!-- These are several examples, how syntaxes could look --> + <arg choice="plain"><option>-e <replaceable>this</replaceable></option></arg> + <arg choice="opt"><option>--example=<parameter>that</parameter></option></arg> + <arg choice="opt"> + <group choice="req"> + <arg choice="plain"><option>-e</option></arg> + <arg choice="plain"><option>--example</option></arg> + </group> + <replaceable class="option">this</replaceable> + </arg> + <arg choice="opt"> + <group choice="req"> + <arg choice="plain"><option>-e</option></arg> + <arg choice="plain"><option>--example</option></arg> + </group> + <group choice="req"> + <arg choice="plain"><replaceable>this</replaceable></arg> + <arg choice="plain"><replaceable>that</replaceable></arg> + </group> + </arg> + </cmdsynopsis> + <cmdsynopsis> + <command>&dhpackage;</command> + <!-- Normally the help and version options make the programs stop + right after outputting the requested information. --> + <group choice="opt"> + <arg choice="plain"> + <group choice="req"> + <arg choice="plain"><option>-h</option></arg> + <arg choice="plain"><option>--help</option></arg> + </group> + </arg> + <arg choice="plain"> + <group choice="req"> + <arg choice="plain"><option>-v</option></arg> + <arg choice="plain"><option>--version</option></arg> + </group> + </arg> + </group> + </cmdsynopsis> + </refsynopsisdiv> + <refsect1 id="description"> + <title>DESCRIPTION</title> + <para>This manual page documents briefly the + <command>&dhpackage;</command> and <command>bar</command> + commands.</para> + <para>This manual page was written for the Debian distribution + because the original program does not have a manual page. + Instead, it has documentation in the GNU <citerefentry> + <refentrytitle>info</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry> format; see below.</para> + <para><command>&dhpackage;</command> is a program that...</para> + </refsect1> + <refsect1 id="options"> + <title>OPTIONS</title> + <para>The program follows the usual GNU command line syntax, + with long options starting with two dashes (`-'). A summary of + options is included below. For a complete description, see the + <citerefentry> + <refentrytitle>info</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry> files.</para> + <variablelist> + <!-- Use the variablelist.term.separator and the + variablelist.term.break.after parameters to + control the term elements. --> + <varlistentry> + <term><option>-e <replaceable>this</replaceable></option></term> + <term><option>--example=<replaceable>that</replaceable></option></term> + <listitem> + <para>Does this and that.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><option>-h</option></term> + <term><option>--help</option></term> + <listitem> + <para>Show summary of options.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><option>-v</option></term> + <term><option>--version</option></term> + <listitem> + <para>Show version of program.</para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + <refsect1 id="files"> + <title>FILES</title> + <variablelist> + <varlistentry> + <term><filename>/etc/foo.conf</filename></term> + <listitem> + <para>The system-wide configuration file to control the + behaviour of <application>&dhpackage;</application>. See + <citerefentry> + <refentrytitle>foo.conf</refentrytitle> + <manvolnum>5</manvolnum> + </citerefentry> for further details.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><filename>${HOME}/.foo.conf</filename></term> + <listitem> + <para>The per-user configuration file to control the + behaviour of <application>&dhpackage;</application>. See + <citerefentry> + <refentrytitle>foo.conf</refentrytitle> + <manvolnum>5</manvolnum> + </citerefentry> for further details.</para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + <refsect1 id="environment"> + <title>ENVIONMENT</title> + <variablelist> + <varlistentry> + <term><envar>FOO_CONF</envar></term> + <listitem> + <para>If used, the defined file is used as configuration + file (see also <xref linkend="files"/>).</para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + <refsect1 id="diagnostics"> + <title>DIAGNOSTICS</title> + <para>The following diagnostics may be issued + on <filename class="devicefile">stderr</filename>:</para> + <variablelist> + <varlistentry> + <term><errortext>Bad configuration file. Exiting.</errortext></term> + <listitem> + <para>The configuration file seems to contain a broken configuration + line. Use the <option>--verbose</option> option, to get more info. + </para> + </listitem> + </varlistentry> + </variablelist> + <para><command>&dhpackage;</command> provides some return codes, that can + be used in scripts:</para> + <segmentedlist> + <segtitle>Code</segtitle> + <segtitle>Diagnostic</segtitle> + <seglistitem> + <seg><errorcode>0</errorcode></seg> + <seg>Program exited successfully.</seg> + </seglistitem> + <seglistitem> + <seg><errorcode>1</errorcode></seg> + <seg>The configuration file seems to be broken.</seg> + </seglistitem> + </segmentedlist> + </refsect1> + <refsect1 id="bugs"> + <!-- Or use this section to tell about upstream BTS. --> + <title>BUGS</title> + <para>The program is currently limited to only work + with the <package>foobar</package> library.</para> + <para>The upstreams <acronym>BTS</acronym> can be found + at <ulink url="http://bugzilla.foo.tld"/>.</para> + </refsect1> + <refsect1 id="see_also"> + <title>SEE ALSO</title> + <!-- In alpabetical order. --> + <para><citerefentry> + <refentrytitle>bar</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry>, <citerefentry> + <refentrytitle>baz</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry>, <citerefentry> + <refentrytitle>foo.conf</refentrytitle> + <manvolnum>5</manvolnum> + </citerefentry></para> + <para>The programs are documented fully by <citetitle>The Rise and + Fall of a Fooish Bar</citetitle> available via the <citerefentry> + <refentrytitle>info</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry> system.</para> + </refsect1> +</refentry> + diff --git a/debian/menu.ex b/debian/menu.ex new file mode 100644 index 0000000..0a1414a --- /dev/null +++ b/debian/menu.ex @@ -0,0 +1,2 @@ +?package(qtmoko):needs="X11|text|vc|wm" section="Applications/see-menu-manual"\ + title="qtmoko" command="/usr/bin/qtmoko" diff --git a/debian/postinst b/debian/postinst new file mode 100755 index 0000000..4d4b03d --- /dev/null +++ b/debian/postinst @@ -0,0 +1,42 @@ +#!/bin/sh +# postinst script for qtmoko +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * <postinst> `configure' <most-recently-configured-version> +# * <old-postinst> `abort-upgrade' <new version> +# * <conflictor's-postinst> `abort-remove' `in-favour' <package> +# <new-version> +# * <postinst> `abort-remove' +# * <deconfigured's-postinst> `abort-deconfigure' `in-favour' +# <failed-install-package> <version> `removing' +# <conflicting-package> <version> +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + configure) + # rescan .desktop files so that we appear on the list + . /opt/qtmoko/qpe.env + qcop QPE/DocAPI 'scanPath(QString,int)' /opt/qtmoko/apps/Applications 1 + ;; + + abort-upgrade|abort-remove|abort-deconfigure) + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/debian/postrm b/debian/postrm new file mode 100755 index 0000000..41272f0 --- /dev/null +++ b/debian/postrm @@ -0,0 +1,40 @@ +#!/bin/sh +# postrm script for qtmoko +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * <postrm> `remove' +# * <postrm> `purge' +# * <old-postrm> `upgrade' <new-version> +# * <new-postrm> `failed-upgrade' <old-version> +# * <new-postrm> `abort-install' +# * <new-postrm> `abort-install' <old-version> +# * <new-postrm> `abort-upgrade' <old-version> +# * <disappearer's-postrm> `disappear' <overwriter> +# <overwriter-version> +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear) + # rescan .desktop files so that we disappear from the list + . /opt/qtmoko/qpe.env + qcop QPE/DocAPI 'scanPath(QString,int)' /opt/qtmoko/apps/Applications 1 + ;; + + *) + echo "postrm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/debian/preinst.ex b/debian/preinst.ex new file mode 100644 index 0000000..6c032f9 --- /dev/null +++ b/debian/preinst.ex @@ -0,0 +1,35 @@ +#!/bin/sh +# preinst script for qtmoko +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * <new-preinst> `install' +# * <new-preinst> `install' <old-version> +# * <new-preinst> `upgrade' <old-version> +# * <old-preinst> `abort-upgrade' <new-version> +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + install|upgrade) + ;; + + abort-upgrade) + ;; + + *) + echo "preinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/debian/prerm.ex b/debian/prerm.ex new file mode 100644 index 0000000..c61eb64 --- /dev/null +++ b/debian/prerm.ex @@ -0,0 +1,38 @@ +#!/bin/sh +# prerm script for qtmoko +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * <prerm> `remove' +# * <old-prerm> `upgrade' <new-version> +# * <new-prerm> `failed-upgrade' <old-version> +# * <conflictor's-prerm> `remove' `in-favour' <package> <new-version> +# * <deconfigured's-prerm> `deconfigure' `in-favour' +# <package-being-installed> <version> `removing' +# <conflicting-package> <version> +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + remove|upgrade|deconfigure) + ;; + + failed-upgrade) + ;; + + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/debian/qtmoko-qgcide.debhelper.log b/debian/qtmoko-qgcide.debhelper.log new file mode 100644 index 0000000..c658307 --- /dev/null +++ b/debian/qtmoko-qgcide.debhelper.log @@ -0,0 +1,2 @@ +dh_installdeb +dh_installdeb diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000..a5e620f --- /dev/null +++ b/debian/rules @@ -0,0 +1,21 @@ +#!/usr/bin/make -f + +build: + +clean: + rm -rf debian/tmp + rm -f debian/files + +binary: build + ../../../build/bin/qbuild packages + mkdir -p debian/tmp/opt/qtmoko + cd debian/tmp/opt/qtmoko && tar xzvpf ../../../../../../../build/qtmoko-apps/qdictopia/pkg/* + cd debian/tmp/opt/qtmoko && tar xzvpf data.tar.gz + cd debian/tmp/opt/qtmoko && rm -f control + cd debian/tmp/opt/qtmoko && rm -f data.tar.gz + install -d debian/tmp/DEBIAN + dpkg-gencontrol + dh_installdeb -P debian/tmp + chown -R root:root debian/tmp/opt + chmod -R u+w,go=rX debian/tmp/opt + dpkg --build debian/tmp .. diff --git a/debian/substvars b/debian/substvars new file mode 100644 index 0000000..6f4ae5b --- /dev/null +++ b/debian/substvars @@ -0,0 +1 @@ +shlibs:Depends=libc6 (>= 2.3.4) diff --git a/debian/watch.ex b/debian/watch.ex new file mode 100644 index 0000000..1fe4561 --- /dev/null +++ b/debian/watch.ex @@ -0,0 +1,23 @@ +# Example watch control file for uscan +# Rename this file to "watch" and then you can run the "uscan" command +# to check for upstream updates and more. +# See uscan(1) for format + +# Compulsory line, this is a version 3 file +version=3 + +# Uncomment to examine a Webpage +# <Webpage URL> <string match> +#http://www.example.com/downloads.php qtmoko-(.*)\.tar\.gz + +# Uncomment to examine a Webserver directory +#http://www.example.com/pub/qtmoko-(.*)\.tar\.gz + +# Uncommment to examine a FTP server +#ftp://ftp.example.com/pub/qtmoko-(.*)\.tar\.gz debian uupdate + +# Uncomment to find new files on sourceforge, for devscripts >= 2.9 +# http://sf.net/qtmoko/qtmoko-(.*)\.tar\.gz + +# Uncomment to find new files on GooglePages +# http://example.googlepages.com/foo.html qtmoko-(.*)\.tar\.gz
radekp/qdictopia
52f48b488e797e2fccc97b564997d5f3b2442478
Use qtopia menu
diff --git a/src/qdictopia.cpp b/src/qdictopia.cpp index af171e7..a1b5400 100644 --- a/src/qdictopia.cpp +++ b/src/qdictopia.cpp @@ -1,10 +1,14 @@ #include "qdictopia.h" QDictOpia::QDictOpia(QWidget* parent, Qt::WindowFlags flags) : QMainWindow(parent, flags) { setWindowTitle(tr("QDictopia")); +#ifdef QTOPIA + QMenu *menu = QSoftMenuBar::menuFor(this); +#else QMenu *menu = menuBar()->addMenu("&File"); +#endif mMainWindow = new MainWindow(this, 0, menu); setCentralWidget(mMainWindow); } diff --git a/src/qdictopia.h b/src/qdictopia.h index b293190..833cd38 100644 --- a/src/qdictopia.h +++ b/src/qdictopia.h @@ -1,18 +1,20 @@ #ifndef _QDICTOPIA_H_ #define _QDICTOPIA_H_ #include <QMainWindow> #include <QMenuBar> - +#ifdef QTOPIA +#include <QSoftMenuBar> +#endif #include "mainwindow.h" class QDictOpia : public QMainWindow { public: QDictOpia(QWidget* parent = 0, Qt::WindowFlags flags = 0); private: MainWindow* mMainWindow; }; #endif
radekp/qdictopia
0c772285b1771abfd1d39c2bb9fd9b330555b4dd
Fix input methods blinking by showing word as dialog.
diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index fa462c5..d9ef3a4 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,164 +1,171 @@ #include <QMessageBox> #include <QTimer> +#ifdef QTOPIA +#include <QtopiaApplication> +#endif #include "mainwindow.h" MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags f, QMenu *menu) : QWidget(parent, f), mLineEdit(NULL) { #ifdef QTOPIA Q_UNUSED(menu); #endif if (loadDicts() == false) { QTimer::singleShot(0, this, SLOT(slotWarning())); } else { // Build UI mLayout = new QGridLayout(this); mLineEdit = new QLineEdit(this); //mLineEdit->setFocusPolicy(Qt::NoFocus); connect(mLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(slotTextChanged(const QString&))); #ifdef QTOPIA mMenu = QSoftMenuBar::menuFor(mLineEdit); #else mMenu = menu; #endif mActionClear = mMenu->addAction(tr("Clear text"), this, SLOT(slotClearText())); mActionClear->setVisible(false); mActionDList = mMenu->addAction(tr("Dictionaries..."), this, SLOT(slotDictList())); mListWidget = new QListWidget(this); mListWidget->setFocusPolicy(Qt::NoFocus); connect(mListWidget, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(slotItemActivated(QListWidgetItem*))); mLayout->addWidget(mLineEdit, 0, 0); mLayout->addWidget(mListWidget, 1, 0); } } MainWindow::~MainWindow() { if (mLibs) delete mLibs; } void MainWindow::keyPressEvent(QKeyEvent* event) { switch(event->key()) { case Qt::Key_Up: if (mListWidget->count() > 0) { if (mListWidget->currentRow() <= 0) mListWidget->setCurrentRow(mListWidget->count() - 1); else mListWidget->setCurrentRow(mListWidget->currentRow() - 1); } break; case Qt::Key_Down: if (mListWidget->count() > 0) { if (mListWidget->currentRow() < (mListWidget->count() - 1)) mListWidget->setCurrentRow(mListWidget->currentRow() + 1); else mListWidget->setCurrentRow(0); } break; case Qt::Key_Select: QString word; if (mListWidget->currentRow() >= 0) word = mListWidget->item(mListWidget->currentRow())->text(); else word = mLineEdit->text(); mWordBrowser = new WordBrowser(this, Qt::Popup); mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); mWordBrowser->showMaximized(); mWordBrowser->lookup(word, mLibs); break; } QWidget::keyPressEvent(event); } bool MainWindow::slotTextChanged(const QString& text) { int MaxFuzzy=MAX_FUZZY; const gchar* word; if (text.isEmpty() && mActionClear->isVisible()) mActionClear->setVisible(false); else if (!text.isEmpty() && !mActionClear->isVisible()) mActionClear->setVisible(true); gchar *fuzzy_res[MaxFuzzy]; if (! mLibs->LookupWithFuzzy((const gchar*)text.toUtf8().data(), fuzzy_res, MaxFuzzy)) return true; mListWidget->clear(); for (gchar **p = fuzzy_res, **end = fuzzy_res + MaxFuzzy; p != end && *p; ++p) { mListWidget->addItem(QString::fromUtf8((const char*)*p)); g_free(*p); } return true; } void MainWindow::paintEvent(QPaintEvent* event) { #ifdef QTOPIA if (mLineEdit) mLineEdit->setEditFocus(true); #endif QWidget::paintEvent(event); } void MainWindow::slotItemActivated(QListWidgetItem* item) { QString word = item->text(); - mWordBrowser = new WordBrowser(this, Qt::Popup); - mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); - mWordBrowser->showMaximized(); - mWordBrowser->lookup(word, mLibs); + mWordBrowser = new WordBrowser(this, Qt::Popup); + mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); + mWordBrowser->lookup(word, mLibs); + mWordBrowser->showMaximized(); + mWordBrowser->exec(); +#ifdef QTOPIA + QtopiaApplication::showInputMethod(); +#endif } void MainWindow::slotClearText() { mLineEdit->clear(); } void MainWindow::slotDictList() { mDictBrowser= new DictBrowser(this, Qt::Popup, mLibs); mDictBrowser->setAttribute(Qt::WA_DeleteOnClose); mDictBrowser->showMaximized(); } void MainWindow::slotWarning() { QMessageBox::warning(this, tr("Dictionary"), tr("There are no dictionary loaded!")); } bool MainWindow::loadDicts() { mLibs = new Libs(); // Retrieve all dict infors mDictDir = QDir(DIC_PATH, "*.ifo"); for (unsigned int i = 0; i < mDictDir.count(); i++) mLibs->load_dict(mDictDir.absoluteFilePath(mDictDir[i]).toUtf8().data()); if (mLibs->ndicts() == 0) return false; else return true; } diff --git a/src/wordbrowser.cpp b/src/wordbrowser.cpp index bf2442b..0bda020 100644 --- a/src/wordbrowser.cpp +++ b/src/wordbrowser.cpp @@ -1,225 +1,225 @@ #include <QTextCodec> #include <QStack> #include "wordbrowser.h" -WordBrowser::WordBrowser(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) +WordBrowser::WordBrowser(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f) { mLayout = new QGridLayout(this); mTextEdit = new QTextEdit(this); mTextEdit->setFocusPolicy(Qt::NoFocus); mTextEdit->setReadOnly(true); mLayout->addWidget(mTextEdit, 0, 0); } bool WordBrowser::lookup(QString& word, Libs* lib) { glong index; QString translation; for (int i = 0; i < lib->ndicts(); i++) { if (lib->LookupWord((gchar*)(word.toUtf8().data()), index, i)) { QString result; translation.append("<span style='color:#99FF33;font-weight:bold'>"); result = QString::fromUtf8(lib->dict_name(i).data()); translation.append(result); translation.append("</span><br>"); translation.append("<span style='color:#FFFF66;'>"); result = QString::fromUtf8((char*)lib->poGetWord(index, i)); translation.append(result); translation.append("</span><br>"); result = parseData(lib->poGetWordData(index, i), i, true, false); translation.append(result); translation.append(tr("<hr>")); } } if (translation.isEmpty()) translation = QString("Not found!"); mTextEdit->setHtml(translation); return true; } void WordBrowser::xdxf2html(QString &str) { str.replace("<abr>", "<font class=\"abbreviature\">"); str.replace("<tr>", "<font class=\"transcription\">["); str.replace("</tr>", "]</font>"); str.replace("<ex>", "<font class=\"example\">"); str.replace(QRegExp("<k>.*<\\/k>"), ""); str.replace(QRegExp("(<\\/abr>)|(<\\ex>)"), "</font"); } // taken from qstardict QString WordBrowser::parseData(const char *data, int dictIndex, bool htmlSpaces, bool reformatLists) { QString result; quint32 dataSize = *reinterpret_cast<const quint32*>(data); const char *dataEnd = data + dataSize; const char *ptr = data + sizeof(quint32); while (ptr < dataEnd) { switch (*ptr++) { case 'm': case 'l': case 'g': { QString str = QString::fromUtf8(ptr); ptr += str.toUtf8().length() + 1; result += str; break; } case 'x': { QString str = QString::fromUtf8(ptr); ptr += str.toUtf8().length() + 1; xdxf2html(str); result += str; break; } case 't': { QString str = QString::fromUtf8(ptr); ptr += str.toUtf8().length() + 1; result += "<font class=\"example\">"; result += str; result += "</font>"; break; } case 'y': { ptr += strlen(ptr) + 1; break; } case 'W': case 'P': { ptr += *reinterpret_cast<const quint32*>(ptr) + sizeof(quint32); break; } default: ; // nothing } } if (reformatLists) { int pos = 0; QStack<QChar> openedLists; while (pos < result.length()) { if (result[pos].isDigit()) { int n = 0; while (result[pos + n].isDigit()) ++n; pos += n; if (result[pos] == '&' && result.mid(pos + 1, 3) == "gt;") result.replace(pos, 4, ">"); QChar marker = result[pos]; QString replacement; if (marker == '>' || marker == '.' || marker == ')') { if (n == 1 && result[pos - 1] == '1') // open new list { if (openedLists.contains(marker)) { replacement = "</li></ol>"; while (openedLists.size() && openedLists.top() != marker) { replacement += "</li></ol>"; openedLists.pop(); } } openedLists.push(marker); replacement += "<ol>"; } else { while (openedLists.size() && openedLists.top() != marker) { replacement += "</li></ol>"; openedLists.pop(); } replacement += "</li>"; } replacement += "<li>"; pos -= n; n += pos; while (result[pos - 1].isSpace()) --pos; while (result[n + 1].isSpace()) ++n; result.replace(pos, n - pos + 1, replacement); pos += replacement.length(); } else ++pos; } else ++pos; } while (openedLists.size()) { result += "</li></ol>"; openedLists.pop(); } } if (htmlSpaces) { int n = 0; while (result[n].isSpace()) ++n; result.remove(0, n); n = 0; while (result[result.length() - 1 - n].isSpace()) ++n; result.remove(result.length() - n, n); for (int pos = 0; pos < result.length();) { switch (result[pos].toAscii()) { case '[': result.insert(pos, "<font class=\"transcription\">"); pos += 28 + 1; // sizeof "<font class=\"transcription\">" + 1 break; case ']': result.insert(pos + 1, "</font>"); pos += 7 + 1; // sizeof "</font>" + 1 break; case '\t': result.insert(pos, "&nbsp;&nbsp;&nbsp;&nbsp;"); pos += 24 + 1; // sizeof "&nbsp;&nbsp;&nbsp;&nbsp;" + 1 break; case '\n': { int count = 1; n = 1; while (result[pos + n].isSpace()) { if (result[pos + n] == '\n') ++count; ++n; } if (count > 1) result.replace(pos, n, "</p><p>"); else result.replace(pos, n, "<br>"); break; } default: ++pos; } } } return result; } diff --git a/src/wordbrowser.h b/src/wordbrowser.h index 2abe8cb..62fd116 100644 --- a/src/wordbrowser.h +++ b/src/wordbrowser.h @@ -1,27 +1,28 @@ #ifndef WORD_BROWSER_H #define WORD_BROWSER_H #include <string> +#include <QDialog> #include <QWidget> #include <QTextEdit> #include <QGridLayout> #include "lib/lib.h" -class WordBrowser : public QWidget +class WordBrowser : public QDialog { public: WordBrowser(QWidget* parent = 0, Qt::WindowFlags f = 0); bool lookup(QString& word, Libs* lib); private: QString parseData(const char*, int, bool, bool); void xdxf2html(QString&); private: QGridLayout* mLayout; QTextEdit* mTextEdit; }; #endif
radekp/qdictopia
f23c56afdc82bf4293a4c959dfa01c2aa587db45
Better icon
diff --git a/pics/QDictopia.png b/pics/QDictopia.png deleted file mode 100644 index 1256873..0000000 Binary files a/pics/QDictopia.png and /dev/null differ diff --git a/pics/qdictopia.svg b/pics/qdictopia.svg new file mode 100644 index 0000000..faa926a --- /dev/null +++ b/pics/qdictopia.svg @@ -0,0 +1,298 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://web.resource.org/cc/" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="48" + height="48" + id="svg1307" + sodipodi:version="0.32" + inkscape:version="0.45" + inkscape:export-xdpi="960" + inkscape:export-ydpi="960" + inkscape:output_extension="org.inkscape.output.svg.inkscape" + sodipodi:modified="TRUE" + version="1.0"> + <defs + id="defs1309"> + <linearGradient + inkscape:collect="always" + id="linearGradient15424"> + <stop + style="stop-color:#729fcf;stop-opacity:1;" + offset="0" + id="stop15426" /> + <stop + style="stop-color:#729fcf;stop-opacity:0;" + offset="1" + id="stop15428" /> + </linearGradient> + <linearGradient + id="linearGradient11002"> + <stop + style="stop-color:#eeeeee;stop-opacity:1;" + offset="0" + id="stop11004" /> + <stop + style="stop-color:#d3d7cf;stop-opacity:1;" + offset="1" + id="stop11006" /> + </linearGradient> + <linearGradient + id="linearGradient7492"> + <stop + style="stop-color:#a40000;stop-opacity:1;" + offset="0" + id="stop7494" /> + <stop + style="stop-color:#cc0000;stop-opacity:0.74509805;" + offset="1" + id="stop7496" /> + </linearGradient> + <linearGradient + id="linearGradient7484"> + <stop + style="stop-color:#cc0000;stop-opacity:1;" + offset="0" + id="stop7486" /> + <stop + style="stop-color:#cc0000;stop-opacity:1;" + offset="1" + id="stop7488" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient5722"> + <stop + style="stop-color:#729fcf;stop-opacity:1;" + offset="0" + id="stop5724" /> + <stop + style="stop-color:#729fcf;stop-opacity:0;" + offset="1" + id="stop5726" /> + </linearGradient> + <linearGradient + id="linearGradient3077"> + <stop + style="stop-color:#3465a4;stop-opacity:1;" + offset="0" + id="stop3079" /> + <stop + style="stop-color:#3465a4;stop-opacity:0;" + offset="1" + id="stop3081" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient5722" + id="linearGradient5728" + x1="45" + y1="34.184055" + x2="7.8263865" + y2="5.1271901" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(1,0,0,0.963894,0,1.234246)" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient7492" + id="linearGradient7498" + x1="45.402073" + y1="32.607113" + x2="8.1801958" + y2="7" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(0.92971,0,0,1,2.031898,1)" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient11002" + id="linearGradient12780" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(1,0,0,0.800658,-1.049033e-8,7.880118)" + x1="3.6162441" + y1="43.778091" + x2="43.494923" + y2="35.142323" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient15424" + id="linearGradient15430" + x1="42.706234" + y1="32.362251" + x2="3.0072398" + y2="2.8657963" + gradientUnits="userSpaceOnUse" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient11002" + id="linearGradient15455" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(1,0,0,0.800658,-1.049033e-8,7.880118)" + x1="3.6162441" + y1="43.778091" + x2="43.494923" + y2="35.142323" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient15424" + id="linearGradient15457" + gradientUnits="userSpaceOnUse" + x1="42.706234" + y1="32.362251" + x2="3.0072398" + y2="2.8657963" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient5722" + id="linearGradient15459" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(1,0,0,0.963894,0,1.234246)" + x1="45" + y1="34.184055" + x2="7.8263865" + y2="5.1271901" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient7492" + id="linearGradient15461" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(0.92971,0,0,1,2.031898,1)" + x1="45.402073" + y1="32.607113" + x2="8.1801958" + y2="7" /> + </defs> + <sodipodi:namedview + id="base" + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1.0" + inkscape:pageopacity="0.0" + inkscape:pageshadow="2" + inkscape:zoom="9.8994949" + inkscape:cx="24.295867" + inkscape:cy="23.945596" + inkscape:current-layer="layer5" + showgrid="true" + inkscape:grid-bbox="true" + inkscape:document-units="px" + fill="#d3d7cf" + inkscape:window-width="1014" + inkscape:window-height="668" + inkscape:window-x="0" + inkscape:window-y="25" /> + <metadata + id="metadata1312"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + </cc:Work> + </rdf:RDF> + </metadata> + <g + id="layer1" + inkscape:label="back-cover" + inkscape:groupmode="layer" + style="display:inline" /> + <g + inkscape:groupmode="layer" + id="layer6" + inkscape:label="pages" /> + <g + inkscape:groupmode="layer" + id="layer7" + inkscape:label="spine" /> + <g + inkscape:groupmode="layer" + id="layer2" + inkscape:label="front-cover" + style="display:inline" /> + <g + inkscape:groupmode="layer" + id="layer8" + inkscape:label="highlight" + style="display:inline" /> + <g + inkscape:groupmode="layer" + id="layer3" + inkscape:label="glow" + style="display:inline" /> + <g + inkscape:groupmode="layer" + id="layer4" + inkscape:label="title-1" + style="display:inline" /> + <g + inkscape:groupmode="layer" + id="layer5" + inkscape:label="title-2" + style="display:inline"> + <g + id="g15442" + transform="matrix(0.931943,0,0,0.949698,2.176413,0.278207)"> + <path + sodipodi:nodetypes="ccccccccc" + id="rect1315" + d="M 7.8124859,4.4639581 L 40.133422,4.4639581 C 40.500078,4.4639581 40.795256,4.7537407 40.795256,5.113695 L 45.428097,43.832455 C 45.428097,44.192408 45.13292,44.482191 44.766264,44.482191 L 3.1796434,44.482191 C 2.8129871,44.482191 2.5178087,44.192408 2.5178087,43.832455 L 7.1506509,5.113695 C 7.1506509,4.7537407 7.4458289,4.4639581 7.8124859,4.4639581 z " + style="fill:#204a87;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.03561747;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;display:inline" /> + <path + sodipodi:nodetypes="ccccccssc" + id="rect7505" + d="M 3.1303047,34.301823 L 43.422336,34.301823 C 43.742362,34.301823 44,34.505877 44,34.759343 L 44,42.65154 C 44,42.905005 43.641347,43.614135 43.321321,43.614135 L 3.0292894,43.715151 C 2.7092638,43.715151 2.1246122,43.8866 1.9465496,42.5723 C 1.5635805,39.745563 1.1606217,37.880413 2.1485801,34.860358 C 2.580254,33.54079 2.8102791,34.301823 3.1303047,34.301823 z " + style="fill:url(#linearGradient15455);fill-opacity:1;fill-rule:evenodd;stroke:#babdb6;stroke-width:0.73400003;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + <path + sodipodi:nodetypes="czzcc" + id="path8381" + d="M 2.5,34.5 C 2.5,34.5 1.75,35.712694 1.5,37.429953 C 1.25,39.147212 1.25,39.869037 1.5,41.369037 C 1.75,42.869037 2.5,43.935029 2.5,43.935029 L 2.8030458,44.440105" + style="fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + <path + sodipodi:nodetypes="czzcc" + id="path11030" + d="M 7.4707316,4.5027374 C 7.4707316,4.5027374 6.5990531,5.7220707 6.3084936,7.4487313 C 6.0179341,9.175392 6.0179341,9.9011689 6.3084936,11.409381 C 6.5990531,12.917593 7.4707316,13.989421 7.4707316,13.989421 L 7.822942,14.497263" + style="fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:#000000;stroke-width:1.08101857;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + <path + id="path11032" + d="M 1.5,37.5 L 6.3529412,6.6997504 L 6.3529412,7.1285302 L 6.3529412,7.1285302" + style="fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" /> + <path + sodipodi:nodetypes="ccccccccc" + id="path2195" + d="M 7.7443838,4.4497066 L 40.065319,4.4497066 C 40.431975,4.4497066 40.727153,4.6682776 40.727153,4.9397756 L 45.359994,34.143693 C 45.359994,34.41519 45.064817,34.633762 44.698161,34.633762 L 3.1115412,34.633762 C 2.744885,34.633762 2.4497066,34.41519 2.4497066,34.143693 L 7.0825488,4.9397756 C 7.0825488,4.6682776 7.3777268,4.4497066 7.7443838,4.4497066 z " + style="fill:#3465a4;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.89941311;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;display:inline" /> + <path + sodipodi:nodetypes="ccccccccc" + id="path12801" + d="M 7.7443838,4.3662384 L 40.065319,4.3662384 C 40.431975,4.3662384 40.727153,4.5848094 40.727153,4.8563074 L 45.359994,34.060224 C 45.359994,34.331721 45.064817,34.550293 44.698161,34.550293 L 3.1115412,34.550293 C 2.744885,34.550293 2.4497066,34.331721 2.4497066,34.060224 L 7.0825488,4.8563074 C 7.0825488,4.5848094 7.3777268,4.3662384 7.7443838,4.3662384 z " + style="fill:none;fill-opacity:1;fill-rule:evenodd;stroke:#729fcf;stroke-width:0.89941311;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:0;display:inline" /> + <path + sodipodi:nodetypes="ccccccccc" + id="path13676" + d="M 8.5112104,5.4251519 L 39.492597,5.4251519 C 39.844057,5.4251519 40.127001,5.6323999 40.127001,5.8898331 L 44.567833,33.580854 C 44.567833,33.838287 44.284889,34.045536 43.93343,34.045536 L 4.0703777,34.045536 C 3.7189179,34.045536 3.4359725,33.838287 3.4359725,33.580854 L 7.8768053,5.8898331 C 7.8768053,5.6323999 8.1597495,5.4251519 8.5112104,5.4251519 z " + style="fill:none;fill-opacity:1;fill-rule:evenodd;stroke:url(#linearGradient15457);stroke-width:0.85746539;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:0.74509804;display:inline" /> + <path + sodipodi:nodetypes="czcccccccc" + id="path3092" + d="M 5.2529148,23.677326 C 5.2529148,23.677326 12.909199,18.7359 24.000001,18.61419 C 34.989788,18.49248 40.827798,14.135261 40.827798,14.135261 C 41.186676,14.135261 41.778638,13.953136 41.778638,14.206161 L 45,33.72733 C 45,33.980354 44.711085,34.184055 44.352207,34.184055 L 3.647794,34.184055 C 3.2889162,34.184055 3,33.980354 3,33.72733 L 4.6051198,24.134051 C 4.6051198,23.881026 4.8940359,23.677326 5.2529148,23.677326 z " + style="fill:url(#linearGradient15459);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:0.89941311;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;display:inline" /> + <path + sodipodi:nodetypes="ccccc" + id="path7500" + d="M 9.3745694,7.0981816 C 9.3745694,7.0981816 32.719444,7 39.12471,7 L 40,13.901819 L 8.5050763,14 L 9.3745694,7.0981816 z " + style="fill:#d3d7cf;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;display:inline" /> + <path + sodipodi:nodetypes="ccccc" + id="path6609" + d="M 9.5794982,8 C 9.5794982,8 32.641961,8 38.919858,8 L 39.595939,13 L 9,13 L 9.5794982,8 z " + style="fill:url(#linearGradient15461);fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;display:inline" /> + </g> + </g> +</svg> diff --git a/qdictopia.desktop b/qdictopia.desktop index 62052ea..edf510f 100644 --- a/qdictopia.desktop +++ b/qdictopia.desktop @@ -1,10 +1,10 @@ [Translation] File=QtopiaApplications Context=QDictopia [Desktop Entry] Comment[]=A Dictionary Program Exec=qdictopia -Icon=qdictopia/QDictopia +Icon=qdictopia/qdictopia Type=Application Name[]=Dictionary Categories=MainApplications
radekp/qdictopia
4c6161c93e734571e3cb5d8c731dad7a74929a5c
Search, parser, path fixes and color support
diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index aad16df..fa462c5 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,181 +1,164 @@ #include <QMessageBox> #include <QTimer> #include "mainwindow.h" MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags f, QMenu *menu) : QWidget(parent, f), mLineEdit(NULL) { #ifdef QTOPIA Q_UNUSED(menu); #endif if (loadDicts() == false) { QTimer::singleShot(0, this, SLOT(slotWarning())); } else { // Build UI mLayout = new QGridLayout(this); mLineEdit = new QLineEdit(this); //mLineEdit->setFocusPolicy(Qt::NoFocus); connect(mLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(slotTextChanged(const QString&))); #ifdef QTOPIA mMenu = QSoftMenuBar::menuFor(mLineEdit); #else mMenu = menu; #endif mActionClear = mMenu->addAction(tr("Clear text"), this, SLOT(slotClearText())); mActionClear->setVisible(false); mActionDList = mMenu->addAction(tr("Dictionaries..."), this, SLOT(slotDictList())); mListWidget = new QListWidget(this); mListWidget->setFocusPolicy(Qt::NoFocus); connect(mListWidget, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(slotItemActivated(QListWidgetItem*))); mLayout->addWidget(mLineEdit, 0, 0); mLayout->addWidget(mListWidget, 1, 0); } } MainWindow::~MainWindow() { if (mLibs) delete mLibs; } void MainWindow::keyPressEvent(QKeyEvent* event) { switch(event->key()) { case Qt::Key_Up: if (mListWidget->count() > 0) { if (mListWidget->currentRow() <= 0) mListWidget->setCurrentRow(mListWidget->count() - 1); else mListWidget->setCurrentRow(mListWidget->currentRow() - 1); } break; case Qt::Key_Down: if (mListWidget->count() > 0) { if (mListWidget->currentRow() < (mListWidget->count() - 1)) mListWidget->setCurrentRow(mListWidget->currentRow() + 1); else mListWidget->setCurrentRow(0); } break; case Qt::Key_Select: QString word; if (mListWidget->currentRow() >= 0) word = mListWidget->item(mListWidget->currentRow())->text(); else word = mLineEdit->text(); mWordBrowser = new WordBrowser(this, Qt::Popup); mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); mWordBrowser->showMaximized(); mWordBrowser->lookup(word, mLibs); - break; } QWidget::keyPressEvent(event); } bool MainWindow::slotTextChanged(const QString& text) { - glong* index = (glong*)malloc(sizeof(glong) * mLibs->ndicts()); - const gchar* word; - bool bfound = false; - - if (text.isEmpty() && mActionClear->isVisible()) - mActionClear->setVisible(false); - else if (!text.isEmpty() && !mActionClear->isVisible()) - mActionClear->setVisible(true); - for (int i = 0; i < mLibs->ndicts(); i++) - if (mLibs->LookupWord((const gchar*)text.toLatin1().data(), index[i], i)) - bfound = true; + int MaxFuzzy=MAX_FUZZY; + const gchar* word; - for (int i = 0; i < mLibs->ndicts(); i++) - if (mLibs->LookupSimilarWord((const gchar*)text.toLatin1().data(), index[i], i)) - bfound = true; - - if (bfound) - { - mListWidget->clear(); - - word = mLibs->poGetCurrentWord(index); - mListWidget->addItem(tr((const char*)word)); - - for (int j = 0; j < MAX_FUZZY; j++) - { - if ((word = mLibs->poGetNextWord(NULL, index))) - mListWidget->addItem(tr((const char*)word)); - else - break; - } - } + if (text.isEmpty() && mActionClear->isVisible()) + mActionClear->setVisible(false); + else if (!text.isEmpty() && !mActionClear->isVisible()) + mActionClear->setVisible(true); - free(index); - return true; + gchar *fuzzy_res[MaxFuzzy]; + if (! mLibs->LookupWithFuzzy((const gchar*)text.toUtf8().data(), fuzzy_res, MaxFuzzy)) + return true; + mListWidget->clear(); + for (gchar **p = fuzzy_res, **end = fuzzy_res + MaxFuzzy; p != end && *p; ++p) + { + mListWidget->addItem(QString::fromUtf8((const char*)*p)); + g_free(*p); + } + return true; } void MainWindow::paintEvent(QPaintEvent* event) { #ifdef QTOPIA if (mLineEdit) mLineEdit->setEditFocus(true); #endif QWidget::paintEvent(event); } void MainWindow::slotItemActivated(QListWidgetItem* item) { QString word = item->text(); mWordBrowser = new WordBrowser(this, Qt::Popup); mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); mWordBrowser->showMaximized(); mWordBrowser->lookup(word, mLibs); } void MainWindow::slotClearText() { mLineEdit->clear(); } void MainWindow::slotDictList() { mDictBrowser= new DictBrowser(this, Qt::Popup, mLibs); mDictBrowser->setAttribute(Qt::WA_DeleteOnClose); mDictBrowser->showMaximized(); } void MainWindow::slotWarning() { QMessageBox::warning(this, tr("Dictionary"), tr("There are no dictionary loaded!")); } bool MainWindow::loadDicts() { mLibs = new Libs(); // Retrieve all dict infors mDictDir = QDir(DIC_PATH, "*.ifo"); for (unsigned int i = 0; i < mDictDir.count(); i++) - mLibs->load_dict(mDictDir.absoluteFilePath(mDictDir[i]).toLatin1().data()); + mLibs->load_dict(mDictDir.absoluteFilePath(mDictDir[i]).toUtf8().data()); if (mLibs->ndicts() == 0) return false; else return true; } diff --git a/src/wordbrowser.cpp b/src/wordbrowser.cpp index f3a8422..bf2442b 100644 --- a/src/wordbrowser.cpp +++ b/src/wordbrowser.cpp @@ -1,186 +1,225 @@ #include <QTextCodec> +#include <QStack> #include "wordbrowser.h" WordBrowser::WordBrowser(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { mLayout = new QGridLayout(this); mTextEdit = new QTextEdit(this); mTextEdit->setFocusPolicy(Qt::NoFocus); mTextEdit->setReadOnly(true); - mLayout->addWidget(mTextEdit, 0, 0); } bool WordBrowser::lookup(QString& word, Libs* lib) { glong index; QString translation; for (int i = 0; i < lib->ndicts(); i++) { - if (lib->LookupWord((gchar*)(word.toLatin1().data()), index, i)) + if (lib->LookupWord((gchar*)(word.toUtf8().data()), index, i)) { - QString result = QString((char*)lib->poGetWord(index, i)); - - if (result == word) - { - const char* utf8_cstr; - QString uni_str; - QTextCodec* codec = QTextCodec::codecForName("UTF-8"); - - translation.append("<---"); - utf8_cstr = lib->dict_name(i).data(); - uni_str = codec->toUnicode(utf8_cstr); - translation.append(uni_str); - translation.append("--->"); - - utf8_cstr = (parse_data(lib->poGetWordData(index, i))).data(); - uni_str = codec->toUnicode(utf8_cstr); - translation.append(uni_str); - translation.append(tr("\n\n")); - } + QString result; + translation.append("<span style='color:#99FF33;font-weight:bold'>"); + result = QString::fromUtf8(lib->dict_name(i).data()); + translation.append(result); + translation.append("</span><br>"); + translation.append("<span style='color:#FFFF66;'>"); + result = QString::fromUtf8((char*)lib->poGetWord(index, i)); + translation.append(result); + translation.append("</span><br>"); + result = parseData(lib->poGetWordData(index, i), i, true, false); + translation.append(result); + translation.append(tr("<hr>")); } } if (translation.isEmpty()) translation = QString("Not found!"); - mTextEdit->setText(translation); + mTextEdit->setHtml(translation); return true; } -std::string WordBrowser::xdxf2text(const char* p) +void WordBrowser::xdxf2html(QString &str) { - std::string res; - for (; *p; ++p) { - if (*p!='<') { - if (g_str_has_prefix(p, "&gt;")) { - res+=">"; - p+=3; - } else if (g_str_has_prefix(p, "&lt;")) { - res+="<"; - p+=3; - } else if (g_str_has_prefix(p, "&amp;")) { - res+="&"; - p+=4; - } else if (g_str_has_prefix(p, "&quot;")) { - res+="\""; - p+=5; - } else - res+=*p; - continue; - } - - const char *next=strchr(p, '>'); - if (!next) - continue; - - std::string name(p+1, next-p-1); - - if (name=="abr") - res+=""; - else if (name=="/abr") - res+=""; - else if (name=="k") { - const char *begin=next; - if ((next=strstr(begin, "</k>"))!=NULL) - next+=sizeof("</k>")-1-1; - else - next=begin; - } else if (name=="b") - res+=""; - else if (name=="/b") - res+=""; - else if (name=="i") - res+=""; - else if (name=="/i") - res+=""; - else if (name=="tr") - res+="["; - else if (name=="/tr") - res+="]"; - else if (name=="ex") - res+=""; - else if (name=="/ex") - res+=""; - else if (!name.empty() && name[0]=='c' && name!="co") { - std::string::size_type pos=name.find("code"); - if (pos!=std::string::size_type(-1)) { - pos+=sizeof("code=\"")-1; - std::string::size_type end_pos=name.find("\""); - std::string color(name, pos, end_pos-pos); - res+=""; - } else { - res+=""; - } - } else if (name=="/c") - res+=""; - - p=next; - } - return res; + str.replace("<abr>", "<font class=\"abbreviature\">"); + str.replace("<tr>", "<font class=\"transcription\">["); + str.replace("</tr>", "]</font>"); + str.replace("<ex>", "<font class=\"example\">"); + str.replace(QRegExp("<k>.*<\\/k>"), ""); + str.replace(QRegExp("(<\\/abr>)|(<\\ex>)"), "</font"); } -std::string WordBrowser::parse_data(const gchar* data) +// taken from qstardict +QString WordBrowser::parseData(const char *data, int dictIndex, bool htmlSpaces, bool reformatLists) { - if (!data) - return ""; + QString result; + quint32 dataSize = *reinterpret_cast<const quint32*>(data); + const char *dataEnd = data + dataSize; + const char *ptr = data + sizeof(quint32); + while (ptr < dataEnd) + { + switch (*ptr++) + { + case 'm': + case 'l': + case 'g': + { + QString str = QString::fromUtf8(ptr); + ptr += str.toUtf8().length() + 1; + result += str; + break; + } + case 'x': + { + QString str = QString::fromUtf8(ptr); + ptr += str.toUtf8().length() + 1; + xdxf2html(str); + result += str; + break; + } + case 't': + { + QString str = QString::fromUtf8(ptr); + ptr += str.toUtf8().length() + 1; + result += "<font class=\"example\">"; + result += str; + result += "</font>"; + break; + } + case 'y': + { + ptr += strlen(ptr) + 1; + break; + } + case 'W': + case 'P': + { + ptr += *reinterpret_cast<const quint32*>(ptr) + sizeof(quint32); + break; + } + default: + ; // nothing + } + } + + + if (reformatLists) + { + int pos = 0; + QStack<QChar> openedLists; + while (pos < result.length()) + { + if (result[pos].isDigit()) + { + int n = 0; + while (result[pos + n].isDigit()) + ++n; + pos += n; + if (result[pos] == '&' && result.mid(pos + 1, 3) == "gt;") + result.replace(pos, 4, ">"); + QChar marker = result[pos]; + QString replacement; + if (marker == '>' || marker == '.' || marker == ')') + { + if (n == 1 && result[pos - 1] == '1') // open new list + { + if (openedLists.contains(marker)) + { + replacement = "</li></ol>"; + while (openedLists.size() && openedLists.top() != marker) + { + replacement += "</li></ol>"; + openedLists.pop(); + } + } + openedLists.push(marker); + replacement += "<ol>"; + } + else + { + while (openedLists.size() && openedLists.top() != marker) + { + replacement += "</li></ol>"; + openedLists.pop(); + } + replacement += "</li>"; + } + replacement += "<li>"; + pos -= n; + n += pos; + while (result[pos - 1].isSpace()) + --pos; + while (result[n + 1].isSpace()) + ++n; + result.replace(pos, n - pos + 1, replacement); + pos += replacement.length(); + } + else + ++pos; + } + else + ++pos; + } + while (openedLists.size()) + { + result += "</li></ol>"; + openedLists.pop(); + } + } + if (htmlSpaces) + { + int n = 0; + while (result[n].isSpace()) + ++n; + result.remove(0, n); + n = 0; + while (result[result.length() - 1 - n].isSpace()) + ++n; + result.remove(result.length() - n, n); + + for (int pos = 0; pos < result.length();) + { + switch (result[pos].toAscii()) + { + case '[': + result.insert(pos, "<font class=\"transcription\">"); + pos += 28 + 1; // sizeof "<font class=\"transcription\">" + 1 + break; + case ']': + result.insert(pos + 1, "</font>"); + pos += 7 + 1; // sizeof "</font>" + 1 + break; + case '\t': + result.insert(pos, "&nbsp;&nbsp;&nbsp;&nbsp;"); + pos += 24 + 1; // sizeof "&nbsp;&nbsp;&nbsp;&nbsp;" + 1 + break; + case '\n': + { + int count = 1; + n = 1; + while (result[pos + n].isSpace()) + { + if (result[pos + n] == '\n') + ++count; + ++n; + } + if (count > 1) + result.replace(pos, n, "</p><p>"); + else + result.replace(pos, n, "<br>"); + break; + } + default: + ++pos; + } + } + } + return result; +} - std::string res; - guint32 data_size, sec_size=0; - gchar *m_str; - const gchar *p=data; - data_size=*((guint32 *)p); - p+=sizeof(guint32); - while (guint32(p - data)<data_size) { - switch (*p++) { - case 'm': - case 'l': //need more work... - case 'g': - sec_size = strlen(p); - if (sec_size) { - res+="\n"; - m_str = g_strndup(p, sec_size); - res += m_str; - g_free(m_str); - } - sec_size++; - break; - case 'x': - sec_size = strlen(p); - if (sec_size) { - res+="\n"; - m_str = g_strndup(p, sec_size); - res += xdxf2text(m_str); - g_free(m_str); - } - sec_size++; - break; - case 't': - sec_size = strlen(p); - if(sec_size){ - res+="\n"; - m_str = g_strndup(p, sec_size); - res += "["+std::string(m_str)+"]"; - g_free(m_str); - } - sec_size++; - break; - case 'y': - sec_size = strlen(p); - sec_size++; - break; - case 'W': - case 'P': - sec_size=*((guint32 *)p); - sec_size+=sizeof(guint32); - break; - } - p += sec_size; - } - - return res; -} diff --git a/src/wordbrowser.h b/src/wordbrowser.h index 4005510..2abe8cb 100644 --- a/src/wordbrowser.h +++ b/src/wordbrowser.h @@ -1,27 +1,27 @@ #ifndef WORD_BROWSER_H #define WORD_BROWSER_H #include <string> #include <QWidget> #include <QTextEdit> #include <QGridLayout> #include "lib/lib.h" class WordBrowser : public QWidget { public: WordBrowser(QWidget* parent = 0, Qt::WindowFlags f = 0); bool lookup(QString& word, Libs* lib); private: - std::string parse_data(const gchar* data); - std::string xdxf2text(const char* p); + QString parseData(const char*, int, bool, bool); + void xdxf2html(QString&); private: QGridLayout* mLayout; QTextEdit* mTextEdit; }; #endif
radekp/qdictopia
60c723432427eaff0ad989ad4181635a9f7f42e1
Fixing typecasting to work correctly on ARM
diff --git a/src/lib/lib.cpp b/src/lib/lib.cpp index 55a859d..de8560c 100644 --- a/src/lib/lib.cpp +++ b/src/lib/lib.cpp @@ -1,1013 +1,1017 @@ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <algorithm> #include <cstring> #include <cctype> #include <sys/stat.h> #include <zlib.h> #include <glib/gstdio.h> #include "distance.h" #include "file.hpp" #include "mapfile.hpp" #include "lib.h" // Notice: read src/tools/DICTFILE_FORMAT for the dictionary // file's format information! static inline bool bIsVowel(gchar inputchar) { gchar ch = g_ascii_toupper(inputchar); return( ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U' ); } static bool bIsPureEnglish(const gchar *str) { // i think this should work even when it is UTF8 string :). for (int i=0; str[i]!=0; i++) //if(str[i]<0) //if(str[i]<32 || str[i]>126) // tab equal 9,so this is not OK. // Better use isascii() but not str[i]<0 while char is default unsigned in arm if (!isascii(str[i])) return false; return true; } static inline gint stardict_strcmp(const gchar *s1, const gchar *s2) { gint a=g_ascii_strcasecmp(s1, s2); if (a == 0) return strcmp(s1, s2); else return a; } bool DictInfo::load_from_ifo_file(const std::string& ifofilename, bool istreedict) { ifo_file_name=ifofilename; gchar *buffer; if (!g_file_get_contents(ifofilename.c_str(), &buffer, NULL, NULL)) return false; #define TREEDICT_MAGIC_DATA "StarDict's treedict ifo file\nversion=2.4.2\n" #define DICT_MAGIC_DATA "StarDict's dict ifo file\nversion=2.4.2\n" const gchar *magic_data=istreedict ? TREEDICT_MAGIC_DATA : DICT_MAGIC_DATA; if (!g_str_has_prefix(buffer, magic_data)) { g_free(buffer); return false; } gchar *p1,*p2,*p3; p1 = buffer + strlen(magic_data)-1; p2 = strstr(p1,"\nwordcount="); if (!p2) { g_free(buffer); return false; } p3 = strchr(p2+ sizeof("\nwordcount=")-1,'\n'); gchar *tmpstr = (gchar *)g_memdup(p2+sizeof("\nwordcount=")-1, p3-(p2+sizeof("\nwordcount=")-1)+1); tmpstr[p3-(p2+sizeof("\nwordcount=")-1)] = '\0'; wordcount = atol(tmpstr); g_free(tmpstr); if (istreedict) { p2 = strstr(p1,"\ntdxfilesize="); if (!p2) { g_free(buffer); return false; } p3 = strchr(p2+ sizeof("\ntdxfilesize=")-1,'\n'); tmpstr = (gchar *)g_memdup(p2+sizeof("\ntdxfilesize=")-1, p3-(p2+sizeof("\ntdxfilesize=")-1)+1); tmpstr[p3-(p2+sizeof("\ntdxfilesize=")-1)] = '\0'; index_file_size = atol(tmpstr); g_free(tmpstr); } else { p2 = strstr(p1,"\nidxfilesize="); if (!p2) { g_free(buffer); return false; } p3 = strchr(p2+ sizeof("\nidxfilesize=")-1,'\n'); tmpstr = (gchar *)g_memdup(p2+sizeof("\nidxfilesize=")-1, p3-(p2+sizeof("\nidxfilesize=")-1)+1); tmpstr[p3-(p2+sizeof("\nidxfilesize=")-1)] = '\0'; index_file_size = atol(tmpstr); g_free(tmpstr); } p2 = strstr(p1,"\nbookname="); if (!p2) { g_free(buffer); return false; } p2 = p2 + sizeof("\nbookname=") -1; p3 = strchr(p2, '\n'); bookname.assign(p2, p3-p2); p2 = strstr(p1,"\nauthor="); if (p2) { p2 = p2 + sizeof("\nauthor=") -1; p3 = strchr(p2, '\n'); author.assign(p2, p3-p2); } p2 = strstr(p1,"\nemail="); if (p2) { p2 = p2 + sizeof("\nemail=") -1; p3 = strchr(p2, '\n'); email.assign(p2, p3-p2); } p2 = strstr(p1,"\nwebsite="); if (p2) { p2 = p2 + sizeof("\nwebsite=") -1; p3 = strchr(p2, '\n'); website.assign(p2, p3-p2); } p2 = strstr(p1,"\ndate="); if (p2) { p2 = p2 + sizeof("\ndate=") -1; p3 = strchr(p2, '\n'); date.assign(p2, p3-p2); } p2 = strstr(p1,"\ndescription="); if (p2) { p2 = p2 + sizeof("\ndescription=")-1; p3 = strchr(p2, '\n'); description.assign(p2, p3-p2); } p2 = strstr(p1,"\nsametypesequence="); if (p2) { p2+=sizeof("\nsametypesequence=")-1; p3 = strchr(p2, '\n'); sametypesequence.assign(p2, p3-p2); } g_free(buffer); return true; } //=================================================================== DictBase::DictBase() { dictfile = NULL; cache_cur =0; } DictBase::~DictBase() { if (dictfile) fclose(dictfile); } gchar* DictBase::GetWordData(guint32 idxitem_offset, guint32 idxitem_size) { for (int i=0; i<WORDDATA_CACHE_NUM; i++) if (cache[i].data && cache[i].offset == idxitem_offset) return cache[i].data; if (dictfile) fseek(dictfile, idxitem_offset, SEEK_SET); gchar *data; if (!sametypesequence.empty()) { gchar *origin_data = (gchar *)g_malloc(idxitem_size); if (dictfile) fread(origin_data, idxitem_size, 1, dictfile); else dictdzfile->read(origin_data, idxitem_offset, idxitem_size); guint32 data_size; gint sametypesequence_len = sametypesequence.length(); //there have sametypesequence_len char being omitted. data_size = idxitem_size + sizeof(guint32) + sametypesequence_len; //if the last item's size is determined by the end up '\0',then +=sizeof(gchar); //if the last item's size is determined by the head guint32 type data,then +=sizeof(guint32); switch (sametypesequence[sametypesequence_len-1]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': data_size += sizeof(gchar); break; case 'W': case 'P': data_size += sizeof(guint32); break; default: if (g_ascii_isupper(sametypesequence[sametypesequence_len-1])) data_size += sizeof(guint32); else data_size += sizeof(gchar); break; } data = (gchar *)g_malloc(data_size); gchar *p1,*p2; p1 = data + sizeof(guint32); p2 = origin_data; guint32 sec_size; //copy the head items. for (int i=0; i<sametypesequence_len-1; i++) { *p1=sametypesequence[i]; p1+=sizeof(gchar); switch (sametypesequence[i]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': sec_size = strlen(p2)+1; memcpy(p1, p2, sec_size); p1+=sec_size; p2+=sec_size; break; case 'W': case 'P': sec_size = *reinterpret_cast<guint32 *>(p2); sec_size += sizeof(guint32); memcpy(p1, p2, sec_size); p1+=sec_size; p2+=sec_size; break; default: if (g_ascii_isupper(sametypesequence[i])) { sec_size = *reinterpret_cast<guint32 *>(p2); sec_size += sizeof(guint32); } else { sec_size = strlen(p2)+1; } memcpy(p1, p2, sec_size); p1+=sec_size; p2+=sec_size; break; } } //calculate the last item 's size. sec_size = idxitem_size - (p2-origin_data); *p1=sametypesequence[sametypesequence_len-1]; p1+=sizeof(gchar); switch (sametypesequence[sametypesequence_len-1]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': memcpy(p1, p2, sec_size); p1 += sec_size; *p1='\0';//add the end up '\0'; break; case 'W': case 'P': *reinterpret_cast<guint32 *>(p1)=sec_size; p1 += sizeof(guint32); memcpy(p1, p2, sec_size); break; default: if (g_ascii_isupper(sametypesequence[sametypesequence_len-1])) { *reinterpret_cast<guint32 *>(p1)=sec_size; p1 += sizeof(guint32); memcpy(p1, p2, sec_size); } else { memcpy(p1, p2, sec_size); p1 += sec_size; *p1='\0'; } break; } g_free(origin_data); *reinterpret_cast<guint32 *>(data)=data_size; } else { data = (gchar *)g_malloc(idxitem_size + sizeof(guint32)); if (dictfile) fread(data+sizeof(guint32), idxitem_size, 1, dictfile); else dictdzfile->read(data+sizeof(guint32), idxitem_offset, idxitem_size); *reinterpret_cast<guint32 *>(data)=idxitem_size+sizeof(guint32); } g_free(cache[cache_cur].data); cache[cache_cur].data = data; cache[cache_cur].offset = idxitem_offset; cache_cur++; if (cache_cur==WORDDATA_CACHE_NUM) cache_cur = 0; return data; } inline bool DictBase::containSearchData() { if (sametypesequence.empty()) return true; return sametypesequence.find_first_of("mlgxty")!=std::string::npos; } bool DictBase::SearchData(std::vector<std::string> &SearchWords, guint32 idxitem_offset, guint32 idxitem_size, gchar *origin_data) { int nWord = SearchWords.size(); std::vector<bool> WordFind(nWord, false); int nfound=0; if (dictfile) fseek(dictfile, idxitem_offset, SEEK_SET); if (dictfile) fread(origin_data, idxitem_size, 1, dictfile); else dictdzfile->read(origin_data, idxitem_offset, idxitem_size); gchar *p = origin_data; guint32 sec_size; int j; if (!sametypesequence.empty()) { gint sametypesequence_len = sametypesequence.length(); for (int i=0; i<sametypesequence_len-1; i++) { switch (sametypesequence[i]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': for (j=0; j<nWord; j++) if (!WordFind[j] && strstr(p, SearchWords[j].c_str())) { WordFind[j] = true; ++nfound; } if (nfound==nWord) return true; sec_size = strlen(p)+1; p+=sec_size; break; default: if (g_ascii_isupper(sametypesequence[i])) { sec_size = *reinterpret_cast<guint32 *>(p); sec_size += sizeof(guint32); } else { sec_size = strlen(p)+1; } p+=sec_size; } } switch (sametypesequence[sametypesequence_len-1]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': sec_size = idxitem_size - (p-origin_data); for (j=0; j<nWord; j++) if (!WordFind[j] && g_strstr_len(p, sec_size, SearchWords[j].c_str())) { WordFind[j] = true; ++nfound; } if (nfound==nWord) return true; break; } } else { while (guint32(p - origin_data)<idxitem_size) { switch (*p) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': for (j=0; j<nWord; j++) if (!WordFind[j] && strstr(p, SearchWords[j].c_str())) { WordFind[j] = true; ++nfound; } if (nfound==nWord) return true; sec_size = strlen(p)+1; p+=sec_size; break; default: if (g_ascii_isupper(*p)) { sec_size = *reinterpret_cast<guint32 *>(p); sec_size += sizeof(guint32); } else { sec_size = strlen(p)+1; } p+=sec_size; } } } return false; } class offset_index : public index_file { public: offset_index() : idxfile(NULL) {} ~offset_index(); bool load(const std::string& url, gulong wc, gulong fsize); const gchar *get_key(glong idx); void get_data(glong idx); const gchar *get_key_and_data(glong idx); bool lookup(const char *str, glong &idx); private: static const gint ENTR_PER_PAGE=32; static const char *CACHE_MAGIC; std::vector<guint32> wordoffset; FILE *idxfile; gulong wordcount; gchar wordentry_buf[256+sizeof(guint32)*2]; // The length of "word_str" should be less than 256. See src/tools/DICTFILE_FORMAT. struct index_entry { glong idx; std::string keystr; void assign(glong i, const std::string& str) { idx=i; keystr.assign(str); } }; index_entry first, last, middle, real_last; struct page_entry { gchar *keystr; guint32 off, size; }; std::vector<gchar> page_data; struct page_t { glong idx; page_entry entries[ENTR_PER_PAGE]; page_t(): idx(-1) {} void fill(gchar *data, gint nent, glong idx_); } page; gulong load_page(glong page_idx); const gchar *read_first_on_page_key(glong page_idx); const gchar *get_first_on_page_key(glong page_idx); bool load_cache(const std::string& url); bool save_cache(const std::string& url); static strlist_t get_cache_variant(const std::string& url); }; const char *offset_index::CACHE_MAGIC="StarDict's Cache, Version: 0.1"; class wordlist_index : public index_file { public: wordlist_index() : idxdatabuf(NULL) {} ~wordlist_index(); bool load(const std::string& url, gulong wc, gulong fsize); const gchar *get_key(glong idx); void get_data(glong idx); const gchar *get_key_and_data(glong idx); bool lookup(const char *str, glong &idx); private: gchar *idxdatabuf; std::vector<gchar *> wordlist; }; void offset_index::page_t::fill(gchar *data, gint nent, glong idx_) { idx=idx_; gchar *p=data; glong len; for (gint i=0; i<nent; ++i) { entries[i].keystr=p; len=strlen(p); p+=len+1; - entries[i].off=g_ntohl(*reinterpret_cast<guint32 *>(p)); + /* + * Can not use typecasting here, because *data does not have + * to be alligned and unalligned access fails on some architectures. + */ + entries[i].off=((unsigned char)p[0] << 24) | ((unsigned char)p[1] << 16) | ((unsigned char)p[2] << 8) | (unsigned char)p[3]; p+=sizeof(guint32); - entries[i].size=g_ntohl(*reinterpret_cast<guint32 *>(p)); + entries[i].size=((unsigned char)p[0] << 24) | ((unsigned char)p[1] << 16) | ((unsigned char)p[2] << 8) | (unsigned char)p[3]; p+=sizeof(guint32); } } offset_index::~offset_index() { if (idxfile) fclose(idxfile); } inline const gchar *offset_index::read_first_on_page_key(glong page_idx) { fseek(idxfile, wordoffset[page_idx], SEEK_SET); guint32 page_size=wordoffset[page_idx+1]-wordoffset[page_idx]; guint32 min = (sizeof(wordentry_buf) < page_size ? sizeof(wordentry_buf) : page_size); fread(wordentry_buf, min, 1, idxfile); //TODO: check returned values, deal with word entry that strlen>255. return wordentry_buf; } inline const gchar *offset_index::get_first_on_page_key(glong page_idx) { if (page_idx<middle.idx) { if (page_idx==first.idx) return first.keystr.c_str(); return read_first_on_page_key(page_idx); } else if (page_idx>middle.idx) { if (page_idx==last.idx) return last.keystr.c_str(); return read_first_on_page_key(page_idx); } else return middle.keystr.c_str(); } bool offset_index::load_cache(const std::string& url) { strlist_t vars=get_cache_variant(url); for (strlist_t::const_iterator it=vars.begin(); it!=vars.end(); ++it) { struct stat idxstat, cachestat; if (g_stat(url.c_str(), &idxstat)!=0 || g_stat(it->c_str(), &cachestat)!=0) continue; if (cachestat.st_mtime<idxstat.st_mtime) continue; MapFile mf; if (!mf.open(it->c_str(), cachestat.st_size)) continue; if (strncmp(mf.begin(), CACHE_MAGIC, strlen(CACHE_MAGIC))!=0) continue; memcpy(&wordoffset[0], mf.begin()+strlen(CACHE_MAGIC), wordoffset.size()*sizeof(wordoffset[0])); return true; } return false; } strlist_t offset_index::get_cache_variant(const std::string& url) { strlist_t res; res.push_back(url+".oft"); if (!g_file_test(g_get_user_cache_dir(), G_FILE_TEST_EXISTS) && g_mkdir(g_get_user_cache_dir(), 0700)==-1) return res; std::string cache_dir=std::string(g_get_user_cache_dir())+G_DIR_SEPARATOR_S+"sdcv"; if (!g_file_test(cache_dir.c_str(), G_FILE_TEST_EXISTS)) { if (g_mkdir(cache_dir.c_str(), 0700)==-1) return res; } else if (!g_file_test(cache_dir.c_str(), G_FILE_TEST_IS_DIR)) return res; gchar *base=g_path_get_basename(url.c_str()); res.push_back(cache_dir+G_DIR_SEPARATOR_S+base+".oft"); g_free(base); return res; } bool offset_index::save_cache(const std::string& url) { strlist_t vars=get_cache_variant(url); for (strlist_t::const_iterator it=vars.begin(); it!=vars.end(); ++it) { FILE *out=fopen(it->c_str(), "wb"); if (!out) continue; if (fwrite(CACHE_MAGIC, 1, strlen(CACHE_MAGIC), out)!=strlen(CACHE_MAGIC)) continue; if (fwrite(&wordoffset[0], sizeof(wordoffset[0]), wordoffset.size(), out)!=wordoffset.size()) continue; fclose(out); printf("save to cache %s\n", url.c_str()); return true; } return false; } bool offset_index::load(const std::string& url, gulong wc, gulong fsize) { wordcount=wc; gulong npages=(wc-1)/ENTR_PER_PAGE+2; wordoffset.resize(npages); if (!load_cache(url)) {//map file will close after finish of block MapFile map_file; if (!map_file.open(url.c_str(), fsize)) return false; const gchar *idxdatabuffer=map_file.begin(); const gchar *p1 = idxdatabuffer; gulong index_size; guint32 j=0; for (guint32 i=0; i<wc; i++) { index_size=strlen(p1) +1 + 2*sizeof(guint32); if (i % ENTR_PER_PAGE==0) { wordoffset[j]=p1-idxdatabuffer; ++j; } p1 += index_size; } wordoffset[j]=p1-idxdatabuffer; if (!save_cache(url)) fprintf(stderr, "cache update failed\n"); } if (!(idxfile = fopen(url.c_str(), "rb"))) { wordoffset.resize(0); return false; } first.assign(0, read_first_on_page_key(0)); last.assign(wordoffset.size()-2, read_first_on_page_key(wordoffset.size()-2)); middle.assign((wordoffset.size()-2)/2, read_first_on_page_key((wordoffset.size()-2)/2)); real_last.assign(wc-1, get_key(wc-1)); return true; } inline gulong offset_index::load_page(glong page_idx) { gulong nentr=ENTR_PER_PAGE; if (page_idx==glong(wordoffset.size()-2)) if ((nentr=wordcount%ENTR_PER_PAGE)==0) nentr=ENTR_PER_PAGE; if (page_idx!=page.idx) { page_data.resize(wordoffset[page_idx+1]-wordoffset[page_idx]); fseek(idxfile, wordoffset[page_idx], SEEK_SET); fread(&page_data[0], 1, page_data.size(), idxfile); page.fill(&page_data[0], nentr, page_idx); } return nentr; } const gchar *offset_index::get_key(glong idx) { load_page(idx/ENTR_PER_PAGE); glong idx_in_page=idx%ENTR_PER_PAGE; wordentry_offset=page.entries[idx_in_page].off; wordentry_size=page.entries[idx_in_page].size; return page.entries[idx_in_page].keystr; } void offset_index::get_data(glong idx) { get_key(idx); } const gchar *offset_index::get_key_and_data(glong idx) { return get_key(idx); } bool offset_index::lookup(const char *str, glong &idx) { bool bFound=false; glong iFrom; glong iTo=wordoffset.size()-2; gint cmpint; glong iThisIndex; if (stardict_strcmp(str, first.keystr.c_str())<0) { idx = 0; return false; } else if (stardict_strcmp(str, real_last.keystr.c_str()) >0) { idx = INVALID_INDEX; return false; } else { iFrom=0; iThisIndex=0; while (iFrom<=iTo) { iThisIndex=(iFrom+iTo)/2; cmpint = stardict_strcmp(str, get_first_on_page_key(iThisIndex)); if (cmpint>0) iFrom=iThisIndex+1; else if (cmpint<0) iTo=iThisIndex-1; else { bFound=true; break; } } if (!bFound) idx = iTo; //prev else idx = iThisIndex; } if (!bFound) { gulong netr=load_page(idx); iFrom=1; // Needn't search the first word anymore. iTo=netr-1; iThisIndex=0; while (iFrom<=iTo) { iThisIndex=(iFrom+iTo)/2; cmpint = stardict_strcmp(str, page.entries[iThisIndex].keystr); if (cmpint>0) iFrom=iThisIndex+1; else if (cmpint<0) iTo=iThisIndex-1; else { bFound=true; break; } } idx*=ENTR_PER_PAGE; if (!bFound) idx += iFrom; //next else idx += iThisIndex; } else { idx*=ENTR_PER_PAGE; } return bFound; } wordlist_index::~wordlist_index() { g_free(idxdatabuf); } bool wordlist_index::load(const std::string& url, gulong wc, gulong fsize) { gzFile in = gzopen(url.c_str(), "rb"); if (in == NULL) return false; idxdatabuf = (gchar *)g_malloc(fsize); gulong len = gzread(in, idxdatabuf, fsize); gzclose(in); if ((glong)len < 0) return false; if (len != fsize) return false; wordlist.resize(wc+1); gchar *p1 = idxdatabuf; guint32 i; for (i=0; i<wc; i++) { wordlist[i] = p1; p1 += strlen(p1) +1 + 2*sizeof(guint32); } wordlist[wc] = p1; return true; } const gchar *wordlist_index::get_key(glong idx) { return wordlist[idx]; } void wordlist_index::get_data(glong idx) { gchar *p1 = wordlist[idx]+strlen(wordlist[idx])+sizeof(gchar); wordentry_offset = g_ntohl(*reinterpret_cast<guint32 *>(p1)); p1 += sizeof(guint32); wordentry_size = g_ntohl(*reinterpret_cast<guint32 *>(p1)); } const gchar *wordlist_index::get_key_and_data(glong idx) { get_data(idx); return get_key(idx); } bool wordlist_index::lookup(const char *str, glong &idx) { bool bFound=false; glong iTo=wordlist.size()-2; if (stardict_strcmp(str, get_key(0))<0) { idx = 0; } else if (stardict_strcmp(str, get_key(iTo)) >0) { idx = INVALID_INDEX; } else { glong iThisIndex=0; glong iFrom=0; gint cmpint; while (iFrom<=iTo) { iThisIndex=(iFrom+iTo)/2; cmpint = stardict_strcmp(str, get_key(iThisIndex)); if (cmpint>0) iFrom=iThisIndex+1; else if (cmpint<0) iTo=iThisIndex-1; else { bFound=true; break; } } if (!bFound) idx = iFrom; //next else idx = iThisIndex; } return bFound; } //=================================================================== bool Dict::load(const std::string& ifofilename) { gulong idxfilesize; if (!load_ifofile(ifofilename, idxfilesize)) return false; std::string fullfilename(ifofilename); fullfilename.replace(fullfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "dict.dz"); if (g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS)) { dictdzfile.reset(new dictData); if (!dictdzfile->open(fullfilename, 0)) { //g_print("open file %s failed!\n",fullfilename); return false; } } else { fullfilename.erase(fullfilename.length()-sizeof(".dz")+1, sizeof(".dz")-1); dictfile = fopen(fullfilename.c_str(),"rb"); if (!dictfile) { //g_print("open file %s failed!\n",fullfilename); return false; } } fullfilename=ifofilename; fullfilename.replace(fullfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "idx.gz"); if (g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS)) { idx_file.reset(new wordlist_index); } else { fullfilename.erase(fullfilename.length()-sizeof(".gz")+1, sizeof(".gz")-1); idx_file.reset(new offset_index); } if (!idx_file->load(fullfilename, wordcount, idxfilesize)) return false; //g_print("bookname: %s , wordcount %lu\n", bookname.c_str(), narticles()); return true; } bool Dict::load_ifofile(const std::string& ifofilename, gulong &idxfilesize) { DictInfo dict_info; if (!dict_info.load_from_ifo_file(ifofilename, false)) return false; if (dict_info.wordcount==0) return false; mDict_info = dict_info; ifo_file_name=dict_info.ifo_file_name; wordcount=dict_info.wordcount; bookname=dict_info.bookname; idxfilesize=dict_info.index_file_size; sametypesequence=dict_info.sametypesequence; return true; } bool Dict::LookupWithRule(GPatternSpec *pspec, glong *aIndex, int iBuffLen) { int iIndexCount=0; for(guint32 i=0; i<narticles() && iIndexCount<iBuffLen-1; i++) if (g_pattern_match_string(pspec, get_key(i))) aIndex[iIndexCount++]=i; aIndex[iIndexCount]= -1; // -1 is the end. return (iIndexCount>0); } //=================================================================== Libs::Libs(progress_func_t f) { progress_func=f; iMaxFuzzyDistance = MAX_FUZZY_DISTANCE; //need to read from cfg. } Libs::~Libs() { for (std::vector<Dict *>::iterator p=oLib.begin(); p!=oLib.end(); ++p) delete *p; } void Libs::load_dict(const std::string& url) { Dict *lib=new Dict; if (lib->load(url)) oLib.push_back(lib); else delete lib; } class DictLoader { public: DictLoader(Libs& lib_): lib(lib_) {} void operator()(const std::string& url, bool disable) { if (!disable) lib.load_dict(url); } private: Libs& lib; }; void Libs::load(const strlist_t& dicts_dirs, const strlist_t& order_list, const strlist_t& disable_list) { for_each_file(dicts_dirs, ".ifo", order_list, disable_list, DictLoader(*this)); } class DictReLoader { public: DictReLoader(std::vector<Dict *> &p, std::vector<Dict *> &f, Libs& lib_) : prev(p), future(f), lib(lib_) { } void operator()(const std::string& url, bool disable) { if (!disable) { Dict *dict=find(url); if (dict) future.push_back(dict); else lib.load_dict(url); } } private: std::vector<Dict *> &prev; std::vector<Dict *> &future; Libs& lib; Dict *find(const std::string& url) { std::vector<Dict *>::iterator it; for (it=prev.begin(); it!=prev.end(); ++it) if ((*it)->ifofilename()==url) break; if (it!=prev.end()) { Dict *res=*it; prev.erase(it); return res; } return NULL; } }; void Libs::reload(const strlist_t& dicts_dirs, const strlist_t& order_list, const strlist_t& disable_list) { std::vector<Dict *> prev(oLib); oLib.clear(); for_each_file(dicts_dirs, ".ifo", order_list, disable_list, DictReLoader(prev, oLib, *this)); for (std::vector<Dict *>::iterator it=prev.begin(); it!=prev.end(); ++it) delete *it; } const gchar *Libs::poGetCurrentWord(glong * iCurrent) { const gchar *poCurrentWord = NULL; const gchar *word; for (std::vector<Dict *>::size_type iLib=0; iLib<oLib.size(); iLib++) { if (iCurrent[iLib]==INVALID_INDEX) continue; if ( iCurrent[iLib]>=narticles(iLib) || iCurrent[iLib]<0) continue; if ( poCurrentWord == NULL ) { poCurrentWord = poGetWord(iCurrent[iLib],iLib); } else { word = poGetWord(iCurrent[iLib],iLib); if (stardict_strcmp(poCurrentWord, word) > 0 ) poCurrentWord = word; } } return poCurrentWord; } const gchar * Libs::poGetNextWord(const gchar *sWord, glong *iCurrent) { // the input can be: // (word,iCurrent),read word,write iNext to iCurrent,and return next word. used by TopWin::NextCallback(); // (NULL,iCurrent),read iCurrent,write iNext to iCurrent,and return next word. used by AppCore::ListWords();
radekp/qdictopia
e5f439b414cf9823bcc48ac828578f90c30b766b
Make it working on PC in QtCreator and qbuild project file.
diff --git a/qbuild.pro b/qbuild.pro new file mode 100644 index 0000000..d27e2fe --- /dev/null +++ b/qbuild.pro @@ -0,0 +1,87 @@ +TEMPLATE=app +TARGET=qdictopia + +CONFIG+=qtopia +DEFINES+=QTOPIA + +# I18n info +STRING_LANGUAGE=en_US +LANGUAGES=en_US + +INCLUDEPATH+=/usr/include/glib-2.0 \ + /usr/lib/glib-2.0/include + +LIBS+=-lglib-2.0 + +# Package info +pkg [ + name=qdictopia + desc="A Dictionary Program for StarDict" + license=GPLv2 + version=1.0 + maintainer="Radek Polak <[email protected]>" +] + +# Input files +HEADERS=\ + src/mainwindow.h \ + src/wordbrowser.h \ + src/qdictopia.h \ + src/dictbrowser.h \ + src/lib/dictziplib.hpp \ + src/lib/distance.h \ + src/lib/file.hpp \ + src/lib/lib.h \ + src/lib/mapfile.hpp + +SOURCES=\ + src/main.cpp \ + src/mainwindow.cpp \ + src/wordbrowser.cpp \ + src/qdictopia.cpp \ + src/dictbrowser.cpp \ + src/lib/dictziplib.cpp \ + src/lib/distance.cpp \ + src/lib/lib.cpp + +# Install rules +target [ + hint=sxe + domain=untrusted +] + +desktop [ + hint=desktop + files=qdictopia.desktop + path=/apps/Applications +] + +pics [ + hint=pics + files=pics/* + path=/pics/qdictopia +] + +help [ + hint=help + source=help + files=*.html +] + +HEADERS += src/mainwindow.h \ + src/wordbrowser.h \ + src/qdictopia.h \ + src/dictbrowser.h \ + src/lib/dictziplib.hpp \ + src/lib/distance.h \ + src/lib/file.hpp \ + src/lib/lib.h \ + src/lib/mapfile.hpp +SOURCES += src/main.cpp \ + src/mainwindow.cpp \ + src/wordbrowser.cpp \ + src/qdictopia.cpp \ + src/dictbrowser.cpp \ + src/lib/dictziplib.cpp \ + src/lib/distance.cpp \ + src/lib/lib.cpp \ No newline at end of file diff --git a/src/lib/lib.cpp b/src/lib/lib.cpp index 9b7e4f4..55a859d 100644 --- a/src/lib/lib.cpp +++ b/src/lib/lib.cpp @@ -4,1025 +4,1026 @@ #include <algorithm> #include <cstring> #include <cctype> #include <sys/stat.h> #include <zlib.h> #include <glib/gstdio.h> #include "distance.h" #include "file.hpp" #include "mapfile.hpp" #include "lib.h" // Notice: read src/tools/DICTFILE_FORMAT for the dictionary // file's format information! static inline bool bIsVowel(gchar inputchar) { gchar ch = g_ascii_toupper(inputchar); return( ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U' ); } static bool bIsPureEnglish(const gchar *str) { // i think this should work even when it is UTF8 string :). for (int i=0; str[i]!=0; i++) //if(str[i]<0) //if(str[i]<32 || str[i]>126) // tab equal 9,so this is not OK. // Better use isascii() but not str[i]<0 while char is default unsigned in arm if (!isascii(str[i])) return false; return true; } static inline gint stardict_strcmp(const gchar *s1, const gchar *s2) { gint a=g_ascii_strcasecmp(s1, s2); if (a == 0) return strcmp(s1, s2); else return a; } bool DictInfo::load_from_ifo_file(const std::string& ifofilename, bool istreedict) { ifo_file_name=ifofilename; gchar *buffer; if (!g_file_get_contents(ifofilename.c_str(), &buffer, NULL, NULL)) return false; #define TREEDICT_MAGIC_DATA "StarDict's treedict ifo file\nversion=2.4.2\n" #define DICT_MAGIC_DATA "StarDict's dict ifo file\nversion=2.4.2\n" const gchar *magic_data=istreedict ? TREEDICT_MAGIC_DATA : DICT_MAGIC_DATA; if (!g_str_has_prefix(buffer, magic_data)) { g_free(buffer); return false; } gchar *p1,*p2,*p3; p1 = buffer + strlen(magic_data)-1; p2 = strstr(p1,"\nwordcount="); if (!p2) { g_free(buffer); return false; } p3 = strchr(p2+ sizeof("\nwordcount=")-1,'\n'); gchar *tmpstr = (gchar *)g_memdup(p2+sizeof("\nwordcount=")-1, p3-(p2+sizeof("\nwordcount=")-1)+1); tmpstr[p3-(p2+sizeof("\nwordcount=")-1)] = '\0'; wordcount = atol(tmpstr); g_free(tmpstr); if (istreedict) { p2 = strstr(p1,"\ntdxfilesize="); if (!p2) { g_free(buffer); return false; } p3 = strchr(p2+ sizeof("\ntdxfilesize=")-1,'\n'); tmpstr = (gchar *)g_memdup(p2+sizeof("\ntdxfilesize=")-1, p3-(p2+sizeof("\ntdxfilesize=")-1)+1); tmpstr[p3-(p2+sizeof("\ntdxfilesize=")-1)] = '\0'; index_file_size = atol(tmpstr); g_free(tmpstr); } else { p2 = strstr(p1,"\nidxfilesize="); if (!p2) { g_free(buffer); return false; } p3 = strchr(p2+ sizeof("\nidxfilesize=")-1,'\n'); tmpstr = (gchar *)g_memdup(p2+sizeof("\nidxfilesize=")-1, p3-(p2+sizeof("\nidxfilesize=")-1)+1); tmpstr[p3-(p2+sizeof("\nidxfilesize=")-1)] = '\0'; index_file_size = atol(tmpstr); g_free(tmpstr); } p2 = strstr(p1,"\nbookname="); if (!p2) { g_free(buffer); return false; } p2 = p2 + sizeof("\nbookname=") -1; p3 = strchr(p2, '\n'); bookname.assign(p2, p3-p2); p2 = strstr(p1,"\nauthor="); if (p2) { p2 = p2 + sizeof("\nauthor=") -1; p3 = strchr(p2, '\n'); author.assign(p2, p3-p2); } p2 = strstr(p1,"\nemail="); if (p2) { p2 = p2 + sizeof("\nemail=") -1; p3 = strchr(p2, '\n'); email.assign(p2, p3-p2); } p2 = strstr(p1,"\nwebsite="); if (p2) { p2 = p2 + sizeof("\nwebsite=") -1; p3 = strchr(p2, '\n'); website.assign(p2, p3-p2); } p2 = strstr(p1,"\ndate="); if (p2) { p2 = p2 + sizeof("\ndate=") -1; p3 = strchr(p2, '\n'); date.assign(p2, p3-p2); } p2 = strstr(p1,"\ndescription="); if (p2) { p2 = p2 + sizeof("\ndescription=")-1; p3 = strchr(p2, '\n'); description.assign(p2, p3-p2); } p2 = strstr(p1,"\nsametypesequence="); if (p2) { p2+=sizeof("\nsametypesequence=")-1; p3 = strchr(p2, '\n'); sametypesequence.assign(p2, p3-p2); } g_free(buffer); return true; } //=================================================================== DictBase::DictBase() { dictfile = NULL; cache_cur =0; } DictBase::~DictBase() { if (dictfile) fclose(dictfile); } gchar* DictBase::GetWordData(guint32 idxitem_offset, guint32 idxitem_size) { for (int i=0; i<WORDDATA_CACHE_NUM; i++) if (cache[i].data && cache[i].offset == idxitem_offset) return cache[i].data; if (dictfile) fseek(dictfile, idxitem_offset, SEEK_SET); gchar *data; if (!sametypesequence.empty()) { gchar *origin_data = (gchar *)g_malloc(idxitem_size); if (dictfile) fread(origin_data, idxitem_size, 1, dictfile); else dictdzfile->read(origin_data, idxitem_offset, idxitem_size); guint32 data_size; gint sametypesequence_len = sametypesequence.length(); //there have sametypesequence_len char being omitted. data_size = idxitem_size + sizeof(guint32) + sametypesequence_len; //if the last item's size is determined by the end up '\0',then +=sizeof(gchar); //if the last item's size is determined by the head guint32 type data,then +=sizeof(guint32); switch (sametypesequence[sametypesequence_len-1]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': data_size += sizeof(gchar); break; case 'W': case 'P': data_size += sizeof(guint32); break; default: if (g_ascii_isupper(sametypesequence[sametypesequence_len-1])) data_size += sizeof(guint32); else data_size += sizeof(gchar); break; } data = (gchar *)g_malloc(data_size); gchar *p1,*p2; p1 = data + sizeof(guint32); p2 = origin_data; guint32 sec_size; //copy the head items. for (int i=0; i<sametypesequence_len-1; i++) { *p1=sametypesequence[i]; p1+=sizeof(gchar); switch (sametypesequence[i]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': sec_size = strlen(p2)+1; memcpy(p1, p2, sec_size); p1+=sec_size; p2+=sec_size; break; case 'W': case 'P': sec_size = *reinterpret_cast<guint32 *>(p2); sec_size += sizeof(guint32); memcpy(p1, p2, sec_size); p1+=sec_size; p2+=sec_size; break; default: if (g_ascii_isupper(sametypesequence[i])) { sec_size = *reinterpret_cast<guint32 *>(p2); sec_size += sizeof(guint32); } else { sec_size = strlen(p2)+1; } memcpy(p1, p2, sec_size); p1+=sec_size; p2+=sec_size; break; } } //calculate the last item 's size. sec_size = idxitem_size - (p2-origin_data); *p1=sametypesequence[sametypesequence_len-1]; p1+=sizeof(gchar); switch (sametypesequence[sametypesequence_len-1]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': memcpy(p1, p2, sec_size); p1 += sec_size; *p1='\0';//add the end up '\0'; break; case 'W': case 'P': *reinterpret_cast<guint32 *>(p1)=sec_size; p1 += sizeof(guint32); memcpy(p1, p2, sec_size); break; default: if (g_ascii_isupper(sametypesequence[sametypesequence_len-1])) { *reinterpret_cast<guint32 *>(p1)=sec_size; p1 += sizeof(guint32); memcpy(p1, p2, sec_size); } else { memcpy(p1, p2, sec_size); p1 += sec_size; *p1='\0'; } break; } g_free(origin_data); *reinterpret_cast<guint32 *>(data)=data_size; } else { data = (gchar *)g_malloc(idxitem_size + sizeof(guint32)); if (dictfile) fread(data+sizeof(guint32), idxitem_size, 1, dictfile); else dictdzfile->read(data+sizeof(guint32), idxitem_offset, idxitem_size); *reinterpret_cast<guint32 *>(data)=idxitem_size+sizeof(guint32); } g_free(cache[cache_cur].data); cache[cache_cur].data = data; cache[cache_cur].offset = idxitem_offset; cache_cur++; if (cache_cur==WORDDATA_CACHE_NUM) cache_cur = 0; return data; } inline bool DictBase::containSearchData() { if (sametypesequence.empty()) return true; return sametypesequence.find_first_of("mlgxty")!=std::string::npos; } bool DictBase::SearchData(std::vector<std::string> &SearchWords, guint32 idxitem_offset, guint32 idxitem_size, gchar *origin_data) { int nWord = SearchWords.size(); std::vector<bool> WordFind(nWord, false); int nfound=0; if (dictfile) fseek(dictfile, idxitem_offset, SEEK_SET); if (dictfile) fread(origin_data, idxitem_size, 1, dictfile); else dictdzfile->read(origin_data, idxitem_offset, idxitem_size); gchar *p = origin_data; guint32 sec_size; int j; if (!sametypesequence.empty()) { gint sametypesequence_len = sametypesequence.length(); for (int i=0; i<sametypesequence_len-1; i++) { switch (sametypesequence[i]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': for (j=0; j<nWord; j++) if (!WordFind[j] && strstr(p, SearchWords[j].c_str())) { WordFind[j] = true; ++nfound; } if (nfound==nWord) return true; sec_size = strlen(p)+1; p+=sec_size; break; default: if (g_ascii_isupper(sametypesequence[i])) { sec_size = *reinterpret_cast<guint32 *>(p); sec_size += sizeof(guint32); } else { sec_size = strlen(p)+1; } p+=sec_size; } } switch (sametypesequence[sametypesequence_len-1]) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': sec_size = idxitem_size - (p-origin_data); for (j=0; j<nWord; j++) if (!WordFind[j] && g_strstr_len(p, sec_size, SearchWords[j].c_str())) { WordFind[j] = true; ++nfound; } if (nfound==nWord) return true; break; } } else { while (guint32(p - origin_data)<idxitem_size) { switch (*p) { case 'm': case 't': case 'y': case 'l': case 'g': case 'x': for (j=0; j<nWord; j++) if (!WordFind[j] && strstr(p, SearchWords[j].c_str())) { WordFind[j] = true; ++nfound; } if (nfound==nWord) return true; sec_size = strlen(p)+1; p+=sec_size; break; default: if (g_ascii_isupper(*p)) { sec_size = *reinterpret_cast<guint32 *>(p); sec_size += sizeof(guint32); } else { sec_size = strlen(p)+1; } p+=sec_size; } } } return false; } class offset_index : public index_file { public: offset_index() : idxfile(NULL) {} ~offset_index(); bool load(const std::string& url, gulong wc, gulong fsize); const gchar *get_key(glong idx); void get_data(glong idx); const gchar *get_key_and_data(glong idx); bool lookup(const char *str, glong &idx); private: static const gint ENTR_PER_PAGE=32; static const char *CACHE_MAGIC; std::vector<guint32> wordoffset; FILE *idxfile; gulong wordcount; gchar wordentry_buf[256+sizeof(guint32)*2]; // The length of "word_str" should be less than 256. See src/tools/DICTFILE_FORMAT. struct index_entry { glong idx; std::string keystr; void assign(glong i, const std::string& str) { idx=i; keystr.assign(str); } }; index_entry first, last, middle, real_last; struct page_entry { gchar *keystr; guint32 off, size; }; std::vector<gchar> page_data; struct page_t { glong idx; page_entry entries[ENTR_PER_PAGE]; page_t(): idx(-1) {} void fill(gchar *data, gint nent, glong idx_); } page; gulong load_page(glong page_idx); const gchar *read_first_on_page_key(glong page_idx); const gchar *get_first_on_page_key(glong page_idx); bool load_cache(const std::string& url); bool save_cache(const std::string& url); static strlist_t get_cache_variant(const std::string& url); }; const char *offset_index::CACHE_MAGIC="StarDict's Cache, Version: 0.1"; class wordlist_index : public index_file { public: wordlist_index() : idxdatabuf(NULL) {} ~wordlist_index(); bool load(const std::string& url, gulong wc, gulong fsize); const gchar *get_key(glong idx); void get_data(glong idx); const gchar *get_key_and_data(glong idx); bool lookup(const char *str, glong &idx); private: gchar *idxdatabuf; std::vector<gchar *> wordlist; }; void offset_index::page_t::fill(gchar *data, gint nent, glong idx_) { idx=idx_; gchar *p=data; glong len; for (gint i=0; i<nent; ++i) { entries[i].keystr=p; len=strlen(p); p+=len+1; entries[i].off=g_ntohl(*reinterpret_cast<guint32 *>(p)); p+=sizeof(guint32); entries[i].size=g_ntohl(*reinterpret_cast<guint32 *>(p)); p+=sizeof(guint32); } } offset_index::~offset_index() { if (idxfile) fclose(idxfile); } inline const gchar *offset_index::read_first_on_page_key(glong page_idx) { fseek(idxfile, wordoffset[page_idx], SEEK_SET); guint32 page_size=wordoffset[page_idx+1]-wordoffset[page_idx]; - fread(wordentry_buf, std::min(sizeof(wordentry_buf), page_size), 1, idxfile); //TODO: check returned values, deal with word entry that strlen>255. + guint32 min = (sizeof(wordentry_buf) < page_size ? sizeof(wordentry_buf) : page_size); + fread(wordentry_buf, min, 1, idxfile); //TODO: check returned values, deal with word entry that strlen>255. return wordentry_buf; } inline const gchar *offset_index::get_first_on_page_key(glong page_idx) { if (page_idx<middle.idx) { if (page_idx==first.idx) return first.keystr.c_str(); return read_first_on_page_key(page_idx); } else if (page_idx>middle.idx) { if (page_idx==last.idx) return last.keystr.c_str(); return read_first_on_page_key(page_idx); } else return middle.keystr.c_str(); } bool offset_index::load_cache(const std::string& url) { strlist_t vars=get_cache_variant(url); for (strlist_t::const_iterator it=vars.begin(); it!=vars.end(); ++it) { struct stat idxstat, cachestat; if (g_stat(url.c_str(), &idxstat)!=0 || g_stat(it->c_str(), &cachestat)!=0) continue; if (cachestat.st_mtime<idxstat.st_mtime) continue; MapFile mf; if (!mf.open(it->c_str(), cachestat.st_size)) continue; if (strncmp(mf.begin(), CACHE_MAGIC, strlen(CACHE_MAGIC))!=0) continue; memcpy(&wordoffset[0], mf.begin()+strlen(CACHE_MAGIC), wordoffset.size()*sizeof(wordoffset[0])); return true; } return false; } strlist_t offset_index::get_cache_variant(const std::string& url) { strlist_t res; res.push_back(url+".oft"); if (!g_file_test(g_get_user_cache_dir(), G_FILE_TEST_EXISTS) && g_mkdir(g_get_user_cache_dir(), 0700)==-1) return res; std::string cache_dir=std::string(g_get_user_cache_dir())+G_DIR_SEPARATOR_S+"sdcv"; if (!g_file_test(cache_dir.c_str(), G_FILE_TEST_EXISTS)) { if (g_mkdir(cache_dir.c_str(), 0700)==-1) return res; } else if (!g_file_test(cache_dir.c_str(), G_FILE_TEST_IS_DIR)) return res; gchar *base=g_path_get_basename(url.c_str()); res.push_back(cache_dir+G_DIR_SEPARATOR_S+base+".oft"); g_free(base); return res; } bool offset_index::save_cache(const std::string& url) { strlist_t vars=get_cache_variant(url); for (strlist_t::const_iterator it=vars.begin(); it!=vars.end(); ++it) { FILE *out=fopen(it->c_str(), "wb"); if (!out) continue; if (fwrite(CACHE_MAGIC, 1, strlen(CACHE_MAGIC), out)!=strlen(CACHE_MAGIC)) continue; if (fwrite(&wordoffset[0], sizeof(wordoffset[0]), wordoffset.size(), out)!=wordoffset.size()) continue; fclose(out); printf("save to cache %s\n", url.c_str()); return true; } return false; } bool offset_index::load(const std::string& url, gulong wc, gulong fsize) { wordcount=wc; gulong npages=(wc-1)/ENTR_PER_PAGE+2; wordoffset.resize(npages); if (!load_cache(url)) {//map file will close after finish of block MapFile map_file; if (!map_file.open(url.c_str(), fsize)) return false; const gchar *idxdatabuffer=map_file.begin(); const gchar *p1 = idxdatabuffer; gulong index_size; guint32 j=0; for (guint32 i=0; i<wc; i++) { index_size=strlen(p1) +1 + 2*sizeof(guint32); if (i % ENTR_PER_PAGE==0) { wordoffset[j]=p1-idxdatabuffer; ++j; } p1 += index_size; } wordoffset[j]=p1-idxdatabuffer; if (!save_cache(url)) fprintf(stderr, "cache update failed\n"); } if (!(idxfile = fopen(url.c_str(), "rb"))) { wordoffset.resize(0); return false; } first.assign(0, read_first_on_page_key(0)); last.assign(wordoffset.size()-2, read_first_on_page_key(wordoffset.size()-2)); middle.assign((wordoffset.size()-2)/2, read_first_on_page_key((wordoffset.size()-2)/2)); real_last.assign(wc-1, get_key(wc-1)); return true; } inline gulong offset_index::load_page(glong page_idx) { gulong nentr=ENTR_PER_PAGE; if (page_idx==glong(wordoffset.size()-2)) if ((nentr=wordcount%ENTR_PER_PAGE)==0) nentr=ENTR_PER_PAGE; if (page_idx!=page.idx) { page_data.resize(wordoffset[page_idx+1]-wordoffset[page_idx]); fseek(idxfile, wordoffset[page_idx], SEEK_SET); fread(&page_data[0], 1, page_data.size(), idxfile); page.fill(&page_data[0], nentr, page_idx); } return nentr; } const gchar *offset_index::get_key(glong idx) { load_page(idx/ENTR_PER_PAGE); glong idx_in_page=idx%ENTR_PER_PAGE; wordentry_offset=page.entries[idx_in_page].off; wordentry_size=page.entries[idx_in_page].size; return page.entries[idx_in_page].keystr; } void offset_index::get_data(glong idx) { get_key(idx); } const gchar *offset_index::get_key_and_data(glong idx) { return get_key(idx); } bool offset_index::lookup(const char *str, glong &idx) { bool bFound=false; glong iFrom; glong iTo=wordoffset.size()-2; gint cmpint; glong iThisIndex; if (stardict_strcmp(str, first.keystr.c_str())<0) { idx = 0; return false; } else if (stardict_strcmp(str, real_last.keystr.c_str()) >0) { idx = INVALID_INDEX; return false; } else { iFrom=0; iThisIndex=0; while (iFrom<=iTo) { iThisIndex=(iFrom+iTo)/2; cmpint = stardict_strcmp(str, get_first_on_page_key(iThisIndex)); if (cmpint>0) iFrom=iThisIndex+1; else if (cmpint<0) iTo=iThisIndex-1; else { bFound=true; break; } } if (!bFound) idx = iTo; //prev else idx = iThisIndex; } if (!bFound) { gulong netr=load_page(idx); iFrom=1; // Needn't search the first word anymore. iTo=netr-1; iThisIndex=0; while (iFrom<=iTo) { iThisIndex=(iFrom+iTo)/2; cmpint = stardict_strcmp(str, page.entries[iThisIndex].keystr); if (cmpint>0) iFrom=iThisIndex+1; else if (cmpint<0) iTo=iThisIndex-1; else { bFound=true; break; } } idx*=ENTR_PER_PAGE; if (!bFound) idx += iFrom; //next else idx += iThisIndex; } else { idx*=ENTR_PER_PAGE; } return bFound; } wordlist_index::~wordlist_index() { g_free(idxdatabuf); } bool wordlist_index::load(const std::string& url, gulong wc, gulong fsize) { gzFile in = gzopen(url.c_str(), "rb"); if (in == NULL) return false; idxdatabuf = (gchar *)g_malloc(fsize); gulong len = gzread(in, idxdatabuf, fsize); gzclose(in); if ((glong)len < 0) return false; if (len != fsize) return false; wordlist.resize(wc+1); gchar *p1 = idxdatabuf; guint32 i; for (i=0; i<wc; i++) { wordlist[i] = p1; p1 += strlen(p1) +1 + 2*sizeof(guint32); } wordlist[wc] = p1; return true; } const gchar *wordlist_index::get_key(glong idx) { return wordlist[idx]; } void wordlist_index::get_data(glong idx) { gchar *p1 = wordlist[idx]+strlen(wordlist[idx])+sizeof(gchar); wordentry_offset = g_ntohl(*reinterpret_cast<guint32 *>(p1)); p1 += sizeof(guint32); wordentry_size = g_ntohl(*reinterpret_cast<guint32 *>(p1)); } const gchar *wordlist_index::get_key_and_data(glong idx) { get_data(idx); return get_key(idx); } bool wordlist_index::lookup(const char *str, glong &idx) { bool bFound=false; glong iTo=wordlist.size()-2; if (stardict_strcmp(str, get_key(0))<0) { idx = 0; } else if (stardict_strcmp(str, get_key(iTo)) >0) { idx = INVALID_INDEX; } else { glong iThisIndex=0; glong iFrom=0; gint cmpint; while (iFrom<=iTo) { iThisIndex=(iFrom+iTo)/2; cmpint = stardict_strcmp(str, get_key(iThisIndex)); if (cmpint>0) iFrom=iThisIndex+1; else if (cmpint<0) iTo=iThisIndex-1; else { bFound=true; break; } } if (!bFound) idx = iFrom; //next else idx = iThisIndex; } return bFound; } //=================================================================== bool Dict::load(const std::string& ifofilename) { gulong idxfilesize; if (!load_ifofile(ifofilename, idxfilesize)) return false; std::string fullfilename(ifofilename); fullfilename.replace(fullfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "dict.dz"); if (g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS)) { dictdzfile.reset(new dictData); if (!dictdzfile->open(fullfilename, 0)) { //g_print("open file %s failed!\n",fullfilename); return false; } } else { fullfilename.erase(fullfilename.length()-sizeof(".dz")+1, sizeof(".dz")-1); dictfile = fopen(fullfilename.c_str(),"rb"); if (!dictfile) { //g_print("open file %s failed!\n",fullfilename); return false; } } fullfilename=ifofilename; fullfilename.replace(fullfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "idx.gz"); if (g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS)) { idx_file.reset(new wordlist_index); } else { fullfilename.erase(fullfilename.length()-sizeof(".gz")+1, sizeof(".gz")-1); idx_file.reset(new offset_index); } if (!idx_file->load(fullfilename, wordcount, idxfilesize)) return false; //g_print("bookname: %s , wordcount %lu\n", bookname.c_str(), narticles()); return true; } bool Dict::load_ifofile(const std::string& ifofilename, gulong &idxfilesize) { DictInfo dict_info; if (!dict_info.load_from_ifo_file(ifofilename, false)) return false; if (dict_info.wordcount==0) return false; mDict_info = dict_info; ifo_file_name=dict_info.ifo_file_name; wordcount=dict_info.wordcount; bookname=dict_info.bookname; idxfilesize=dict_info.index_file_size; sametypesequence=dict_info.sametypesequence; return true; } bool Dict::LookupWithRule(GPatternSpec *pspec, glong *aIndex, int iBuffLen) { int iIndexCount=0; for(guint32 i=0; i<narticles() && iIndexCount<iBuffLen-1; i++) if (g_pattern_match_string(pspec, get_key(i))) aIndex[iIndexCount++]=i; aIndex[iIndexCount]= -1; // -1 is the end. return (iIndexCount>0); } //=================================================================== Libs::Libs(progress_func_t f) { progress_func=f; iMaxFuzzyDistance = MAX_FUZZY_DISTANCE; //need to read from cfg. } Libs::~Libs() { for (std::vector<Dict *>::iterator p=oLib.begin(); p!=oLib.end(); ++p) delete *p; } void Libs::load_dict(const std::string& url) { Dict *lib=new Dict; if (lib->load(url)) oLib.push_back(lib); else delete lib; } class DictLoader { public: DictLoader(Libs& lib_): lib(lib_) {} void operator()(const std::string& url, bool disable) { if (!disable) lib.load_dict(url); } private: Libs& lib; }; void Libs::load(const strlist_t& dicts_dirs, const strlist_t& order_list, const strlist_t& disable_list) { for_each_file(dicts_dirs, ".ifo", order_list, disable_list, DictLoader(*this)); } class DictReLoader { public: DictReLoader(std::vector<Dict *> &p, std::vector<Dict *> &f, Libs& lib_) : prev(p), future(f), lib(lib_) { } void operator()(const std::string& url, bool disable) { if (!disable) { Dict *dict=find(url); if (dict) future.push_back(dict); else lib.load_dict(url); } } private: std::vector<Dict *> &prev; std::vector<Dict *> &future; Libs& lib; Dict *find(const std::string& url) { std::vector<Dict *>::iterator it; for (it=prev.begin(); it!=prev.end(); ++it) if ((*it)->ifofilename()==url) break; if (it!=prev.end()) { Dict *res=*it; prev.erase(it); return res; } return NULL; } }; void Libs::reload(const strlist_t& dicts_dirs, const strlist_t& order_list, const strlist_t& disable_list) { std::vector<Dict *> prev(oLib); oLib.clear(); for_each_file(dicts_dirs, ".ifo", order_list, disable_list, DictReLoader(prev, oLib, *this)); for (std::vector<Dict *>::iterator it=prev.begin(); it!=prev.end(); ++it) delete *it; } const gchar *Libs::poGetCurrentWord(glong * iCurrent) { const gchar *poCurrentWord = NULL; const gchar *word; for (std::vector<Dict *>::size_type iLib=0; iLib<oLib.size(); iLib++) { if (iCurrent[iLib]==INVALID_INDEX) continue; if ( iCurrent[iLib]>=narticles(iLib) || iCurrent[iLib]<0) continue; if ( poCurrentWord == NULL ) { poCurrentWord = poGetWord(iCurrent[iLib],iLib); } else { word = poGetWord(iCurrent[iLib],iLib); if (stardict_strcmp(poCurrentWord, word) > 0 ) poCurrentWord = word; } } return poCurrentWord; } const gchar * Libs::poGetNextWord(const gchar *sWord, glong *iCurrent) { // the input can be: // (word,iCurrent),read word,write iNext to iCurrent,and return next word. used by TopWin::NextCallback(); // (NULL,iCurrent),read iCurrent,write iNext to iCurrent,and return next word. used by AppCore::ListWords(); const gchar *poCurrentWord = NULL; std::vector<Dict *>::size_type iCurrentLib=0; const gchar *word; for (std::vector<Dict *>::size_type iLib=0;iLib<oLib.size();iLib++) { if (sWord) oLib[iLib]->Lookup(sWord, iCurrent[iLib]); if (iCurrent[iLib]==INVALID_INDEX) continue; if (iCurrent[iLib]>=narticles(iLib) || iCurrent[iLib]<0) continue; if (poCurrentWord == NULL ) { poCurrentWord = poGetWord(iCurrent[iLib],iLib); iCurrentLib = iLib; } else { word = poGetWord(iCurrent[iLib],iLib); diff --git a/src/main.cpp b/src/main.cpp index 6e6e2d2..7ece448 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,5 +1,22 @@ +#ifdef QTOPIA + #include <qtopiaapplication.h> #include "qdictopia.h" QTOPIA_ADD_APPLICATION(QTOPIA_TARGET, QDictOpia) QTOPIA_MAIN + +#else // QTOPIA + +#include <QtGui/QApplication> +#include "qdictopia.h" + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + QDictOpia w; + w.show(); + return a.exec(); +} + +#endif // QTOPIA diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 1d619d7..aad16df 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,171 +1,181 @@ #include <QMessageBox> #include <QTimer> #include "mainwindow.h" -MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f), mLineEdit(NULL) +MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags f, QMenu *menu) : QWidget(parent, f), mLineEdit(NULL) { +#ifdef QTOPIA + Q_UNUSED(menu); +#endif + if (loadDicts() == false) { QTimer::singleShot(0, this, SLOT(slotWarning())); } else { // Build UI mLayout = new QGridLayout(this); mLineEdit = new QLineEdit(this); - mLineEdit->setFocusPolicy(Qt::NoFocus); + //mLineEdit->setFocusPolicy(Qt::NoFocus); connect(mLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(slotTextChanged(const QString&))); - mMenu = QSoftMenuBar::menuFor(mLineEdit); +#ifdef QTOPIA + mMenu = QSoftMenuBar::menuFor(mLineEdit); +#else + mMenu = menu; +#endif mActionClear = mMenu->addAction(tr("Clear text"), this, SLOT(slotClearText())); mActionClear->setVisible(false); mActionDList = mMenu->addAction(tr("Dictionaries..."), this, SLOT(slotDictList())); mListWidget = new QListWidget(this); mListWidget->setFocusPolicy(Qt::NoFocus); connect(mListWidget, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(slotItemActivated(QListWidgetItem*))); mLayout->addWidget(mLineEdit, 0, 0); mLayout->addWidget(mListWidget, 1, 0); } } MainWindow::~MainWindow() { if (mLibs) delete mLibs; } void MainWindow::keyPressEvent(QKeyEvent* event) { switch(event->key()) { case Qt::Key_Up: if (mListWidget->count() > 0) { if (mListWidget->currentRow() <= 0) mListWidget->setCurrentRow(mListWidget->count() - 1); else mListWidget->setCurrentRow(mListWidget->currentRow() - 1); } break; case Qt::Key_Down: if (mListWidget->count() > 0) { if (mListWidget->currentRow() < (mListWidget->count() - 1)) mListWidget->setCurrentRow(mListWidget->currentRow() + 1); else mListWidget->setCurrentRow(0); } break; case Qt::Key_Select: QString word; if (mListWidget->currentRow() >= 0) word = mListWidget->item(mListWidget->currentRow())->text(); else word = mLineEdit->text(); mWordBrowser = new WordBrowser(this, Qt::Popup); mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); mWordBrowser->showMaximized(); mWordBrowser->lookup(word, mLibs); break; } QWidget::keyPressEvent(event); } bool MainWindow::slotTextChanged(const QString& text) { glong* index = (glong*)malloc(sizeof(glong) * mLibs->ndicts()); const gchar* word; bool bfound = false; if (text.isEmpty() && mActionClear->isVisible()) mActionClear->setVisible(false); else if (!text.isEmpty() && !mActionClear->isVisible()) mActionClear->setVisible(true); for (int i = 0; i < mLibs->ndicts(); i++) if (mLibs->LookupWord((const gchar*)text.toLatin1().data(), index[i], i)) bfound = true; for (int i = 0; i < mLibs->ndicts(); i++) if (mLibs->LookupSimilarWord((const gchar*)text.toLatin1().data(), index[i], i)) bfound = true; if (bfound) { mListWidget->clear(); word = mLibs->poGetCurrentWord(index); mListWidget->addItem(tr((const char*)word)); for (int j = 0; j < MAX_FUZZY; j++) { if ((word = mLibs->poGetNextWord(NULL, index))) mListWidget->addItem(tr((const char*)word)); else break; } } free(index); return true; } void MainWindow::paintEvent(QPaintEvent* event) { +#ifdef QTOPIA if (mLineEdit) mLineEdit->setEditFocus(true); +#endif QWidget::paintEvent(event); } void MainWindow::slotItemActivated(QListWidgetItem* item) { QString word = item->text(); mWordBrowser = new WordBrowser(this, Qt::Popup); mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); mWordBrowser->showMaximized(); mWordBrowser->lookup(word, mLibs); } void MainWindow::slotClearText() { mLineEdit->clear(); } void MainWindow::slotDictList() { mDictBrowser= new DictBrowser(this, Qt::Popup, mLibs); mDictBrowser->setAttribute(Qt::WA_DeleteOnClose); mDictBrowser->showMaximized(); } void MainWindow::slotWarning() { QMessageBox::warning(this, tr("Dictionary"), tr("There are no dictionary loaded!")); } bool MainWindow::loadDicts() { mLibs = new Libs(); // Retrieve all dict infors mDictDir = QDir(DIC_PATH, "*.ifo"); for (unsigned int i = 0; i < mDictDir.count(); i++) mLibs->load_dict(mDictDir.absoluteFilePath(mDictDir[i]).toLatin1().data()); if (mLibs->ndicts() == 0) return false; else return true; } diff --git a/src/mainwindow.h b/src/mainwindow.h index 4d07093..d61bb39 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -1,57 +1,60 @@ #ifndef MAIN_WINDOW_H #define MAIN_WINDOW_H #include <QWidget> #include <QGridLayout> #include <QLineEdit> #include <QListWidget> #include <QDir> #include <QKeyEvent> -#include <QSoftMenuBar> #include <QMenu> #include <QAction> +#ifdef QTOPIA +#include <QSoftMenuBar> +#endif + #include "lib/lib.h" #include "wordbrowser.h" #include "dictbrowser.h" #define MAX_FUZZY 30 #define DIC_PATH "/usr/share/stardict/dic/" class MainWindow : public QWidget { Q_OBJECT public: - MainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); + MainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0, QMenu *menu = 0); ~MainWindow(); protected: void keyPressEvent(QKeyEvent* event); void paintEvent(QPaintEvent* event); private: bool loadDicts(); private slots: bool slotTextChanged(const QString& text); void slotItemActivated(QListWidgetItem* item); void slotClearText(); void slotDictList(); void slotWarning(); private: QGridLayout* mLayout; QLineEdit* mLineEdit; QListWidget* mListWidget; WordBrowser* mWordBrowser; DictBrowser* mDictBrowser; QMenu* mMenu; QAction* mActionClear; QAction* mActionDList; Libs* mLibs; QDir mDictDir; }; #endif diff --git a/src/qdictopia.cpp b/src/qdictopia.cpp index ee9aacd..af171e7 100644 --- a/src/qdictopia.cpp +++ b/src/qdictopia.cpp @@ -1,9 +1,10 @@ #include "qdictopia.h" QDictOpia::QDictOpia(QWidget* parent, Qt::WindowFlags flags) : QMainWindow(parent, flags) { setWindowTitle(tr("QDictopia")); - mMainWindow = new MainWindow(this); + QMenu *menu = menuBar()->addMenu("&File"); + mMainWindow = new MainWindow(this, 0, menu); setCentralWidget(mMainWindow); } diff --git a/src/qdictopia.h b/src/qdictopia.h index 7a1a7ed..b293190 100644 --- a/src/qdictopia.h +++ b/src/qdictopia.h @@ -1,17 +1,18 @@ #ifndef _QDICTOPIA_H_ #define _QDICTOPIA_H_ #include <QMainWindow> +#include <QMenuBar> #include "mainwindow.h" class QDictOpia : public QMainWindow { public: QDictOpia(QWidget* parent = 0, Qt::WindowFlags flags = 0); private: MainWindow* mMainWindow; }; #endif
radekp/qdictopia
79671ab933178f894660d8daf3f1265553153b1d
QDictopia 0.0.5
diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..864c4b8 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,11 @@ +Author of StarDict: + Hu Zheng <[email protected]> http://forlinux.yeah.net + +Author of sdcv: + Evgeniy Dushistov <[email protected]> + +Author of QStarDict: + Alexander Rodin http://qstardict.ylsoftware.com + +Author of QDictopia: + Luxi Liu <[email protected]> diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 0000000..92f9335 --- /dev/null +++ b/ChangeLog @@ -0,0 +1,21 @@ +* Version 0.0.5 + - Move dictionary files back to StarDict's default path. + - Implement UTF-8 to Unicode conversion to avoid unreadable code. + +* Version 0.0.4 + - New icon changed. + - "Clear text" menu option added. + - "Dictionaries" menu to list available dictionary's information. + +* Version 0.0.3 + - Search quickly & accurately. + - Multi-dictionary support. + +* Version 0.0.2 + - Fix word translation browser to read only. + - Move dictionary files to QTOPIA_HOME/Applications/Dictionary/dic + - Warning if no dictionary file. + - Add help files. + +* Version 0.0.1 + - Initial release. diff --git a/README b/README new file mode 100644 index 0000000..64a0f1d --- /dev/null +++ b/README @@ -0,0 +1,27 @@ +QDictopia is an edition of sdcv/stardict on Qtopia Open Source 4.3.1. It uses sdcv's lib for word lookup and Qt for GUI. + +------------------- +1. Build & Install + + # QTOPIABUILDDIR/bin/qtopiamake + # make & make install + + +2. Dictionary files + + Dictionary files used by QDictopia are from StarDict. By default, it locates in "/usr/share/stardict/dic/". For one dictionary, it includes four types of file: *.dict.dz, *.idx, *.oft, and *.ifo. You could put your own dictionary file in this directory or modify DIC_PATH in the souce code. + + +3. Fonts + + QDictopia uses Wen Quan Yi font.. You could find it in "http://wqy.sourceforge.net/cgi-bin/enindex.cgi". And I use "wqy-unibit" font because Qtopia is unicode based. Put the font file "wqy-unibit.bdf" in the tarball to "$QPEDIR/lib/fonts/". Append a line in the file "$QPEDIR/lib/fonts/fontdir" with following: + + wenquanyi wqy-unibit.bdf FT n 75 160 s + + Then in the file "$QPEDIR/etc/default/Trolltech/qpe.conf", modify: + + [Font] + FontFamily[]=wenquanyi + FontSize[]=6.4 + + Restart Qtopia, then you will see a different font is used. diff --git a/help/html/qdictopia.html b/help/html/qdictopia.html new file mode 100644 index 0000000..ab51b5c --- /dev/null +++ b/help/html/qdictopia.html @@ -0,0 +1,10 @@ + <html> + <head><title>QDictopia</title></head> + <body> + <!--#if expr="$USERGUIDE"--> + <h2>QDictopia</h2> + <!--#endif--> + <p><img src=":image/qdictopia/QDictopia"></p> + <p> A dictionary program ported from StarDict.</p> + </body> + </html> diff --git a/pics/QDictopia.png b/pics/QDictopia.png new file mode 100644 index 0000000..1256873 Binary files /dev/null and b/pics/QDictopia.png differ diff --git a/qdictopia.desktop b/qdictopia.desktop new file mode 100644 index 0000000..62052ea --- /dev/null +++ b/qdictopia.desktop @@ -0,0 +1,10 @@ +[Translation] +File=QtopiaApplications +Context=QDictopia +[Desktop Entry] +Comment[]=A Dictionary Program +Exec=qdictopia +Icon=qdictopia/QDictopia +Type=Application +Name[]=Dictionary +Categories=MainApplications diff --git a/qdictopia.pro b/qdictopia.pro new file mode 100644 index 0000000..fb4b876 --- /dev/null +++ b/qdictopia.pro @@ -0,0 +1,45 @@ +qtopia_project(qtopia app) +TARGET=qdictopia +CONFIG+=qtopia_main no_quicklaunch +INCLUDEPATH += /usr/include/glib-2.0 \ + /usr/lib/glib-2.0/include +LIBS += -lglib-2.0 + +HEADERS += src/mainwindow.h \ + src/wordbrowser.h \ + src/qdictopia.h \ + src/dictbrowser.h \ + src/lib/dictziplib.hpp \ + src/lib/distance.h \ + src/lib/file.hpp \ + src/lib/lib.h \ + src/lib/mapfile.hpp +SOURCES += src/main.cpp \ + src/mainwindow.cpp \ + src/wordbrowser.cpp \ + src/qdictopia.cpp \ + src/dictbrowser.cpp \ + src/lib/dictziplib.cpp \ + src/lib/distance.cpp \ + src/lib/lib.cpp + +help.source=help +help.files=qdictopia* +help.hint=help +INSTALLS+=help + +desktop.files=qdictopia.desktop +desktop.path=/apps/Applications +desktop.hint=desktop +INSTALLS+=desktop + +pics.files=pics/* +pics.path=/pics/qdictopia +pics.hint=pics +INSTALLS+=pics + +pkg.desc=A Dictionary Program from QStarDict +pkg.version=Alpha-x.x.x +pkg.maintainer=Luxi Liu([email protected]) +pkg.license=GPL +pkg.domain=trusted diff --git a/src/dictbrowser.cpp b/src/dictbrowser.cpp new file mode 100644 index 0000000..b94192a --- /dev/null +++ b/src/dictbrowser.cpp @@ -0,0 +1,79 @@ +#include <QTextCodec> +#include "dictbrowser.h" + +DictInfoWidget::DictInfoWidget(QWidget* parent, Qt::WindowFlags f, struct DictInfo info) : QWidget(parent, f), mInfo(info) +{ + QString count; + QString uni_str; + const char* utf8_cstr; + QTextCodec* codec = QTextCodec::codecForName("UTF-8"); + + mLayout = new QGridLayout(this); + + mLabelCount = new QLabel(tr("<qt><b>Word count:</qt></b>"), this); + count.sprintf("%d", mInfo.wordcount); + mLabelCountResult = new QLabel(count, this); + + mLabelAuthor = new QLabel(tr("<qt><b>Author:</qt></b>"), this); + utf8_cstr = mInfo.author.data(); + uni_str = codec->toUnicode(utf8_cstr); + mLabelAuthorResult = new QLabel(uni_str, this); + + mLabelEmail = new QLabel(tr("<qt><b>Email:</qt></b>"), this); + mLabelEmailResult = new QLabel(mInfo.email.c_str(), this); + + mLabelWebsite = new QLabel(tr("<qt><b>Website:</qt></b>"), this); + mLabelWebsiteResult = new QLabel(mInfo.website.c_str(), this); + + mLabelDescription = new QLabel(tr("<qt><b>Description:</qt></b>"), this); + utf8_cstr = mInfo.description.data(); + uni_str = codec->toUnicode(utf8_cstr); + mLabelDescriptionResult = new QLabel(uni_str, this); + + mLabelDate = new QLabel(tr("<qt><b>Date:</qt></b>"), this); + mLabelDateResult = new QLabel(mInfo.date.c_str(), this); + + mLayout->addWidget(mLabelCount, 0, 0); + mLayout->addWidget(mLabelCountResult, 0, 1); + mLayout->addWidget(mLabelAuthor, 1, 0); + mLayout->addWidget(mLabelAuthorResult, 1, 1); + mLayout->addWidget(mLabelEmail, 2, 0); + mLayout->addWidget(mLabelEmailResult, 2, 1); + mLayout->addWidget(mLabelWebsite, 3, 0); + mLayout->addWidget(mLabelWebsiteResult, 3, 1); + mLayout->addWidget(mLabelDescription, 4, 0); + mLayout->addWidget(mLabelDescriptionResult, 4, 1); + mLayout->addWidget(mLabelDate, 5, 0); + mLayout->addWidget(mLabelDateResult, 5, 1); +} + +DictBrowser::DictBrowser(QWidget* parent, Qt::WindowFlags f, Libs* lib) : QWidget(parent, f), mLibs(lib) +{ + int i; + + mLayout = new QGridLayout(this); + + mListWidget = new QListWidget(this); + for (i = 0; i < mLibs->ndicts(); i++) { + const char* bkname = mLibs->dict_name(i).data(); + QTextCodec* codec = QTextCodec::codecForName("UTF-8"); + QString str = codec->toUnicode(bkname); + mListWidget->addItem(str); + } + mListWidget->setCurrentRow(0); + + connect(mListWidget, SIGNAL(itemActivated(QListWidgetItem*)), + this, SLOT(slotItemActivated(QListWidgetItem*))); + + mLayout->addWidget(mListWidget, 0, 0); +} + +void DictBrowser::slotItemActivated(QListWidgetItem* item) +{ + DictInfoWidget* info_widget; + + info_widget = new DictInfoWidget(this, Qt::Popup, + mLibs->dict_info(mListWidget->row(item))); + info_widget->setAttribute(Qt::WA_DeleteOnClose); + info_widget->showMaximized(); +} diff --git a/src/dictbrowser.h b/src/dictbrowser.h new file mode 100644 index 0000000..bfae6a7 --- /dev/null +++ b/src/dictbrowser.h @@ -0,0 +1,50 @@ +#ifndef DICT_BROWSER_H +#define DICT_BROWSER_H + +#include <QWidget> +#include <QListWidget> +#include <QGridLayout> +#include <QLabel> + +#include "lib/lib.h" + +class DictInfoWidget : public QWidget +{ +public: + DictInfoWidget(QWidget* parent, Qt::WindowFlags f, struct DictInfo info); + +private: + QGridLayout* mLayout; + struct DictInfo mInfo; + QLabel* mLabelCount; + QLabel* mLabelCountResult; + QLabel* mLabelAuthor; + QLabel* mLabelAuthorResult; + QLabel* mLabelEmail; + QLabel* mLabelEmailResult; + QLabel* mLabelWebsite; + QLabel* mLabelWebsiteResult; + QLabel* mLabelDescription; + QLabel* mLabelDescriptionResult; + QLabel* mLabelDate; + QLabel* mLabelDateResult; +}; + +class DictBrowser : public QWidget +{ + Q_OBJECT + +public: + DictBrowser(QWidget* parent = 0, Qt::WindowFlags f = 0, Libs* lib = 0); + +private slots: + void slotItemActivated(QListWidgetItem* item); + +private: + QGridLayout* mLayout; + QListWidget* mListWidget; + + Libs* mLibs; +}; + +#endif diff --git a/src/lib/.depsbak/dictziplib.Po b/src/lib/.depsbak/dictziplib.Po new file mode 100644 index 0000000..7c50afa --- /dev/null +++ b/src/lib/.depsbak/dictziplib.Po @@ -0,0 +1,487 @@ +dictziplib.o dictziplib.o: dictziplib.cpp ../../config.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cassert \ + /usr/include/assert.h /usr/include/features.h /usr/include/sys/cdefs.h \ + /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \ + /usr/include/gnu/stubs-32.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstdio \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++config.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/os_defines.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/cpu_defines.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstddef \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stddef.h \ + /usr/include/stdio.h /usr/include/bits/types.h \ + /usr/include/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \ + /usr/include/gconv.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stdarg.h \ + /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \ + /usr/include/bits/stdio.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstdlib \ + /usr/include/stdlib.h /usr/include/bits/waitflags.h \ + /usr/include/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/bits/endian.h /usr/include/xlocale.h \ + /usr/include/sys/types.h /usr/include/time.h /usr/include/sys/select.h \ + /usr/include/bits/select.h /usr/include/bits/sigset.h \ + /usr/include/bits/time.h /usr/include/sys/sysmacros.h \ + /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstring \ + /usr/include/string.h /usr/include/unistd.h \ + /usr/include/bits/posix_opt.h /usr/include/bits/environments.h \ + /usr/include/bits/confname.h /usr/include/getopt.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/limits.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/syslimits.h \ + /usr/include/limits.h /usr/include/bits/posix1_lim.h \ + /usr/include/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \ + /usr/include/fcntl.h /usr/include/bits/fcntl.h /usr/include/bits/uio.h \ + /usr/include/sys/stat.h /usr/include/bits/stat.h dictziplib.hpp \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/ctime \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/string \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stringfwd.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/char_traits.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_algobase.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/climits \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/iosfwd \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++locale.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/clocale \ + /usr/include/locale.h /usr/include/bits/locale.h \ + /usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \ + /usr/include/libintl.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++io.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/gthr.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/gthr-default.h \ + /usr/include/pthread.h /usr/include/sched.h /usr/include/bits/sched.h \ + /usr/include/signal.h /usr/include/bits/setjmp.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cctype \ + /usr/include/ctype.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/postypes.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cwchar \ + /usr/include/stdint.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/functexcept.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/exception_defines.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_pair.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/cpp_type_traits.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator_base_types.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator_base_funcs.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/concept_check.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/debug/debug.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/memory \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/allocator.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++allocator.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/ext/new_allocator.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/new \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/exception \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_construct.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_uninitialized.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_raw_storage_iter.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/limits \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_function.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/basic_string.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/atomicity.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/atomic_word.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/algorithm \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_algo.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_heap.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_tempbuf.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/basic_string.tcc \ + /usr/include/zlib.h /usr/include/zconf.h mapfile.hpp \ + /usr/include/sys/mman.h /usr/include/bits/mman.h \ + /usr/include/glib-2.0/glib.h /usr/include/glib-2.0/glib/galloca.h \ + /usr/include/glib-2.0/glib/gtypes.h \ + /usr/lib/glib-2.0/include/glibconfig.h \ + /usr/include/glib-2.0/glib/gmacros.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/float.h \ + /usr/include/glib-2.0/glib/garray.h \ + /usr/include/glib-2.0/glib/gasyncqueue.h \ + /usr/include/glib-2.0/glib/gthread.h \ + /usr/include/glib-2.0/glib/gerror.h /usr/include/glib-2.0/glib/gquark.h \ + /usr/include/glib-2.0/glib/gutils.h \ + /usr/include/glib-2.0/glib/gatomic.h \ + /usr/include/glib-2.0/glib/gbacktrace.h \ + /usr/include/glib-2.0/glib/gbase64.h \ + /usr/include/glib-2.0/glib/gbookmarkfile.h \ + /usr/include/glib-2.0/glib/gcache.h /usr/include/glib-2.0/glib/glist.h \ + /usr/include/glib-2.0/glib/gmem.h /usr/include/glib-2.0/glib/gslice.h \ + /usr/include/glib-2.0/glib/gcompletion.h \ + /usr/include/glib-2.0/glib/gconvert.h \ + /usr/include/glib-2.0/glib/gdataset.h \ + /usr/include/glib-2.0/glib/gdate.h /usr/include/glib-2.0/glib/gdir.h \ + /usr/include/glib-2.0/glib/gfileutils.h \ + /usr/include/glib-2.0/glib/ghash.h /usr/include/glib-2.0/glib/ghook.h \ + /usr/include/glib-2.0/glib/giochannel.h \ + /usr/include/glib-2.0/glib/gmain.h /usr/include/glib-2.0/glib/gslist.h \ + /usr/include/glib-2.0/glib/gstring.h \ + /usr/include/glib-2.0/glib/gunicode.h \ + /usr/include/glib-2.0/glib/gkeyfile.h \ + /usr/include/glib-2.0/glib/gmappedfile.h \ + /usr/include/glib-2.0/glib/gmarkup.h \ + /usr/include/glib-2.0/glib/gmessages.h \ + /usr/include/glib-2.0/glib/gnode.h /usr/include/glib-2.0/glib/goption.h \ + /usr/include/glib-2.0/glib/gpattern.h \ + /usr/include/glib-2.0/glib/gprimes.h \ + /usr/include/glib-2.0/glib/gqsort.h /usr/include/glib-2.0/glib/gqueue.h \ + /usr/include/glib-2.0/glib/grand.h /usr/include/glib-2.0/glib/grel.h \ + /usr/include/glib-2.0/glib/gregex.h \ + /usr/include/glib-2.0/glib/gscanner.h \ + /usr/include/glib-2.0/glib/gsequence.h \ + /usr/include/glib-2.0/glib/gshell.h /usr/include/glib-2.0/glib/gspawn.h \ + /usr/include/glib-2.0/glib/gstrfuncs.h \ + /usr/include/glib-2.0/glib/gthreadpool.h \ + /usr/include/glib-2.0/glib/gtimer.h /usr/include/glib-2.0/glib/gtree.h + +../../config.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cassert: + +/usr/include/assert.h: + +/usr/include/features.h: + +/usr/include/sys/cdefs.h: + +/usr/include/bits/wordsize.h: + +/usr/include/gnu/stubs.h: + +/usr/include/gnu/stubs-32.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstdio: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++config.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/os_defines.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/cpu_defines.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstddef: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stddef.h: + +/usr/include/stdio.h: + +/usr/include/bits/types.h: + +/usr/include/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/include/bits/wchar.h: + +/usr/include/gconv.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stdarg.h: + +/usr/include/bits/stdio_lim.h: + +/usr/include/bits/sys_errlist.h: + +/usr/include/bits/stdio.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstdlib: + +/usr/include/stdlib.h: + +/usr/include/bits/waitflags.h: + +/usr/include/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/bits/endian.h: + +/usr/include/xlocale.h: + +/usr/include/sys/types.h: + +/usr/include/time.h: + +/usr/include/sys/select.h: + +/usr/include/bits/select.h: + +/usr/include/bits/sigset.h: + +/usr/include/bits/time.h: + +/usr/include/sys/sysmacros.h: + +/usr/include/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstring: + +/usr/include/string.h: + +/usr/include/unistd.h: + +/usr/include/bits/posix_opt.h: + +/usr/include/bits/environments.h: + +/usr/include/bits/confname.h: + +/usr/include/getopt.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/limits.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/syslimits.h: + +/usr/include/limits.h: + +/usr/include/bits/posix1_lim.h: + +/usr/include/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/bits/posix2_lim.h: + +/usr/include/bits/xopen_lim.h: + +/usr/include/fcntl.h: + +/usr/include/bits/fcntl.h: + +/usr/include/bits/uio.h: + +/usr/include/sys/stat.h: + +/usr/include/bits/stat.h: + +dictziplib.hpp: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/ctime: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/string: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stringfwd.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/char_traits.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_algobase.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/climits: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/iosfwd: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++locale.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/clocale: + +/usr/include/locale.h: + +/usr/include/bits/locale.h: + +/usr/include/langinfo.h: + +/usr/include/nl_types.h: + +/usr/include/iconv.h: + +/usr/include/libintl.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++io.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/gthr.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/gthr-default.h: + +/usr/include/pthread.h: + +/usr/include/sched.h: + +/usr/include/bits/sched.h: + +/usr/include/signal.h: + +/usr/include/bits/setjmp.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cctype: + +/usr/include/ctype.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/postypes.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cwchar: + +/usr/include/stdint.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/functexcept.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/exception_defines.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_pair.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/cpp_type_traits.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator_base_types.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator_base_funcs.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/concept_check.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/debug/debug.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/memory: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/allocator.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++allocator.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/ext/new_allocator.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/new: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/exception: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_construct.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_uninitialized.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_raw_storage_iter.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/limits: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_function.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/basic_string.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/atomicity.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/atomic_word.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/algorithm: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_algo.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_heap.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_tempbuf.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/basic_string.tcc: + +/usr/include/zlib.h: + +/usr/include/zconf.h: + +mapfile.hpp: + +/usr/include/sys/mman.h: + +/usr/include/bits/mman.h: + +/usr/include/glib-2.0/glib.h: + +/usr/include/glib-2.0/glib/galloca.h: + +/usr/include/glib-2.0/glib/gtypes.h: + +/usr/lib/glib-2.0/include/glibconfig.h: + +/usr/include/glib-2.0/glib/gmacros.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/float.h: + +/usr/include/glib-2.0/glib/garray.h: + +/usr/include/glib-2.0/glib/gasyncqueue.h: + +/usr/include/glib-2.0/glib/gthread.h: + +/usr/include/glib-2.0/glib/gerror.h: + +/usr/include/glib-2.0/glib/gquark.h: + +/usr/include/glib-2.0/glib/gutils.h: + +/usr/include/glib-2.0/glib/gatomic.h: + +/usr/include/glib-2.0/glib/gbacktrace.h: + +/usr/include/glib-2.0/glib/gbase64.h: + +/usr/include/glib-2.0/glib/gbookmarkfile.h: + +/usr/include/glib-2.0/glib/gcache.h: + +/usr/include/glib-2.0/glib/glist.h: + +/usr/include/glib-2.0/glib/gmem.h: + +/usr/include/glib-2.0/glib/gslice.h: + +/usr/include/glib-2.0/glib/gcompletion.h: + +/usr/include/glib-2.0/glib/gconvert.h: + +/usr/include/glib-2.0/glib/gdataset.h: + +/usr/include/glib-2.0/glib/gdate.h: + +/usr/include/glib-2.0/glib/gdir.h: + +/usr/include/glib-2.0/glib/gfileutils.h: + +/usr/include/glib-2.0/glib/ghash.h: + +/usr/include/glib-2.0/glib/ghook.h: + +/usr/include/glib-2.0/glib/giochannel.h: + +/usr/include/glib-2.0/glib/gmain.h: + +/usr/include/glib-2.0/glib/gslist.h: + +/usr/include/glib-2.0/glib/gstring.h: + +/usr/include/glib-2.0/glib/gunicode.h: + +/usr/include/glib-2.0/glib/gkeyfile.h: + +/usr/include/glib-2.0/glib/gmappedfile.h: + +/usr/include/glib-2.0/glib/gmarkup.h: + +/usr/include/glib-2.0/glib/gmessages.h: + +/usr/include/glib-2.0/glib/gnode.h: + +/usr/include/glib-2.0/glib/goption.h: + +/usr/include/glib-2.0/glib/gpattern.h: + +/usr/include/glib-2.0/glib/gprimes.h: + +/usr/include/glib-2.0/glib/gqsort.h: + +/usr/include/glib-2.0/glib/gqueue.h: + +/usr/include/glib-2.0/glib/grand.h: + +/usr/include/glib-2.0/glib/grel.h: + +/usr/include/glib-2.0/glib/gregex.h: + +/usr/include/glib-2.0/glib/gscanner.h: + +/usr/include/glib-2.0/glib/gsequence.h: + +/usr/include/glib-2.0/glib/gshell.h: + +/usr/include/glib-2.0/glib/gspawn.h: + +/usr/include/glib-2.0/glib/gstrfuncs.h: + +/usr/include/glib-2.0/glib/gthreadpool.h: + +/usr/include/glib-2.0/glib/gtimer.h: + +/usr/include/glib-2.0/glib/gtree.h: diff --git a/src/lib/.depsbak/distance.Po b/src/lib/.depsbak/distance.Po new file mode 100644 index 0000000..611b6db --- /dev/null +++ b/src/lib/.depsbak/distance.Po @@ -0,0 +1,240 @@ +distance.o distance.o: distance.cpp /usr/include/stdlib.h \ + /usr/include/features.h /usr/include/sys/cdefs.h \ + /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \ + /usr/include/gnu/stubs-32.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stddef.h \ + /usr/include/bits/waitflags.h /usr/include/bits/waitstatus.h \ + /usr/include/endian.h /usr/include/bits/endian.h /usr/include/xlocale.h \ + /usr/include/sys/types.h /usr/include/bits/types.h \ + /usr/include/bits/typesizes.h /usr/include/time.h \ + /usr/include/sys/select.h /usr/include/bits/select.h \ + /usr/include/bits/sigset.h /usr/include/bits/time.h \ + /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \ + /usr/include/alloca.h /usr/include/string.h distance.h \ + /usr/include/glib-2.0/glib.h /usr/include/glib-2.0/glib/galloca.h \ + /usr/include/glib-2.0/glib/gtypes.h \ + /usr/lib/glib-2.0/include/glibconfig.h \ + /usr/include/glib-2.0/glib/gmacros.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/limits.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/syslimits.h \ + /usr/include/limits.h /usr/include/bits/posix1_lim.h \ + /usr/include/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \ + /usr/include/bits/stdio_lim.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/float.h \ + /usr/include/glib-2.0/glib/garray.h \ + /usr/include/glib-2.0/glib/gasyncqueue.h \ + /usr/include/glib-2.0/glib/gthread.h \ + /usr/include/glib-2.0/glib/gerror.h /usr/include/glib-2.0/glib/gquark.h \ + /usr/include/glib-2.0/glib/gutils.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stdarg.h \ + /usr/include/glib-2.0/glib/gatomic.h \ + /usr/include/glib-2.0/glib/gbacktrace.h \ + /usr/include/glib-2.0/glib/gbase64.h \ + /usr/include/glib-2.0/glib/gbookmarkfile.h \ + /usr/include/glib-2.0/glib/gcache.h /usr/include/glib-2.0/glib/glist.h \ + /usr/include/glib-2.0/glib/gmem.h /usr/include/glib-2.0/glib/gslice.h \ + /usr/include/glib-2.0/glib/gcompletion.h \ + /usr/include/glib-2.0/glib/gconvert.h \ + /usr/include/glib-2.0/glib/gdataset.h \ + /usr/include/glib-2.0/glib/gdate.h /usr/include/glib-2.0/glib/gdir.h \ + /usr/include/glib-2.0/glib/gfileutils.h \ + /usr/include/glib-2.0/glib/ghash.h /usr/include/glib-2.0/glib/ghook.h \ + /usr/include/glib-2.0/glib/giochannel.h \ + /usr/include/glib-2.0/glib/gmain.h /usr/include/glib-2.0/glib/gslist.h \ + /usr/include/glib-2.0/glib/gstring.h \ + /usr/include/glib-2.0/glib/gunicode.h \ + /usr/include/glib-2.0/glib/gkeyfile.h \ + /usr/include/glib-2.0/glib/gmappedfile.h \ + /usr/include/glib-2.0/glib/gmarkup.h \ + /usr/include/glib-2.0/glib/gmessages.h \ + /usr/include/glib-2.0/glib/gnode.h /usr/include/glib-2.0/glib/goption.h \ + /usr/include/glib-2.0/glib/gpattern.h \ + /usr/include/glib-2.0/glib/gprimes.h \ + /usr/include/glib-2.0/glib/gqsort.h /usr/include/glib-2.0/glib/gqueue.h \ + /usr/include/glib-2.0/glib/grand.h /usr/include/glib-2.0/glib/grel.h \ + /usr/include/glib-2.0/glib/gregex.h \ + /usr/include/glib-2.0/glib/gscanner.h \ + /usr/include/glib-2.0/glib/gsequence.h \ + /usr/include/glib-2.0/glib/gshell.h /usr/include/glib-2.0/glib/gspawn.h \ + /usr/include/glib-2.0/glib/gstrfuncs.h \ + /usr/include/glib-2.0/glib/gthreadpool.h \ + /usr/include/glib-2.0/glib/gtimer.h /usr/include/glib-2.0/glib/gtree.h + +/usr/include/stdlib.h: + +/usr/include/features.h: + +/usr/include/sys/cdefs.h: + +/usr/include/bits/wordsize.h: + +/usr/include/gnu/stubs.h: + +/usr/include/gnu/stubs-32.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stddef.h: + +/usr/include/bits/waitflags.h: + +/usr/include/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/bits/endian.h: + +/usr/include/xlocale.h: + +/usr/include/sys/types.h: + +/usr/include/bits/types.h: + +/usr/include/bits/typesizes.h: + +/usr/include/time.h: + +/usr/include/sys/select.h: + +/usr/include/bits/select.h: + +/usr/include/bits/sigset.h: + +/usr/include/bits/time.h: + +/usr/include/sys/sysmacros.h: + +/usr/include/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/string.h: + +distance.h: + +/usr/include/glib-2.0/glib.h: + +/usr/include/glib-2.0/glib/galloca.h: + +/usr/include/glib-2.0/glib/gtypes.h: + +/usr/lib/glib-2.0/include/glibconfig.h: + +/usr/include/glib-2.0/glib/gmacros.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/limits.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/syslimits.h: + +/usr/include/limits.h: + +/usr/include/bits/posix1_lim.h: + +/usr/include/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/bits/posix2_lim.h: + +/usr/include/bits/xopen_lim.h: + +/usr/include/bits/stdio_lim.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/float.h: + +/usr/include/glib-2.0/glib/garray.h: + +/usr/include/glib-2.0/glib/gasyncqueue.h: + +/usr/include/glib-2.0/glib/gthread.h: + +/usr/include/glib-2.0/glib/gerror.h: + +/usr/include/glib-2.0/glib/gquark.h: + +/usr/include/glib-2.0/glib/gutils.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stdarg.h: + +/usr/include/glib-2.0/glib/gatomic.h: + +/usr/include/glib-2.0/glib/gbacktrace.h: + +/usr/include/glib-2.0/glib/gbase64.h: + +/usr/include/glib-2.0/glib/gbookmarkfile.h: + +/usr/include/glib-2.0/glib/gcache.h: + +/usr/include/glib-2.0/glib/glist.h: + +/usr/include/glib-2.0/glib/gmem.h: + +/usr/include/glib-2.0/glib/gslice.h: + +/usr/include/glib-2.0/glib/gcompletion.h: + +/usr/include/glib-2.0/glib/gconvert.h: + +/usr/include/glib-2.0/glib/gdataset.h: + +/usr/include/glib-2.0/glib/gdate.h: + +/usr/include/glib-2.0/glib/gdir.h: + +/usr/include/glib-2.0/glib/gfileutils.h: + +/usr/include/glib-2.0/glib/ghash.h: + +/usr/include/glib-2.0/glib/ghook.h: + +/usr/include/glib-2.0/glib/giochannel.h: + +/usr/include/glib-2.0/glib/gmain.h: + +/usr/include/glib-2.0/glib/gslist.h: + +/usr/include/glib-2.0/glib/gstring.h: + +/usr/include/glib-2.0/glib/gunicode.h: + +/usr/include/glib-2.0/glib/gkeyfile.h: + +/usr/include/glib-2.0/glib/gmappedfile.h: + +/usr/include/glib-2.0/glib/gmarkup.h: + +/usr/include/glib-2.0/glib/gmessages.h: + +/usr/include/glib-2.0/glib/gnode.h: + +/usr/include/glib-2.0/glib/goption.h: + +/usr/include/glib-2.0/glib/gpattern.h: + +/usr/include/glib-2.0/glib/gprimes.h: + +/usr/include/glib-2.0/glib/gqsort.h: + +/usr/include/glib-2.0/glib/gqueue.h: + +/usr/include/glib-2.0/glib/grand.h: + +/usr/include/glib-2.0/glib/grel.h: + +/usr/include/glib-2.0/glib/gregex.h: + +/usr/include/glib-2.0/glib/gscanner.h: + +/usr/include/glib-2.0/glib/gsequence.h: + +/usr/include/glib-2.0/glib/gshell.h: + +/usr/include/glib-2.0/glib/gspawn.h: + +/usr/include/glib-2.0/glib/gstrfuncs.h: + +/usr/include/glib-2.0/glib/gthreadpool.h: + +/usr/include/glib-2.0/glib/gtimer.h: + +/usr/include/glib-2.0/glib/gtree.h: diff --git a/src/lib/.depsbak/lib.Po b/src/lib/.depsbak/lib.Po new file mode 100644 index 0000000..c0f89a3 --- /dev/null +++ b/src/lib/.depsbak/lib.Po @@ -0,0 +1,515 @@ +lib.o lib.o: lib.cpp ../../config.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/algorithm \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_algobase.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++config.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/os_defines.h \ + /usr/include/features.h /usr/include/sys/cdefs.h \ + /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \ + /usr/include/gnu/stubs-32.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/cpu_defines.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstring \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstddef \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stddef.h \ + /usr/include/string.h /usr/include/xlocale.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/climits \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/limits.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/syslimits.h \ + /usr/include/limits.h /usr/include/bits/posix1_lim.h \ + /usr/include/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \ + /usr/include/bits/stdio_lim.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstdlib \ + /usr/include/stdlib.h /usr/include/bits/waitflags.h \ + /usr/include/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/bits/endian.h /usr/include/sys/types.h \ + /usr/include/bits/types.h /usr/include/bits/typesizes.h \ + /usr/include/time.h /usr/include/sys/select.h \ + /usr/include/bits/select.h /usr/include/bits/sigset.h \ + /usr/include/bits/time.h /usr/include/sys/sysmacros.h \ + /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/iosfwd \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++locale.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstdio \ + /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \ + /usr/include/wchar.h /usr/include/bits/wchar.h /usr/include/gconv.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stdarg.h \ + /usr/include/bits/sys_errlist.h /usr/include/bits/stdio.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/clocale \ + /usr/include/locale.h /usr/include/bits/locale.h \ + /usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \ + /usr/include/libintl.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++io.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/gthr.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/gthr-default.h \ + /usr/include/pthread.h /usr/include/sched.h /usr/include/bits/sched.h \ + /usr/include/signal.h /usr/include/bits/setjmp.h /usr/include/unistd.h \ + /usr/include/bits/posix_opt.h /usr/include/bits/environments.h \ + /usr/include/bits/confname.h /usr/include/getopt.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cctype \ + /usr/include/ctype.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stringfwd.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/postypes.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cwchar \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/ctime \ + /usr/include/stdint.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/functexcept.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/exception_defines.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_pair.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/cpp_type_traits.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator_base_types.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator_base_funcs.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/concept_check.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/debug/debug.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_construct.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/new \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/exception \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_uninitialized.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_algo.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_heap.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_tempbuf.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/memory \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/allocator.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++allocator.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/ext/new_allocator.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_raw_storage_iter.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/limits \ + /usr/include/sys/stat.h /usr/include/bits/stat.h /usr/include/zlib.h \ + /usr/include/zconf.h /usr/include/glib-2.0/glib/gstdio.h \ + /usr/include/glib-2.0/glib/gprintf.h \ + /usr/include/glib-2.0/glib/gtypes.h \ + /usr/lib/glib-2.0/include/glibconfig.h \ + /usr/include/glib-2.0/glib/gmacros.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/float.h distance.h \ + /usr/include/glib-2.0/glib.h /usr/include/glib-2.0/glib/galloca.h \ + /usr/include/glib-2.0/glib/garray.h \ + /usr/include/glib-2.0/glib/gasyncqueue.h \ + /usr/include/glib-2.0/glib/gthread.h \ + /usr/include/glib-2.0/glib/gerror.h /usr/include/glib-2.0/glib/gquark.h \ + /usr/include/glib-2.0/glib/gutils.h \ + /usr/include/glib-2.0/glib/gatomic.h \ + /usr/include/glib-2.0/glib/gbacktrace.h \ + /usr/include/glib-2.0/glib/gbase64.h \ + /usr/include/glib-2.0/glib/gbookmarkfile.h \ + /usr/include/glib-2.0/glib/gcache.h /usr/include/glib-2.0/glib/glist.h \ + /usr/include/glib-2.0/glib/gmem.h /usr/include/glib-2.0/glib/gslice.h \ + /usr/include/glib-2.0/glib/gcompletion.h \ + /usr/include/glib-2.0/glib/gconvert.h \ + /usr/include/glib-2.0/glib/gdataset.h \ + /usr/include/glib-2.0/glib/gdate.h /usr/include/glib-2.0/glib/gdir.h \ + /usr/include/glib-2.0/glib/gfileutils.h \ + /usr/include/glib-2.0/glib/ghash.h /usr/include/glib-2.0/glib/ghook.h \ + /usr/include/glib-2.0/glib/giochannel.h \ + /usr/include/glib-2.0/glib/gmain.h /usr/include/glib-2.0/glib/gslist.h \ + /usr/include/glib-2.0/glib/gstring.h \ + /usr/include/glib-2.0/glib/gunicode.h \ + /usr/include/glib-2.0/glib/gkeyfile.h \ + /usr/include/glib-2.0/glib/gmappedfile.h \ + /usr/include/glib-2.0/glib/gmarkup.h \ + /usr/include/glib-2.0/glib/gmessages.h \ + /usr/include/glib-2.0/glib/gnode.h /usr/include/glib-2.0/glib/goption.h \ + /usr/include/glib-2.0/glib/gpattern.h \ + /usr/include/glib-2.0/glib/gprimes.h \ + /usr/include/glib-2.0/glib/gqsort.h /usr/include/glib-2.0/glib/gqueue.h \ + /usr/include/glib-2.0/glib/grand.h /usr/include/glib-2.0/glib/grel.h \ + /usr/include/glib-2.0/glib/gregex.h \ + /usr/include/glib-2.0/glib/gscanner.h \ + /usr/include/glib-2.0/glib/gsequence.h \ + /usr/include/glib-2.0/glib/gshell.h /usr/include/glib-2.0/glib/gspawn.h \ + /usr/include/glib-2.0/glib/gstrfuncs.h \ + /usr/include/glib-2.0/glib/gthreadpool.h \ + /usr/include/glib-2.0/glib/gtimer.h /usr/include/glib-2.0/glib/gtree.h \ + file.hpp /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/list \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_list.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/list.tcc \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/string \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/char_traits.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_function.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/basic_string.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/atomicity.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/atomic_word.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/basic_string.tcc \ + mapfile.hpp /usr/include/fcntl.h /usr/include/bits/fcntl.h \ + /usr/include/bits/uio.h /usr/include/sys/mman.h \ + /usr/include/bits/mman.h lib.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/vector \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_vector.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_bvector.h \ + /usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/vector.tcc \ + dictziplib.hpp + +../../config.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/algorithm: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_algobase.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++config.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/os_defines.h: + +/usr/include/features.h: + +/usr/include/sys/cdefs.h: + +/usr/include/bits/wordsize.h: + +/usr/include/gnu/stubs.h: + +/usr/include/gnu/stubs-32.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/cpu_defines.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstring: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstddef: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stddef.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/climits: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/limits.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/syslimits.h: + +/usr/include/limits.h: + +/usr/include/bits/posix1_lim.h: + +/usr/include/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/bits/posix2_lim.h: + +/usr/include/bits/xopen_lim.h: + +/usr/include/bits/stdio_lim.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstdlib: + +/usr/include/stdlib.h: + +/usr/include/bits/waitflags.h: + +/usr/include/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/bits/endian.h: + +/usr/include/sys/types.h: + +/usr/include/bits/types.h: + +/usr/include/bits/typesizes.h: + +/usr/include/time.h: + +/usr/include/sys/select.h: + +/usr/include/bits/select.h: + +/usr/include/bits/sigset.h: + +/usr/include/bits/time.h: + +/usr/include/sys/sysmacros.h: + +/usr/include/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/iosfwd: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++locale.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cstdio: + +/usr/include/stdio.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/include/bits/wchar.h: + +/usr/include/gconv.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/stdarg.h: + +/usr/include/bits/sys_errlist.h: + +/usr/include/bits/stdio.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/clocale: + +/usr/include/locale.h: + +/usr/include/bits/locale.h: + +/usr/include/langinfo.h: + +/usr/include/nl_types.h: + +/usr/include/iconv.h: + +/usr/include/libintl.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++io.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/gthr.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/gthr-default.h: + +/usr/include/pthread.h: + +/usr/include/sched.h: + +/usr/include/bits/sched.h: + +/usr/include/signal.h: + +/usr/include/bits/setjmp.h: + +/usr/include/unistd.h: + +/usr/include/bits/posix_opt.h: + +/usr/include/bits/environments.h: + +/usr/include/bits/confname.h: + +/usr/include/getopt.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cctype: + +/usr/include/ctype.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stringfwd.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/postypes.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/cwchar: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/ctime: + +/usr/include/stdint.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/functexcept.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/exception_defines.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_pair.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/cpp_type_traits.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator_base_types.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator_base_funcs.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/concept_check.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_iterator.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/debug/debug.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_construct.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/new: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/exception: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_uninitialized.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_algo.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_heap.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_tempbuf.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/memory: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/allocator.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/c++allocator.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/ext/new_allocator.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_raw_storage_iter.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/limits: + +/usr/include/sys/stat.h: + +/usr/include/bits/stat.h: + +/usr/include/zlib.h: + +/usr/include/zconf.h: + +/usr/include/glib-2.0/glib/gstdio.h: + +/usr/include/glib-2.0/glib/gprintf.h: + +/usr/include/glib-2.0/glib/gtypes.h: + +/usr/lib/glib-2.0/include/glibconfig.h: + +/usr/include/glib-2.0/glib/gmacros.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/float.h: + +distance.h: + +/usr/include/glib-2.0/glib.h: + +/usr/include/glib-2.0/glib/galloca.h: + +/usr/include/glib-2.0/glib/garray.h: + +/usr/include/glib-2.0/glib/gasyncqueue.h: + +/usr/include/glib-2.0/glib/gthread.h: + +/usr/include/glib-2.0/glib/gerror.h: + +/usr/include/glib-2.0/glib/gquark.h: + +/usr/include/glib-2.0/glib/gutils.h: + +/usr/include/glib-2.0/glib/gatomic.h: + +/usr/include/glib-2.0/glib/gbacktrace.h: + +/usr/include/glib-2.0/glib/gbase64.h: + +/usr/include/glib-2.0/glib/gbookmarkfile.h: + +/usr/include/glib-2.0/glib/gcache.h: + +/usr/include/glib-2.0/glib/glist.h: + +/usr/include/glib-2.0/glib/gmem.h: + +/usr/include/glib-2.0/glib/gslice.h: + +/usr/include/glib-2.0/glib/gcompletion.h: + +/usr/include/glib-2.0/glib/gconvert.h: + +/usr/include/glib-2.0/glib/gdataset.h: + +/usr/include/glib-2.0/glib/gdate.h: + +/usr/include/glib-2.0/glib/gdir.h: + +/usr/include/glib-2.0/glib/gfileutils.h: + +/usr/include/glib-2.0/glib/ghash.h: + +/usr/include/glib-2.0/glib/ghook.h: + +/usr/include/glib-2.0/glib/giochannel.h: + +/usr/include/glib-2.0/glib/gmain.h: + +/usr/include/glib-2.0/glib/gslist.h: + +/usr/include/glib-2.0/glib/gstring.h: + +/usr/include/glib-2.0/glib/gunicode.h: + +/usr/include/glib-2.0/glib/gkeyfile.h: + +/usr/include/glib-2.0/glib/gmappedfile.h: + +/usr/include/glib-2.0/glib/gmarkup.h: + +/usr/include/glib-2.0/glib/gmessages.h: + +/usr/include/glib-2.0/glib/gnode.h: + +/usr/include/glib-2.0/glib/goption.h: + +/usr/include/glib-2.0/glib/gpattern.h: + +/usr/include/glib-2.0/glib/gprimes.h: + +/usr/include/glib-2.0/glib/gqsort.h: + +/usr/include/glib-2.0/glib/gqueue.h: + +/usr/include/glib-2.0/glib/grand.h: + +/usr/include/glib-2.0/glib/grel.h: + +/usr/include/glib-2.0/glib/gregex.h: + +/usr/include/glib-2.0/glib/gscanner.h: + +/usr/include/glib-2.0/glib/gsequence.h: + +/usr/include/glib-2.0/glib/gshell.h: + +/usr/include/glib-2.0/glib/gspawn.h: + +/usr/include/glib-2.0/glib/gstrfuncs.h: + +/usr/include/glib-2.0/glib/gthreadpool.h: + +/usr/include/glib-2.0/glib/gtimer.h: + +/usr/include/glib-2.0/glib/gtree.h: + +file.hpp: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/list: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_list.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/list.tcc: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/string: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/char_traits.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_function.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/basic_string.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/atomicity.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/i686-pc-linux-gnu/bits/atomic_word.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/basic_string.tcc: + +mapfile.hpp: + +/usr/include/fcntl.h: + +/usr/include/bits/fcntl.h: + +/usr/include/bits/uio.h: + +/usr/include/sys/mman.h: + +/usr/include/bits/mman.h: + +lib.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/vector: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_vector.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/stl_bvector.h: + +/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/bits/vector.tcc: + +dictziplib.hpp: diff --git a/src/lib/dictziplib.cpp b/src/lib/dictziplib.cpp new file mode 100644 index 0000000..2a45d61 --- /dev/null +++ b/src/lib/dictziplib.cpp @@ -0,0 +1,484 @@ +/* dictziplib.c -- + * http://stardict.sourceforge.net + * Copyright (C) 2003-2003 Hu Zheng <[email protected]> + * This file is a modify version of dictd-1.9.7's data.c + * + * data.c -- + * Created: Tue Jul 16 12:45:41 1996 by [email protected] + * Revised: Sat Mar 30 10:46:06 2002 by [email protected] + * Copyright 1996, 1997, 1998, 2000, 2002 Rickard E. Faith ([email protected]) + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Library General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +//#define HAVE_MMAP //it will defined in config.h. this can be done by configure.in with a AC_FUNC_MMAP. +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include <cassert> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <unistd.h> +#include <limits.h> +#include <fcntl.h> + +#include <sys/stat.h> + + +#include "dictziplib.hpp" + +#define USE_CACHE 1 + +#define BUFFERSIZE 10240 + +/* + * Output buffer must be greater than or + * equal to 110% of input buffer size, plus + * 12 bytes. +*/ +#define OUT_BUFFER_SIZE 0xffffL + +#define IN_BUFFER_SIZE ((unsigned long)((double)(OUT_BUFFER_SIZE - 12) * 0.89)) + +/* For gzip-compatible header, as defined in RFC 1952 */ + + /* Magic for GZIP (rfc1952) */ +#define GZ_MAGIC1 0x1f /* First magic byte */ +#define GZ_MAGIC2 0x8b /* Second magic byte */ + + /* FLaGs (bitmapped), from rfc1952 */ +#define GZ_FTEXT 0x01 /* Set for ASCII text */ +#define GZ_FHCRC 0x02 /* Header CRC16 */ +#define GZ_FEXTRA 0x04 /* Optional field (random access index) */ +#define GZ_FNAME 0x08 /* Original name */ +#define GZ_COMMENT 0x10 /* Zero-terminated, human-readable comment */ +#define GZ_MAX 2 /* Maximum compression */ +#define GZ_FAST 4 /* Fasted compression */ + + /* These are from rfc1952 */ +#define GZ_OS_FAT 0 /* FAT filesystem (MS-DOS, OS/2, NT/Win32) */ +#define GZ_OS_AMIGA 1 /* Amiga */ +#define GZ_OS_VMS 2 /* VMS (or OpenVMS) */ +#define GZ_OS_UNIX 3 /* Unix */ +#define GZ_OS_VMCMS 4 /* VM/CMS */ +#define GZ_OS_ATARI 5 /* Atari TOS */ +#define GZ_OS_HPFS 6 /* HPFS filesystem (OS/2, NT) */ +#define GZ_OS_MAC 7 /* Macintosh */ +#define GZ_OS_Z 8 /* Z-System */ +#define GZ_OS_CPM 9 /* CP/M */ +#define GZ_OS_TOPS20 10 /* TOPS-20 */ +#define GZ_OS_NTFS 11 /* NTFS filesystem (NT) */ +#define GZ_OS_QDOS 12 /* QDOS */ +#define GZ_OS_ACORN 13 /* Acorn RISCOS */ +#define GZ_OS_UNKNOWN 255 /* unknown */ + +#define GZ_RND_S1 'R' /* First magic for random access format */ +#define GZ_RND_S2 'A' /* Second magic for random access format */ + +#define GZ_ID1 0 /* GZ_MAGIC1 */ +#define GZ_ID2 1 /* GZ_MAGIC2 */ +#define GZ_CM 2 /* Compression Method (Z_DEFALTED) */ +#define GZ_FLG 3 /* FLaGs (see above) */ +#define GZ_MTIME 4 /* Modification TIME */ +#define GZ_XFL 8 /* eXtra FLags (GZ_MAX or GZ_FAST) */ +#define GZ_OS 9 /* Operating System */ +#define GZ_XLEN 10 /* eXtra LENgth (16bit) */ +#define GZ_FEXTRA_START 12 /* Start of extra fields */ +#define GZ_SI1 12 /* Subfield ID1 */ +#define GZ_SI2 13 /* Subfield ID2 */ +#define GZ_SUBLEN 14 /* Subfield length (16bit) */ +#define GZ_VERSION 16 /* Version for subfield format */ +#define GZ_CHUNKLEN 18 /* Chunk length (16bit) */ +#define GZ_CHUNKCNT 20 /* Number of chunks (16bit) */ +#define GZ_RNDDATA 22 /* Random access data (16bit) */ + +#define DICT_UNKNOWN 0 +#define DICT_TEXT 1 +#define DICT_GZIP 2 +#define DICT_DZIP 3 + + +int dictData::read_header(const std::string &fname, int computeCRC) +{ + FILE *str; + int id1, id2, si1, si2; + char buffer[BUFFERSIZE]; + int extraLength, subLength; + int i; + char *pt; + int c; + struct stat sb; + unsigned long crc = crc32( 0L, Z_NULL, 0 ); + int count; + unsigned long offset; + + if (!(str = fopen(fname.c_str(), "rb"))) { + //err_fatal_errno( __FUNCTION__, + // "Cannot open data file \"%s\" for read\n", filename ); + } + + this->headerLength = GZ_XLEN - 1; + this->type = DICT_UNKNOWN; + + id1 = getc( str ); + id2 = getc( str ); + + if (id1 != GZ_MAGIC1 || id2 != GZ_MAGIC2) { + this->type = DICT_TEXT; + fstat( fileno( str ), &sb ); + this->compressedLength = this->length = sb.st_size; + this->origFilename = fname; + this->mtime = sb.st_mtime; + if (computeCRC) { + rewind( str ); + while (!feof( str )) { + if ((count = fread( buffer, 1, BUFFERSIZE, str ))) { + crc = crc32(crc, (Bytef *)buffer, count); + } + } + } + this->crc = crc; + fclose( str ); + return 0; + } + this->type = DICT_GZIP; + + this->method = getc( str ); + this->flags = getc( str ); + this->mtime = getc( str ) << 0; + this->mtime |= getc( str ) << 8; + this->mtime |= getc( str ) << 16; + this->mtime |= getc( str ) << 24; + this->extraFlags = getc( str ); + this->os = getc( str ); + + if (this->flags & GZ_FEXTRA) { + extraLength = getc( str ) << 0; + extraLength |= getc( str ) << 8; + this->headerLength += extraLength + 2; + si1 = getc( str ); + si2 = getc( str ); + + if (si1 == GZ_RND_S1 || si2 == GZ_RND_S2) { + subLength = getc( str ) << 0; + subLength |= getc( str ) << 8; + this->version = getc( str ) << 0; + this->version |= getc( str ) << 8; + + if (this->version != 1) { + //err_internal( __FUNCTION__, + // "dzip header version %d not supported\n", + // this->version ); + } + + this->chunkLength = getc( str ) << 0; + this->chunkLength |= getc( str ) << 8; + this->chunkCount = getc( str ) << 0; + this->chunkCount |= getc( str ) << 8; + + if (this->chunkCount <= 0) { + fclose( str ); + return 5; + } + this->chunks = (int *)malloc(sizeof( this->chunks[0] ) + * this->chunkCount ); + for (i = 0; i < this->chunkCount; i++) { + this->chunks[i] = getc( str ) << 0; + this->chunks[i] |= getc( str ) << 8; + } + this->type = DICT_DZIP; + } else { + fseek( str, this->headerLength, SEEK_SET ); + } + } + + if (this->flags & GZ_FNAME) { /* FIXME! Add checking against header len */ + pt = buffer; + while ((c = getc( str )) && c != EOF) + *pt++ = c; + *pt = '\0'; + + this->origFilename = buffer; + this->headerLength += this->origFilename.length() + 1; + } else { + this->origFilename = ""; + } + + if (this->flags & GZ_COMMENT) { /* FIXME! Add checking for header len */ + pt = buffer; + while ((c = getc( str )) && c != EOF) + *pt++ = c; + *pt = '\0'; + comment = buffer; + headerLength += comment.length()+1; + } else { + comment = ""; + } + + if (this->flags & GZ_FHCRC) { + getc( str ); + getc( str ); + this->headerLength += 2; + } + + if (ftell( str ) != this->headerLength + 1) { + //err_internal( __FUNCTION__, + // "File position (%lu) != header length + 1 (%d)\n", + // ftell( str ), this->headerLength + 1 ); + } + + fseek( str, -8, SEEK_END ); + this->crc = getc( str ) << 0; + this->crc |= getc( str ) << 8; + this->crc |= getc( str ) << 16; + this->crc |= getc( str ) << 24; + this->length = getc( str ) << 0; + this->length |= getc( str ) << 8; + this->length |= getc( str ) << 16; + this->length |= getc( str ) << 24; + this->compressedLength = ftell( str ); + + /* Compute offsets */ + this->offsets = (unsigned long *)malloc( sizeof( this->offsets[0] ) + * this->chunkCount ); + for (offset = this->headerLength + 1, i = 0; + i < this->chunkCount; + i++) { + this->offsets[i] = offset; + offset += this->chunks[i]; + } + + fclose( str ); + return 0; +} + +bool dictData::open(const std::string& fname, int computeCRC) +{ + struct stat sb; + int j; + int fd; + + this->initialized = 0; + + if (stat(fname.c_str(), &sb) || !S_ISREG(sb.st_mode)) { + //err_warning( __FUNCTION__, + // "%s is not a regular file -- ignoring\n", fname ); + return false; + } + + if (read_header(fname, computeCRC)) { + //err_fatal( __FUNCTION__, + // "\"%s\" not in text or dzip format\n", fname ); + return false; + } + + if ((fd = ::open(fname.c_str(), O_RDONLY )) < 0) { + //err_fatal_errno( __FUNCTION__, + // "Cannot open data file \"%s\"\n", fname ); + return false; + } + if (fstat(fd, &sb)) { + //err_fatal_errno( __FUNCTION__, + // "Cannot stat data file \"%s\"\n", fname ); + return false; + } + + this->size = sb.st_size; + ::close(fd); + if (!mapfile.open(fname.c_str(), size)) + return false; + + this->start=mapfile.begin(); + this->end = this->start + this->size; + + for (j = 0; j < DICT_CACHE_SIZE; j++) { + cache[j].chunk = -1; + cache[j].stamp = -1; + cache[j].inBuffer = NULL; + cache[j].count = 0; + } + + return true; +} + +void dictData::close() +{ + int i; + + if (this->chunks) + free(this->chunks); + if (this->offsets) + free(this->offsets); + + if (this->initialized) { + if (inflateEnd( &this->zStream )) { + //err_internal( __FUNCTION__, + // "Cannot shut down inflation engine: %s\n", + // this->zStream.msg ); + } + } + + for (i = 0; i < DICT_CACHE_SIZE; ++i){ + if (this -> cache [i].inBuffer) + free (this -> cache [i].inBuffer); + } +} + +void dictData::read(char *buffer, unsigned long start, unsigned long size) +{ + char *pt; + unsigned long end; + int count; + char *inBuffer; + char outBuffer[OUT_BUFFER_SIZE]; + int firstChunk, lastChunk; + int firstOffset, lastOffset; + int i, j; + int found, target, lastStamp; + static int stamp = 0; + + end = start + size; + + //buffer = malloc( size + 1 ); + + //PRINTF(DBG_UNZIP, + // ("dict_data_read( %p, %lu, %lu )\n", + //h, start, size )); + + + switch (this->type) { + case DICT_GZIP: + //err_fatal( __FUNCTION__, + // "Cannot seek on pure gzip format files.\n" + // "Use plain text (for performance)" + // " or dzip format (for space savings).\n" ); + break; + case DICT_TEXT: + memcpy( buffer, this->start + start, size ); + //buffer[size] = '\0'; + break; + case DICT_DZIP: + if (!this->initialized) { + ++this->initialized; + this->zStream.zalloc = NULL; + this->zStream.zfree = NULL; + this->zStream.opaque = NULL; + this->zStream.next_in = 0; + this->zStream.avail_in = 0; + this->zStream.next_out = NULL; + this->zStream.avail_out = 0; + if (inflateInit2( &this->zStream, -15 ) != Z_OK) { + //err_internal( __FUNCTION__, + // "Cannot initialize inflation engine: %s\n", + //this->zStream.msg ); + } + } + firstChunk = start / this->chunkLength; + firstOffset = start - firstChunk * this->chunkLength; + lastChunk = end / this->chunkLength; + lastOffset = end - lastChunk * this->chunkLength; + //PRINTF(DBG_UNZIP, + // (" start = %lu, end = %lu\n" + //"firstChunk = %d, firstOffset = %d," + //" lastChunk = %d, lastOffset = %d\n", + //start, end, firstChunk, firstOffset, lastChunk, lastOffset )); + for (pt = buffer, i = firstChunk; i <= lastChunk; i++) { + + /* Access cache */ + found = 0; + target = 0; + lastStamp = INT_MAX; + for (j = 0; j < DICT_CACHE_SIZE; j++) { +#if USE_CACHE + if (this->cache[j].chunk == i) { + found = 1; + target = j; + break; + } +#endif + if (this->cache[j].stamp < lastStamp) { + lastStamp = this->cache[j].stamp; + target = j; + } + } + + this->cache[target].stamp = ++stamp; + if (found) { + count = this->cache[target].count; + inBuffer = this->cache[target].inBuffer; + } else { + this->cache[target].chunk = i; + if (!this->cache[target].inBuffer) + this->cache[target].inBuffer = (char *)malloc( IN_BUFFER_SIZE ); + inBuffer = this->cache[target].inBuffer; + + if (this->chunks[i] >= OUT_BUFFER_SIZE ) { + //err_internal( __FUNCTION__, + // "this->chunks[%d] = %d >= %ld (OUT_BUFFER_SIZE)\n", + // i, this->chunks[i], OUT_BUFFER_SIZE ); + } + memcpy( outBuffer, this->start + this->offsets[i], this->chunks[i] ); + + this->zStream.next_in = (Bytef *)outBuffer; + this->zStream.avail_in = this->chunks[i]; + this->zStream.next_out = (Bytef *)inBuffer; + this->zStream.avail_out = IN_BUFFER_SIZE; + if (inflate( &this->zStream, Z_PARTIAL_FLUSH ) != Z_OK) { + //err_fatal( __FUNCTION__, "inflate: %s\n", this->zStream.msg ); + } + if (this->zStream.avail_in) { + //err_internal( __FUNCTION__, + // "inflate did not flush (%d pending, %d avail)\n", + // this->zStream.avail_in, this->zStream.avail_out ); + } + + count = IN_BUFFER_SIZE - this->zStream.avail_out; + + this->cache[target].count = count; + } + + if (i == firstChunk) { + if (i == lastChunk) { + memcpy( pt, inBuffer + firstOffset, lastOffset-firstOffset); + pt += lastOffset - firstOffset; + } else { + if (count != this->chunkLength ) { + //err_internal( __FUNCTION__, + // "Length = %d instead of %d\n", + //count, this->chunkLength ); + } + memcpy( pt, inBuffer + firstOffset, + this->chunkLength - firstOffset ); + pt += this->chunkLength - firstOffset; + } + } else if (i == lastChunk) { + memcpy( pt, inBuffer, lastOffset ); + pt += lastOffset; + } else { + assert( count == this->chunkLength ); + memcpy( pt, inBuffer, this->chunkLength ); + pt += this->chunkLength; + } + } + //*pt = '\0'; + break; + case DICT_UNKNOWN: + //err_fatal( __FUNCTION__, "Cannot read unknown file type\n" ); + break; + } +} diff --git a/src/lib/dictziplib.hpp b/src/lib/dictziplib.hpp new file mode 100644 index 0000000..172912d --- /dev/null +++ b/src/lib/dictziplib.hpp @@ -0,0 +1,57 @@ +#ifndef __DICT_ZIP_LIB_H__ +#define __DICT_ZIP_LIB_H__ + +#include <ctime> +#include <string> +#include <zlib.h> + +#include "mapfile.hpp" + + +#define DICT_CACHE_SIZE 5 + +struct dictCache { + int chunk; + char *inBuffer; + int stamp; + int count; +}; + +struct dictData { + dictData() {} + bool open(const std::string& filename, int computeCRC); + void close(); + void read(char *buffer, unsigned long start, unsigned long size); + ~dictData() { close(); } +private: + const char *start; /* start of mmap'd area */ + const char *end; /* end of mmap'd area */ + unsigned long size; /* size of mmap */ + + int type; + z_stream zStream; + int initialized; + + int headerLength; + int method; + int flags; + time_t mtime; + int extraFlags; + int os; + int version; + int chunkLength; + int chunkCount; + int *chunks; + unsigned long *offsets; /* Sum-scan of chunks. */ + std::string origFilename; + std::string comment; + unsigned long crc; + unsigned long length; + unsigned long compressedLength; + dictCache cache[DICT_CACHE_SIZE]; + MapFile mapfile; + + int read_header(const std::string &filename, int computeCRC); +}; + +#endif//!__DICT_ZIP_LIB_H__ diff --git a/src/lib/distance.cpp b/src/lib/distance.cpp new file mode 100644 index 0000000..b764d7c --- /dev/null +++ b/src/lib/distance.cpp @@ -0,0 +1,203 @@ +/* + writer : Opera Wang + E-Mail : wangvisual AT sohu DOT com + License: GPL +*/ + +/* filename: distance.cc */ +/* +http://www.merriampark.com/ld.htm +What is Levenshtein Distance? + +Levenshtein distance (LD) is a measure of the similarity between two strings, +which we will refer to as the source string (s) and the target string (t). +The distance is the number of deletions, insertions, or substitutions required + to transform s into t. For example, + + * If s is "test" and t is "test", then LD(s,t) = 0, because no transformations are needed. + The strings are already identical. + * If s is "test" and t is "tent", then LD(s,t) = 1, because one substitution + (change "s" to "n") is sufficient to transform s into t. + +The greater the Levenshtein distance, the more different the strings are. + +Levenshtein distance is named after the Russian scientist Vladimir Levenshtein, + who devised the algorithm in 1965. If you can't spell or pronounce Levenshtein, + the metric is also sometimes called edit distance. + +The Levenshtein distance algorithm has been used in: + + * Spell checking + * Speech recognition + * DNA analysis + * Plagiarism detection +*/ + + +#include <stdlib.h> +#include <string.h> +//#include <stdio.h> + +#include "distance.h" + +#define OPTIMIZE_ED +/* +Cover transposition, in addition to deletion, +insertion and substitution. This step is taken from: +Berghel, Hal ; Roach, David : "An Extension of Ukkonen's +Enhanced Dynamic Programming ASM Algorithm" +(http://www.acm.org/~hlb/publications/asm/asm.html) +*/ +#define COVER_TRANSPOSITION + +/****************************************/ +/*Implementation of Levenshtein distance*/ +/****************************************/ + +EditDistance::EditDistance() +{ + currentelements = 2500; // It's enough for most conditions :-) + d = (int*)malloc(sizeof(int)*currentelements); +} + +EditDistance::~EditDistance() +{ +// printf("size:%d\n",currentelements); + if (d) free(d); +} + +#ifdef OPTIMIZE_ED +int EditDistance::CalEditDistance(const gunichar *s,const gunichar *t,const int limit) +/*Compute levenshtein distance between s and t, this is using QUICK algorithm*/ +{ + int n=0,m=0,iLenDif,k,i,j,cost; + // Remove leftmost matching portion of strings + while ( *s && (*s==*t) ) + { + s++; + t++; + } + + while (s[n]) + { + n++; + } + while (t[m]) + { + m++; + } + + // Remove rightmost matching portion of strings by decrement n and m. + while ( n && m && (*(s+n-1)==*(t+m-1)) ) + { + n--;m--; + } + if ( m==0 || n==0 || d==(int*)0 ) + return (m+n); + if ( m < n ) + { + const gunichar * temp = s; + int itemp = n; + s = t; + t = temp; + n = m; + m = itemp; + } + iLenDif = m - n; + if ( iLenDif >= limit ) + return iLenDif; + // step 1 + n++;m++; +// d=(int*)malloc(sizeof(int)*m*n); + if ( m*n > currentelements ) + { + currentelements = m*n*2; // double the request + d = (int*)realloc(d,sizeof(int)*currentelements); + if ( (int*)0 == d ) + return (m+n); + } + // step 2, init matrix + for (k=0;k<n;k++) + d[k] = k; + for (k=1;k<m;k++) + d[k*n] = k; + // step 3 + for (i=1;i<n;i++) + { + // first calculate column, d(i,j) + for ( j=1;j<iLenDif+i;j++ ) + { + cost = s[i-1]==t[j-1]?0:1; + d[j*n+i] = minimum(d[(j-1)*n+i]+1,d[j*n+i-1]+1,d[(j-1)*n+i-1]+cost); +#ifdef COVER_TRANSPOSITION + if ( i>=2 && j>=2 && (d[j*n+i]-d[(j-2)*n+i-2]==2) + && (s[i-2]==t[j-1]) && (s[i-1]==t[j-2]) ) + d[j*n+i]--; +#endif + } + // second calculate row, d(k,j) + // now j==iLenDif+i; + for ( k=1;k<=i;k++ ) + { + cost = s[k-1]==t[j-1]?0:1; + d[j*n+k] = minimum(d[(j-1)*n+k]+1,d[j*n+k-1]+1,d[(j-1)*n+k-1]+cost); +#ifdef COVER_TRANSPOSITION + if ( k>=2 && j>=2 && (d[j*n+k]-d[(j-2)*n+k-2]==2) + && (s[k-2]==t[j-1]) && (s[k-1]==t[j-2]) ) + d[j*n+k]--; +#endif + } + // test if d(i,j) limit gets equal or exceed + if ( d[j*n+i] >= limit ) + { + return d[j*n+i]; + } + } + // d(n-1,m-1) + return d[n*m-1]; +} +#else +int EditDistance::CalEditDistance(const char *s,const char *t,const int limit) +{ + //Step 1 + int k,i,j,n,m,cost; + n=strlen(s); + m=strlen(t); + if( n!=0 && m!=0 && d!=(int*)0 ) + { + m++;n++; + if ( m*n > currentelements ) + { + currentelements = m*n*2; + d = (int*)realloc(d,sizeof(int)*currentelements); + if ( (int*)0 == d ) + return (m+n); + } + //Step 2 + for(k=0;k<n;k++) + d[k]=k; + for(k=0;k<m;k++) + d[k*n]=k; + //Step 3 and 4 + for(i=1;i<n;i++) + for(j=1;j<m;j++) + { + //Step 5 + if(s[i-1]==t[j-1]) + cost=0; + else + cost=1; + //Step 6 + d[j*n+i]=minimum(d[(j-1)*n+i]+1,d[j*n+i-1]+1,d[(j-1)*n+i-1]+cost); +#ifdef COVER_TRANSPOSITION + if ( i>=2 && j>=2 && (d[j*n+i]-d[(j-2)*n+i-2]==2) + && (s[i-2]==t[j-1]) && (s[i-1]==t[j-2]) ) + d[j*n+i]--; +#endif + } + return d[n*m-1]; + } + else + return (n+m); +} +#endif diff --git a/src/lib/distance.h b/src/lib/distance.h new file mode 100644 index 0000000..9a6f402 --- /dev/null +++ b/src/lib/distance.h @@ -0,0 +1,26 @@ +#ifndef DISTANCE_H +#define DISTANCE_H + +#include <glib.h> + +class EditDistance { +private: + int *d; + int currentelements; + /*Gets the minimum of three values */ + inline int minimum( const int a, const int b, const int c ) + { + int min = a; + if ( b < min ) + min = b; + if ( c < min ) + min = c; + return min; + }; +public: + EditDistance( ); + ~EditDistance( ); + int CalEditDistance( const gunichar *s, const gunichar *t, const int limit ); +}; + +#endif diff --git a/src/lib/file.hpp b/src/lib/file.hpp new file mode 100644 index 0000000..53e55c7 --- /dev/null +++ b/src/lib/file.hpp @@ -0,0 +1,53 @@ +#ifndef _FILE_HPP_ +#define _FILE_HPP_ + +#include <algorithm> +#include <glib.h> +#include <list> +#include <string> + + +typedef std::list<std::string> List; + +template<typename Function> +void __for_each_file(const std::string& dirname, const std::string& suff, + const List& order_list, const List& disable_list, + Function f) +{ + GDir *dir = g_dir_open(dirname.c_str(), 0, NULL); + if (dir) { + const gchar *filename; + + while ((filename = g_dir_read_name(dir))!=NULL) { + std::string fullfilename(dirname+G_DIR_SEPARATOR_S+filename); + if (g_file_test(fullfilename.c_str(), G_FILE_TEST_IS_DIR)) + __for_each_file(fullfilename, suff, order_list, disable_list, f); + else if (g_str_has_suffix(filename, suff.c_str()) && + std::find(order_list.begin(), order_list.end(), + fullfilename)==order_list.end()) { + bool disable=std::find(disable_list.begin(), + disable_list.end(), + fullfilename)!=disable_list.end(); + f(fullfilename, disable); + } + } + g_dir_close(dir); + } +} + +template<typename Function> +void for_each_file(const List& dirs_list, const std::string& suff, + const List& order_list, const List& disable_list, + Function f) +{ + List::const_iterator it; + for (it=order_list.begin(); it!=order_list.end(); ++it) { + bool disable=std::find(disable_list.begin(), disable_list.end(), + *it)!=disable_list.end(); + f(*it, disable); + } + for (it=dirs_list.begin(); it!=dirs_list.end(); ++it) + __for_each_file(*it, suff, order_list, disable_list, f); +} + +#endif//!_FILE_HPP_ diff --git a/src/lib/lib.cpp b/src/lib/lib.cpp new file mode 100644 index 0000000..9b7e4f4 --- /dev/null +++ b/src/lib/lib.cpp @@ -0,0 +1,1694 @@ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include <algorithm> +#include <cstring> +#include <cctype> + +#include <sys/stat.h> +#include <zlib.h> +#include <glib/gstdio.h> + +#include "distance.h" +#include "file.hpp" +#include "mapfile.hpp" + +#include "lib.h" + +// Notice: read src/tools/DICTFILE_FORMAT for the dictionary +// file's format information! + + +static inline bool bIsVowel(gchar inputchar) +{ + gchar ch = g_ascii_toupper(inputchar); + return( ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U' ); +} + +static bool bIsPureEnglish(const gchar *str) +{ + // i think this should work even when it is UTF8 string :). + for (int i=0; str[i]!=0; i++) + //if(str[i]<0) + //if(str[i]<32 || str[i]>126) // tab equal 9,so this is not OK. + // Better use isascii() but not str[i]<0 while char is default unsigned in arm + if (!isascii(str[i])) + return false; + return true; +} + +static inline gint stardict_strcmp(const gchar *s1, const gchar *s2) +{ + gint a=g_ascii_strcasecmp(s1, s2); + if (a == 0) + return strcmp(s1, s2); + else + return a; +} + +bool DictInfo::load_from_ifo_file(const std::string& ifofilename, + bool istreedict) +{ + ifo_file_name=ifofilename; + gchar *buffer; + if (!g_file_get_contents(ifofilename.c_str(), &buffer, NULL, NULL)) + return false; + +#define TREEDICT_MAGIC_DATA "StarDict's treedict ifo file\nversion=2.4.2\n" +#define DICT_MAGIC_DATA "StarDict's dict ifo file\nversion=2.4.2\n" + const gchar *magic_data=istreedict ? TREEDICT_MAGIC_DATA : DICT_MAGIC_DATA; + if (!g_str_has_prefix(buffer, magic_data)) { + g_free(buffer); + return false; + } + + gchar *p1,*p2,*p3; + + p1 = buffer + strlen(magic_data)-1; + + p2 = strstr(p1,"\nwordcount="); + if (!p2) { + g_free(buffer); + return false; + } + + p3 = strchr(p2+ sizeof("\nwordcount=")-1,'\n'); + gchar *tmpstr = (gchar *)g_memdup(p2+sizeof("\nwordcount=")-1, p3-(p2+sizeof("\nwordcount=")-1)+1); + tmpstr[p3-(p2+sizeof("\nwordcount=")-1)] = '\0'; + wordcount = atol(tmpstr); + g_free(tmpstr); + + if (istreedict) { + p2 = strstr(p1,"\ntdxfilesize="); + if (!p2) { + g_free(buffer); + return false; + } + p3 = strchr(p2+ sizeof("\ntdxfilesize=")-1,'\n'); + tmpstr = (gchar *)g_memdup(p2+sizeof("\ntdxfilesize=")-1, p3-(p2+sizeof("\ntdxfilesize=")-1)+1); + tmpstr[p3-(p2+sizeof("\ntdxfilesize=")-1)] = '\0'; + index_file_size = atol(tmpstr); + g_free(tmpstr); + } else { + + p2 = strstr(p1,"\nidxfilesize="); + if (!p2) { + g_free(buffer); + return false; + } + + p3 = strchr(p2+ sizeof("\nidxfilesize=")-1,'\n'); + tmpstr = (gchar *)g_memdup(p2+sizeof("\nidxfilesize=")-1, p3-(p2+sizeof("\nidxfilesize=")-1)+1); + tmpstr[p3-(p2+sizeof("\nidxfilesize=")-1)] = '\0'; + index_file_size = atol(tmpstr); + g_free(tmpstr); + } + + p2 = strstr(p1,"\nbookname="); + + if (!p2) { + g_free(buffer); + return false; + } + + p2 = p2 + sizeof("\nbookname=") -1; + p3 = strchr(p2, '\n'); + bookname.assign(p2, p3-p2); + + p2 = strstr(p1,"\nauthor="); + if (p2) { + p2 = p2 + sizeof("\nauthor=") -1; + p3 = strchr(p2, '\n'); + author.assign(p2, p3-p2); + } + + p2 = strstr(p1,"\nemail="); + if (p2) { + p2 = p2 + sizeof("\nemail=") -1; + p3 = strchr(p2, '\n'); + email.assign(p2, p3-p2); + } + + p2 = strstr(p1,"\nwebsite="); + if (p2) { + p2 = p2 + sizeof("\nwebsite=") -1; + p3 = strchr(p2, '\n'); + website.assign(p2, p3-p2); + } + + p2 = strstr(p1,"\ndate="); + if (p2) { + p2 = p2 + sizeof("\ndate=") -1; + p3 = strchr(p2, '\n'); + date.assign(p2, p3-p2); + } + + p2 = strstr(p1,"\ndescription="); + if (p2) { + p2 = p2 + sizeof("\ndescription=")-1; + p3 = strchr(p2, '\n'); + description.assign(p2, p3-p2); + } + + p2 = strstr(p1,"\nsametypesequence="); + if (p2) { + p2+=sizeof("\nsametypesequence=")-1; + p3 = strchr(p2, '\n'); + sametypesequence.assign(p2, p3-p2); + } + + g_free(buffer); + + return true; +} +//=================================================================== +DictBase::DictBase() +{ + dictfile = NULL; + cache_cur =0; +} + +DictBase::~DictBase() +{ + if (dictfile) + fclose(dictfile); +} + +gchar* DictBase::GetWordData(guint32 idxitem_offset, guint32 idxitem_size) +{ + for (int i=0; i<WORDDATA_CACHE_NUM; i++) + if (cache[i].data && cache[i].offset == idxitem_offset) + return cache[i].data; + + if (dictfile) + fseek(dictfile, idxitem_offset, SEEK_SET); + + gchar *data; + if (!sametypesequence.empty()) { + gchar *origin_data = (gchar *)g_malloc(idxitem_size); + + if (dictfile) + fread(origin_data, idxitem_size, 1, dictfile); + else + dictdzfile->read(origin_data, idxitem_offset, idxitem_size); + + guint32 data_size; + gint sametypesequence_len = sametypesequence.length(); + //there have sametypesequence_len char being omitted. + data_size = idxitem_size + sizeof(guint32) + sametypesequence_len; + //if the last item's size is determined by the end up '\0',then +=sizeof(gchar); + //if the last item's size is determined by the head guint32 type data,then +=sizeof(guint32); + switch (sametypesequence[sametypesequence_len-1]) { + case 'm': + case 't': + case 'y': + case 'l': + case 'g': + case 'x': + data_size += sizeof(gchar); + break; + case 'W': + case 'P': + data_size += sizeof(guint32); + break; + default: + if (g_ascii_isupper(sametypesequence[sametypesequence_len-1])) + data_size += sizeof(guint32); + else + data_size += sizeof(gchar); + break; + } + data = (gchar *)g_malloc(data_size); + gchar *p1,*p2; + p1 = data + sizeof(guint32); + p2 = origin_data; + guint32 sec_size; + //copy the head items. + for (int i=0; i<sametypesequence_len-1; i++) { + *p1=sametypesequence[i]; + p1+=sizeof(gchar); + switch (sametypesequence[i]) { + case 'm': + case 't': + case 'y': + case 'l': + case 'g': + case 'x': + sec_size = strlen(p2)+1; + memcpy(p1, p2, sec_size); + p1+=sec_size; + p2+=sec_size; + break; + case 'W': + case 'P': + sec_size = *reinterpret_cast<guint32 *>(p2); + sec_size += sizeof(guint32); + memcpy(p1, p2, sec_size); + p1+=sec_size; + p2+=sec_size; + break; + default: + if (g_ascii_isupper(sametypesequence[i])) { + sec_size = *reinterpret_cast<guint32 *>(p2); + sec_size += sizeof(guint32); + } else { + sec_size = strlen(p2)+1; + } + memcpy(p1, p2, sec_size); + p1+=sec_size; + p2+=sec_size; + break; + } + } + //calculate the last item 's size. + sec_size = idxitem_size - (p2-origin_data); + *p1=sametypesequence[sametypesequence_len-1]; + p1+=sizeof(gchar); + switch (sametypesequence[sametypesequence_len-1]) { + case 'm': + case 't': + case 'y': + case 'l': + case 'g': + case 'x': + memcpy(p1, p2, sec_size); + p1 += sec_size; + *p1='\0';//add the end up '\0'; + break; + case 'W': + case 'P': + *reinterpret_cast<guint32 *>(p1)=sec_size; + p1 += sizeof(guint32); + memcpy(p1, p2, sec_size); + break; + default: + if (g_ascii_isupper(sametypesequence[sametypesequence_len-1])) { + *reinterpret_cast<guint32 *>(p1)=sec_size; + p1 += sizeof(guint32); + memcpy(p1, p2, sec_size); + } else { + memcpy(p1, p2, sec_size); + p1 += sec_size; + *p1='\0'; + } + break; + } + g_free(origin_data); + *reinterpret_cast<guint32 *>(data)=data_size; + } else { + data = (gchar *)g_malloc(idxitem_size + sizeof(guint32)); + if (dictfile) + fread(data+sizeof(guint32), idxitem_size, 1, dictfile); + else + dictdzfile->read(data+sizeof(guint32), idxitem_offset, idxitem_size); + *reinterpret_cast<guint32 *>(data)=idxitem_size+sizeof(guint32); + } + g_free(cache[cache_cur].data); + + cache[cache_cur].data = data; + cache[cache_cur].offset = idxitem_offset; + cache_cur++; + if (cache_cur==WORDDATA_CACHE_NUM) + cache_cur = 0; + return data; +} + +inline bool DictBase::containSearchData() +{ + if (sametypesequence.empty()) + return true; + + return sametypesequence.find_first_of("mlgxty")!=std::string::npos; +} + +bool DictBase::SearchData(std::vector<std::string> &SearchWords, guint32 idxitem_offset, guint32 idxitem_size, gchar *origin_data) +{ + int nWord = SearchWords.size(); + std::vector<bool> WordFind(nWord, false); + int nfound=0; + + if (dictfile) + fseek(dictfile, idxitem_offset, SEEK_SET); + if (dictfile) + fread(origin_data, idxitem_size, 1, dictfile); + else + dictdzfile->read(origin_data, idxitem_offset, idxitem_size); + gchar *p = origin_data; + guint32 sec_size; + int j; + if (!sametypesequence.empty()) { + gint sametypesequence_len = sametypesequence.length(); + for (int i=0; i<sametypesequence_len-1; i++) { + switch (sametypesequence[i]) { + case 'm': + case 't': + case 'y': + case 'l': + case 'g': + case 'x': + for (j=0; j<nWord; j++) + if (!WordFind[j] && strstr(p, SearchWords[j].c_str())) { + WordFind[j] = true; + ++nfound; + } + + + if (nfound==nWord) + return true; + sec_size = strlen(p)+1; + p+=sec_size; + break; + default: + if (g_ascii_isupper(sametypesequence[i])) { + sec_size = *reinterpret_cast<guint32 *>(p); + sec_size += sizeof(guint32); + } else { + sec_size = strlen(p)+1; + } + p+=sec_size; + } + } + switch (sametypesequence[sametypesequence_len-1]) { + case 'm': + case 't': + case 'y': + case 'l': + case 'g': + case 'x': + sec_size = idxitem_size - (p-origin_data); + for (j=0; j<nWord; j++) + if (!WordFind[j] && + g_strstr_len(p, sec_size, SearchWords[j].c_str())) { + WordFind[j] = true; + ++nfound; + } + + + if (nfound==nWord) + return true; + break; + } + } else { + while (guint32(p - origin_data)<idxitem_size) { + switch (*p) { + case 'm': + case 't': + case 'y': + case 'l': + case 'g': + case 'x': + for (j=0; j<nWord; j++) + if (!WordFind[j] && strstr(p, SearchWords[j].c_str())) { + WordFind[j] = true; + ++nfound; + } + + if (nfound==nWord) + return true; + sec_size = strlen(p)+1; + p+=sec_size; + break; + default: + if (g_ascii_isupper(*p)) { + sec_size = *reinterpret_cast<guint32 *>(p); + sec_size += sizeof(guint32); + } else { + sec_size = strlen(p)+1; + } + p+=sec_size; + } + } + } + return false; +} + +class offset_index : public index_file { +public: + offset_index() : idxfile(NULL) {} + ~offset_index(); + bool load(const std::string& url, gulong wc, gulong fsize); + const gchar *get_key(glong idx); + void get_data(glong idx); + const gchar *get_key_and_data(glong idx); + bool lookup(const char *str, glong &idx); +private: + static const gint ENTR_PER_PAGE=32; + static const char *CACHE_MAGIC; + + std::vector<guint32> wordoffset; + FILE *idxfile; + gulong wordcount; + + gchar wordentry_buf[256+sizeof(guint32)*2]; // The length of "word_str" should be less than 256. See src/tools/DICTFILE_FORMAT. + struct index_entry { + glong idx; + std::string keystr; + void assign(glong i, const std::string& str) { + idx=i; + keystr.assign(str); + } + }; + index_entry first, last, middle, real_last; + + struct page_entry { + gchar *keystr; + guint32 off, size; + }; + std::vector<gchar> page_data; + struct page_t { + glong idx; + page_entry entries[ENTR_PER_PAGE]; + + page_t(): idx(-1) {} + void fill(gchar *data, gint nent, glong idx_); + } page; + gulong load_page(glong page_idx); + const gchar *read_first_on_page_key(glong page_idx); + const gchar *get_first_on_page_key(glong page_idx); + bool load_cache(const std::string& url); + bool save_cache(const std::string& url); + static strlist_t get_cache_variant(const std::string& url); +}; + +const char *offset_index::CACHE_MAGIC="StarDict's Cache, Version: 0.1"; + +class wordlist_index : public index_file { +public: + wordlist_index() : idxdatabuf(NULL) {} + ~wordlist_index(); + bool load(const std::string& url, gulong wc, gulong fsize); + const gchar *get_key(glong idx); + void get_data(glong idx); + const gchar *get_key_and_data(glong idx); + bool lookup(const char *str, glong &idx); +private: + gchar *idxdatabuf; + std::vector<gchar *> wordlist; +}; + +void offset_index::page_t::fill(gchar *data, gint nent, glong idx_) +{ + idx=idx_; + gchar *p=data; + glong len; + for (gint i=0; i<nent; ++i) { + entries[i].keystr=p; + len=strlen(p); + p+=len+1; + entries[i].off=g_ntohl(*reinterpret_cast<guint32 *>(p)); + p+=sizeof(guint32); + entries[i].size=g_ntohl(*reinterpret_cast<guint32 *>(p)); + p+=sizeof(guint32); + } +} + +offset_index::~offset_index() +{ + if (idxfile) + fclose(idxfile); +} + +inline const gchar *offset_index::read_first_on_page_key(glong page_idx) +{ + fseek(idxfile, wordoffset[page_idx], SEEK_SET); + guint32 page_size=wordoffset[page_idx+1]-wordoffset[page_idx]; + fread(wordentry_buf, std::min(sizeof(wordentry_buf), page_size), 1, idxfile); //TODO: check returned values, deal with word entry that strlen>255. + return wordentry_buf; +} + +inline const gchar *offset_index::get_first_on_page_key(glong page_idx) +{ + if (page_idx<middle.idx) { + if (page_idx==first.idx) + return first.keystr.c_str(); + return read_first_on_page_key(page_idx); + } else if (page_idx>middle.idx) { + if (page_idx==last.idx) + return last.keystr.c_str(); + return read_first_on_page_key(page_idx); + } else + return middle.keystr.c_str(); +} + +bool offset_index::load_cache(const std::string& url) +{ + strlist_t vars=get_cache_variant(url); + + for (strlist_t::const_iterator it=vars.begin(); it!=vars.end(); ++it) { + struct stat idxstat, cachestat; + if (g_stat(url.c_str(), &idxstat)!=0 || + g_stat(it->c_str(), &cachestat)!=0) + continue; + if (cachestat.st_mtime<idxstat.st_mtime) + continue; + MapFile mf; + if (!mf.open(it->c_str(), cachestat.st_size)) + continue; + if (strncmp(mf.begin(), CACHE_MAGIC, strlen(CACHE_MAGIC))!=0) + continue; + memcpy(&wordoffset[0], mf.begin()+strlen(CACHE_MAGIC), wordoffset.size()*sizeof(wordoffset[0])); + return true; + + } + + return false; +} + +strlist_t offset_index::get_cache_variant(const std::string& url) +{ + strlist_t res; + res.push_back(url+".oft"); + if (!g_file_test(g_get_user_cache_dir(), G_FILE_TEST_EXISTS) && + g_mkdir(g_get_user_cache_dir(), 0700)==-1) + return res; + + std::string cache_dir=std::string(g_get_user_cache_dir())+G_DIR_SEPARATOR_S+"sdcv"; + + if (!g_file_test(cache_dir.c_str(), G_FILE_TEST_EXISTS)) { + if (g_mkdir(cache_dir.c_str(), 0700)==-1) + return res; + } else if (!g_file_test(cache_dir.c_str(), G_FILE_TEST_IS_DIR)) + return res; + + gchar *base=g_path_get_basename(url.c_str()); + res.push_back(cache_dir+G_DIR_SEPARATOR_S+base+".oft"); + g_free(base); + return res; +} + +bool offset_index::save_cache(const std::string& url) +{ + strlist_t vars=get_cache_variant(url); + for (strlist_t::const_iterator it=vars.begin(); it!=vars.end(); ++it) { + FILE *out=fopen(it->c_str(), "wb"); + if (!out) + continue; + if (fwrite(CACHE_MAGIC, 1, strlen(CACHE_MAGIC), out)!=strlen(CACHE_MAGIC)) + continue; + if (fwrite(&wordoffset[0], sizeof(wordoffset[0]), wordoffset.size(), out)!=wordoffset.size()) + continue; + fclose(out); + printf("save to cache %s\n", url.c_str()); + return true; + } + return false; +} + +bool offset_index::load(const std::string& url, gulong wc, gulong fsize) +{ + wordcount=wc; + gulong npages=(wc-1)/ENTR_PER_PAGE+2; + wordoffset.resize(npages); + if (!load_cache(url)) {//map file will close after finish of block + MapFile map_file; + if (!map_file.open(url.c_str(), fsize)) + return false; + const gchar *idxdatabuffer=map_file.begin(); + + const gchar *p1 = idxdatabuffer; + gulong index_size; + guint32 j=0; + for (guint32 i=0; i<wc; i++) { + index_size=strlen(p1) +1 + 2*sizeof(guint32); + if (i % ENTR_PER_PAGE==0) { + wordoffset[j]=p1-idxdatabuffer; + ++j; + } + p1 += index_size; + } + wordoffset[j]=p1-idxdatabuffer; + if (!save_cache(url)) + fprintf(stderr, "cache update failed\n"); + } + + if (!(idxfile = fopen(url.c_str(), "rb"))) { + wordoffset.resize(0); + return false; + } + + first.assign(0, read_first_on_page_key(0)); + last.assign(wordoffset.size()-2, read_first_on_page_key(wordoffset.size()-2)); + middle.assign((wordoffset.size()-2)/2, read_first_on_page_key((wordoffset.size()-2)/2)); + real_last.assign(wc-1, get_key(wc-1)); + + return true; +} + +inline gulong offset_index::load_page(glong page_idx) +{ + gulong nentr=ENTR_PER_PAGE; + if (page_idx==glong(wordoffset.size()-2)) + if ((nentr=wordcount%ENTR_PER_PAGE)==0) + nentr=ENTR_PER_PAGE; + + + if (page_idx!=page.idx) { + page_data.resize(wordoffset[page_idx+1]-wordoffset[page_idx]); + fseek(idxfile, wordoffset[page_idx], SEEK_SET); + fread(&page_data[0], 1, page_data.size(), idxfile); + page.fill(&page_data[0], nentr, page_idx); + } + + return nentr; +} + +const gchar *offset_index::get_key(glong idx) +{ + load_page(idx/ENTR_PER_PAGE); + glong idx_in_page=idx%ENTR_PER_PAGE; + wordentry_offset=page.entries[idx_in_page].off; + wordentry_size=page.entries[idx_in_page].size; + + return page.entries[idx_in_page].keystr; +} + +void offset_index::get_data(glong idx) +{ + get_key(idx); +} + +const gchar *offset_index::get_key_and_data(glong idx) +{ + return get_key(idx); +} + +bool offset_index::lookup(const char *str, glong &idx) +{ + bool bFound=false; + glong iFrom; + glong iTo=wordoffset.size()-2; + gint cmpint; + glong iThisIndex; + if (stardict_strcmp(str, first.keystr.c_str())<0) { + idx = 0; + return false; + } else if (stardict_strcmp(str, real_last.keystr.c_str()) >0) { + idx = INVALID_INDEX; + return false; + } else { + iFrom=0; + iThisIndex=0; + while (iFrom<=iTo) { + iThisIndex=(iFrom+iTo)/2; + cmpint = stardict_strcmp(str, get_first_on_page_key(iThisIndex)); + if (cmpint>0) + iFrom=iThisIndex+1; + else if (cmpint<0) + iTo=iThisIndex-1; + else { + bFound=true; + break; + } + } + if (!bFound) + idx = iTo; //prev + else + idx = iThisIndex; + } + if (!bFound) { + gulong netr=load_page(idx); + iFrom=1; // Needn't search the first word anymore. + iTo=netr-1; + iThisIndex=0; + while (iFrom<=iTo) { + iThisIndex=(iFrom+iTo)/2; + cmpint = stardict_strcmp(str, page.entries[iThisIndex].keystr); + if (cmpint>0) + iFrom=iThisIndex+1; + else if (cmpint<0) + iTo=iThisIndex-1; + else { + bFound=true; + break; + } + } + idx*=ENTR_PER_PAGE; + if (!bFound) + idx += iFrom; //next + else + idx += iThisIndex; + } else { + idx*=ENTR_PER_PAGE; + } + return bFound; +} + +wordlist_index::~wordlist_index() +{ + g_free(idxdatabuf); +} + +bool wordlist_index::load(const std::string& url, gulong wc, gulong fsize) +{ + gzFile in = gzopen(url.c_str(), "rb"); + if (in == NULL) + return false; + + idxdatabuf = (gchar *)g_malloc(fsize); + + gulong len = gzread(in, idxdatabuf, fsize); + gzclose(in); + if ((glong)len < 0) + return false; + + if (len != fsize) + return false; + + wordlist.resize(wc+1); + gchar *p1 = idxdatabuf; + guint32 i; + for (i=0; i<wc; i++) { + wordlist[i] = p1; + p1 += strlen(p1) +1 + 2*sizeof(guint32); + } + wordlist[wc] = p1; + + return true; +} + +const gchar *wordlist_index::get_key(glong idx) +{ + return wordlist[idx]; +} + +void wordlist_index::get_data(glong idx) +{ + gchar *p1 = wordlist[idx]+strlen(wordlist[idx])+sizeof(gchar); + wordentry_offset = g_ntohl(*reinterpret_cast<guint32 *>(p1)); + p1 += sizeof(guint32); + wordentry_size = g_ntohl(*reinterpret_cast<guint32 *>(p1)); +} + +const gchar *wordlist_index::get_key_and_data(glong idx) +{ + get_data(idx); + return get_key(idx); +} + +bool wordlist_index::lookup(const char *str, glong &idx) +{ + bool bFound=false; + glong iTo=wordlist.size()-2; + + if (stardict_strcmp(str, get_key(0))<0) { + idx = 0; + } else if (stardict_strcmp(str, get_key(iTo)) >0) { + idx = INVALID_INDEX; + } else { + glong iThisIndex=0; + glong iFrom=0; + gint cmpint; + while (iFrom<=iTo) { + iThisIndex=(iFrom+iTo)/2; + cmpint = stardict_strcmp(str, get_key(iThisIndex)); + if (cmpint>0) + iFrom=iThisIndex+1; + else if (cmpint<0) + iTo=iThisIndex-1; + else { + bFound=true; + break; + } + } + if (!bFound) + idx = iFrom; //next + else + idx = iThisIndex; + } + return bFound; +} + +//=================================================================== +bool Dict::load(const std::string& ifofilename) +{ + gulong idxfilesize; + if (!load_ifofile(ifofilename, idxfilesize)) + return false; + + std::string fullfilename(ifofilename); + fullfilename.replace(fullfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "dict.dz"); + + if (g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS)) { + dictdzfile.reset(new dictData); + if (!dictdzfile->open(fullfilename, 0)) { + //g_print("open file %s failed!\n",fullfilename); + return false; + } + } else { + fullfilename.erase(fullfilename.length()-sizeof(".dz")+1, sizeof(".dz")-1); + dictfile = fopen(fullfilename.c_str(),"rb"); + if (!dictfile) { + //g_print("open file %s failed!\n",fullfilename); + return false; + } + } + + fullfilename=ifofilename; + fullfilename.replace(fullfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "idx.gz"); + + if (g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS)) { + idx_file.reset(new wordlist_index); + } else { + fullfilename.erase(fullfilename.length()-sizeof(".gz")+1, sizeof(".gz")-1); + idx_file.reset(new offset_index); + } + + if (!idx_file->load(fullfilename, wordcount, idxfilesize)) + return false; + + //g_print("bookname: %s , wordcount %lu\n", bookname.c_str(), narticles()); + return true; +} + +bool Dict::load_ifofile(const std::string& ifofilename, gulong &idxfilesize) +{ + DictInfo dict_info; + if (!dict_info.load_from_ifo_file(ifofilename, false)) + return false; + if (dict_info.wordcount==0) + return false; + + + mDict_info = dict_info; + + ifo_file_name=dict_info.ifo_file_name; + wordcount=dict_info.wordcount; + bookname=dict_info.bookname; + + idxfilesize=dict_info.index_file_size; + + sametypesequence=dict_info.sametypesequence; + + return true; +} + +bool Dict::LookupWithRule(GPatternSpec *pspec, glong *aIndex, int iBuffLen) +{ + int iIndexCount=0; + + for(guint32 i=0; i<narticles() && iIndexCount<iBuffLen-1; i++) + if (g_pattern_match_string(pspec, get_key(i))) + aIndex[iIndexCount++]=i; + + aIndex[iIndexCount]= -1; // -1 is the end. + + return (iIndexCount>0); +} + +//=================================================================== +Libs::Libs(progress_func_t f) +{ + progress_func=f; + iMaxFuzzyDistance = MAX_FUZZY_DISTANCE; //need to read from cfg. +} + +Libs::~Libs() +{ + for (std::vector<Dict *>::iterator p=oLib.begin(); p!=oLib.end(); ++p) + delete *p; +} + +void Libs::load_dict(const std::string& url) +{ + Dict *lib=new Dict; + if (lib->load(url)) + oLib.push_back(lib); + else + delete lib; +} + +class DictLoader { +public: + DictLoader(Libs& lib_): lib(lib_) {} + void operator()(const std::string& url, bool disable) { + if (!disable) + lib.load_dict(url); + } +private: + Libs& lib; +}; + +void Libs::load(const strlist_t& dicts_dirs, + const strlist_t& order_list, + const strlist_t& disable_list) +{ + for_each_file(dicts_dirs, ".ifo", order_list, disable_list, + DictLoader(*this)); +} + +class DictReLoader { +public: + DictReLoader(std::vector<Dict *> &p, std::vector<Dict *> &f, + Libs& lib_) : prev(p), future(f), lib(lib_) + { + } + void operator()(const std::string& url, bool disable) { + if (!disable) { + Dict *dict=find(url); + if (dict) + future.push_back(dict); + else + lib.load_dict(url); + } + } +private: + std::vector<Dict *> &prev; + std::vector<Dict *> &future; + Libs& lib; + + Dict *find(const std::string& url) { + std::vector<Dict *>::iterator it; + for (it=prev.begin(); it!=prev.end(); ++it) + if ((*it)->ifofilename()==url) + break; + if (it!=prev.end()) { + Dict *res=*it; + prev.erase(it); + return res; + } + return NULL; + } +}; + +void Libs::reload(const strlist_t& dicts_dirs, + const strlist_t& order_list, + const strlist_t& disable_list) +{ + std::vector<Dict *> prev(oLib); + oLib.clear(); + for_each_file(dicts_dirs, ".ifo", order_list, disable_list, + DictReLoader(prev, oLib, *this)); + for (std::vector<Dict *>::iterator it=prev.begin(); it!=prev.end(); ++it) + delete *it; +} + +const gchar *Libs::poGetCurrentWord(glong * iCurrent) +{ + const gchar *poCurrentWord = NULL; + const gchar *word; + for (std::vector<Dict *>::size_type iLib=0; iLib<oLib.size(); iLib++) { + if (iCurrent[iLib]==INVALID_INDEX) + continue; + if ( iCurrent[iLib]>=narticles(iLib) || iCurrent[iLib]<0) + continue; + if ( poCurrentWord == NULL ) { + poCurrentWord = poGetWord(iCurrent[iLib],iLib); + } else { + word = poGetWord(iCurrent[iLib],iLib); + + if (stardict_strcmp(poCurrentWord, word) > 0 ) + poCurrentWord = word; + } + } + return poCurrentWord; +} + +const gchar * +Libs::poGetNextWord(const gchar *sWord, glong *iCurrent) +{ + // the input can be: + // (word,iCurrent),read word,write iNext to iCurrent,and return next word. used by TopWin::NextCallback(); + // (NULL,iCurrent),read iCurrent,write iNext to iCurrent,and return next word. used by AppCore::ListWords(); + const gchar *poCurrentWord = NULL; + std::vector<Dict *>::size_type iCurrentLib=0; + const gchar *word; + + for (std::vector<Dict *>::size_type iLib=0;iLib<oLib.size();iLib++) { + if (sWord) + oLib[iLib]->Lookup(sWord, iCurrent[iLib]); + if (iCurrent[iLib]==INVALID_INDEX) + continue; + if (iCurrent[iLib]>=narticles(iLib) || iCurrent[iLib]<0) + continue; + if (poCurrentWord == NULL ) { + poCurrentWord = poGetWord(iCurrent[iLib],iLib); + iCurrentLib = iLib; + } else { + word = poGetWord(iCurrent[iLib],iLib); + + if (stardict_strcmp(poCurrentWord, word) > 0 ) { + poCurrentWord = word; + iCurrentLib = iLib; + } + } + } + if (poCurrentWord) { + iCurrent[iCurrentLib]++; + for (std::vector<Dict *>::size_type iLib=0;iLib<oLib.size();iLib++) { + if (iLib == iCurrentLib) + continue; + if (iCurrent[iLib]==INVALID_INDEX) + continue; + if ( iCurrent[iLib]>=narticles(iLib) || iCurrent[iLib]<0) + continue; + if (strcmp(poCurrentWord, poGetWord(iCurrent[iLib],iLib)) == 0 ) + iCurrent[iLib]++; + } + poCurrentWord = poGetCurrentWord(iCurrent); + } + return poCurrentWord; +} + + +const gchar * +Libs::poGetPreWord(glong * iCurrent) +{ + // used by TopWin::PreviousCallback(); the iCurrent is cached by AppCore::TopWinWordChange(); + const gchar *poCurrentWord = NULL; + std::vector<Dict *>::size_type iCurrentLib=0; + const gchar *word; + + for (std::vector<Dict *>::size_type iLib=0;iLib<oLib.size();iLib++) { + if (iCurrent[iLib]==INVALID_INDEX) + iCurrent[iLib]=narticles(iLib); + else { + if ( iCurrent[iLib]>narticles(iLib) || iCurrent[iLib]<=0) + continue; + } + if ( poCurrentWord == NULL ) { + poCurrentWord = poGetWord(iCurrent[iLib]-1,iLib); + iCurrentLib = iLib; + } else { + word = poGetWord(iCurrent[iLib]-1,iLib); + if (stardict_strcmp(poCurrentWord, word) < 0 ) { + poCurrentWord = word; + iCurrentLib = iLib; + } + } + } + + if (poCurrentWord) { + iCurrent[iCurrentLib]--; + for (std::vector<Dict *>::size_type iLib=0;iLib<oLib.size();iLib++) { + if (iLib == iCurrentLib) + continue; + if (iCurrent[iLib]>narticles(iLib) || iCurrent[iLib]<=0) + continue; + if (strcmp(poCurrentWord, poGetWord(iCurrent[iLib]-1,iLib)) == 0) { + iCurrent[iLib]--; + } else { + if (iCurrent[iLib]==narticles(iLib)) + iCurrent[iLib]=INVALID_INDEX; + } + } + } + return poCurrentWord; +} + +bool Libs::LookupSimilarWord(const gchar* sWord, glong & iWordIndex, int iLib) +{ + glong iIndex; + bool bFound=false; + gchar *casestr; + + if (!bFound) { + // to lower case. + casestr = g_utf8_strdown(sWord, -1); + if (strcmp(casestr, sWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + // to upper case. + if (!bFound) { + casestr = g_utf8_strup(sWord, -1); + if (strcmp(casestr, sWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + // Upper the first character and lower others. + if (!bFound) { + gchar *nextchar = g_utf8_next_char(sWord); + gchar *firstchar = g_utf8_strup(sWord, nextchar - sWord); + nextchar = g_utf8_strdown(nextchar, -1); + casestr = g_strdup_printf("%s%s", firstchar, nextchar); + g_free(firstchar); + g_free(nextchar); + if (strcmp(casestr, sWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + + if (bIsPureEnglish(sWord)) { + // If not Found , try other status of sWord. + int iWordLen=strlen(sWord); + bool isupcase; + + gchar *sNewWord = (gchar *)g_malloc(iWordLen + 1); + + //cut one char "s" or "d" + if(!bFound && iWordLen>1) { + isupcase = sWord[iWordLen-1]=='S' || !strncmp(&sWord[iWordLen-2],"ED",2); + if (isupcase || sWord[iWordLen-1]=='s' || !strncmp(&sWord[iWordLen-2],"ed",2)) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-1]='\0'; // cut "s" or "d" + if (oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + + //cut "ly" + if(!bFound && iWordLen>2) { + isupcase = !strncmp(&sWord[iWordLen-2],"LY",2); + if (isupcase || (!strncmp(&sWord[iWordLen-2],"ly",2))) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-2]='\0'; // cut "ly" + if (iWordLen>5 && sNewWord[iWordLen-3]==sNewWord[iWordLen-4] + && !bIsVowel(sNewWord[iWordLen-4]) && + bIsVowel(sNewWord[iWordLen-5])) {//doubled + + sNewWord[iWordLen-3]='\0'; + if( oLib[iLib]->Lookup(sNewWord, iIndex) ) + bFound=true; + else { + if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + if (!bFound) + sNewWord[iWordLen-3]=sNewWord[iWordLen-4]; //restore + } + } + if (!bFound) { + if (oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + } + + //cut "ing" + if(!bFound && iWordLen>3) { + isupcase = !strncmp(&sWord[iWordLen-3],"ING",3); + if (isupcase || !strncmp(&sWord[iWordLen-3],"ing",3) ) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-3]='\0'; + if ( iWordLen>6 && (sNewWord[iWordLen-4]==sNewWord[iWordLen-5]) + && !bIsVowel(sNewWord[iWordLen-5]) && + bIsVowel(sNewWord[iWordLen-6])) { //doubled + sNewWord[iWordLen-4]='\0'; + if (oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else { + if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + if (!bFound) + sNewWord[iWordLen-4]=sNewWord[iWordLen-5]; //restore + } + } + if( !bFound ) { + if (oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + if(!bFound) { + if (isupcase) + strcat(sNewWord,"E"); // add a char "E" + else + strcat(sNewWord,"e"); // add a char "e" + if(oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + } + + //cut two char "es" + if(!bFound && iWordLen>3) { + isupcase = (!strncmp(&sWord[iWordLen-2],"ES",2) && + (sWord[iWordLen-3] == 'S' || + sWord[iWordLen-3] == 'X' || + sWord[iWordLen-3] == 'O' || + (iWordLen >4 && sWord[iWordLen-3] == 'H' && + (sWord[iWordLen-4] == 'C' || + sWord[iWordLen-4] == 'S')))); + if (isupcase || + (!strncmp(&sWord[iWordLen-2],"es",2) && + (sWord[iWordLen-3] == 's' || sWord[iWordLen-3] == 'x' || + sWord[iWordLen-3] == 'o' || + (iWordLen >4 && sWord[iWordLen-3] == 'h' && + (sWord[iWordLen-4] == 'c' || sWord[iWordLen-4] == 's'))))) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-2]='\0'; + if(oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + + //cut "ed" + if (!bFound && iWordLen>3) { + isupcase = !strncmp(&sWord[iWordLen-2],"ED",2); + if (isupcase || !strncmp(&sWord[iWordLen-2],"ed",2)) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-2]='\0'; + if (iWordLen>5 && (sNewWord[iWordLen-3]==sNewWord[iWordLen-4]) + && !bIsVowel(sNewWord[iWordLen-4]) && + bIsVowel(sNewWord[iWordLen-5])) {//doubled + sNewWord[iWordLen-3]='\0'; + if (oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else { + if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + if (!bFound) + sNewWord[iWordLen-3]=sNewWord[iWordLen-4]; //restore + } + } + if (!bFound) { + if (oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + } + + // cut "ied" , add "y". + if (!bFound && iWordLen>3) { + isupcase = !strncmp(&sWord[iWordLen-3],"IED",3); + if (isupcase || (!strncmp(&sWord[iWordLen-3],"ied",3))) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-3]='\0'; + if (isupcase) + strcat(sNewWord,"Y"); // add a char "Y" + else + strcat(sNewWord,"y"); // add a char "y" + if (oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + + // cut "ies" , add "y". + if (!bFound && iWordLen>3) { + isupcase = !strncmp(&sWord[iWordLen-3],"IES",3); + if (isupcase || (!strncmp(&sWord[iWordLen-3],"ies",3))) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-3]='\0'; + if (isupcase) + strcat(sNewWord,"Y"); // add a char "Y" + else + strcat(sNewWord,"y"); // add a char "y" + if(oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + + // cut "er". + if (!bFound && iWordLen>2) { + isupcase = !strncmp(&sWord[iWordLen-2],"ER",2); + if (isupcase || (!strncmp(&sWord[iWordLen-2],"er",2))) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-2]='\0'; + if(oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + + // cut "est". + if (!bFound && iWordLen>3) { + isupcase = !strncmp(&sWord[iWordLen-3], "EST", 3); + if (isupcase || (!strncmp(&sWord[iWordLen-3],"est", 3))) { + strcpy(sNewWord,sWord); + sNewWord[iWordLen-3]='\0'; + if(oLib[iLib]->Lookup(sNewWord, iIndex)) + bFound=true; + else if (isupcase || g_ascii_isupper(sWord[0])) { + casestr = g_ascii_strdown(sNewWord, -1); + if (strcmp(casestr, sNewWord)) { + if(oLib[iLib]->Lookup(casestr, iIndex)) + bFound=true; + } + g_free(casestr); + } + } + } + + g_free(sNewWord); + } + + if (bFound) + iWordIndex = iIndex; +#if 0 + else { + //don't change iWordIndex here. + //when LookupSimilarWord all failed too, we want to use the old LookupWord index to list words. + //iWordIndex = INVALID_INDEX; + } +#endif + return bFound; +} + +bool Libs::SimpleLookupWord(const gchar* sWord, glong & iWordIndex, int iLib) +{ + bool bFound = oLib[iLib]->Lookup(sWord, iWordIndex); + if (!bFound) + bFound = LookupSimilarWord(sWord, iWordIndex, iLib); + return bFound; +} + +struct Fuzzystruct { + char * pMatchWord; + int iMatchWordDistance; +}; + +inline bool operator<(const Fuzzystruct & lh, const Fuzzystruct & rh) { + if (lh.iMatchWordDistance!=rh.iMatchWordDistance) + return lh.iMatchWordDistance<rh.iMatchWordDistance; + + if (lh.pMatchWord && rh.pMatchWord) + return stardict_strcmp(lh.pMatchWord, rh.pMatchWord)<0; + + return false; +} + +static inline void unicode_strdown(gunichar *str) +{ + while (*str) { + *str=g_unichar_tolower(*str); + ++str; + } +} + +bool Libs::LookupWithFuzzy(const gchar *sWord, gchar *reslist[], gint reslist_size) +{ + if (sWord[0] == '\0') + return false; + + Fuzzystruct oFuzzystruct[reslist_size]; + + for (int i=0; i<reslist_size; i++) { + oFuzzystruct[i].pMatchWord = NULL; + oFuzzystruct[i].iMatchWordDistance = iMaxFuzzyDistance; + } + int iMaxDistance = iMaxFuzzyDistance; + int iDistance; + bool Found = false; + EditDistance oEditDistance; + + glong iCheckWordLen; + const char *sCheck; + gunichar *ucs4_str1, *ucs4_str2; + glong ucs4_str2_len; + + ucs4_str2 = g_utf8_to_ucs4_fast(sWord, -1, &ucs4_str2_len); + unicode_strdown(ucs4_str2); + + for (std::vector<Dict *>::size_type iLib=0; iLib<oLib.size(); iLib++) { + if (progress_func) + progress_func(); + + //if (stardict_strcmp(sWord, poGetWord(0,iLib))>=0 && stardict_strcmp(sWord, poGetWord(narticles(iLib)-1,iLib))<=0) { + //there are Chinese dicts and English dicts... + if (TRUE) { + const int iwords = narticles(iLib); + for (int index=0; index<iwords; index++) { + sCheck = poGetWord(index,iLib); + // tolower and skip too long or too short words + iCheckWordLen = g_utf8_strlen(sCheck, -1); + if (iCheckWordLen-ucs4_str2_len>=iMaxDistance || + ucs4_str2_len-iCheckWordLen>=iMaxDistance) + continue; + ucs4_str1 = g_utf8_to_ucs4_fast(sCheck, -1, NULL); + if (iCheckWordLen > ucs4_str2_len) + ucs4_str1[ucs4_str2_len]=0; + unicode_strdown(ucs4_str1); + + iDistance = oEditDistance.CalEditDistance(ucs4_str1, ucs4_str2, iMaxDistance); + g_free(ucs4_str1); + if (iDistance<iMaxDistance && iDistance < ucs4_str2_len) { + // when ucs4_str2_len=1,2 we need less fuzzy. + Found = true; + bool bAlreadyInList = false; + int iMaxDistanceAt=0; + for (int j=0; j<reslist_size; j++) { + if (oFuzzystruct[j].pMatchWord && + strcmp(oFuzzystruct[j].pMatchWord,sCheck)==0 ) {//already in list + bAlreadyInList = true; + break; + } + //find the position,it will certainly be found (include the first time) as iMaxDistance is set by last time. + if (oFuzzystruct[j].iMatchWordDistance == iMaxDistance ) { + iMaxDistanceAt = j; + } + } + if (!bAlreadyInList) { + if (oFuzzystruct[iMaxDistanceAt].pMatchWord) + g_free(oFuzzystruct[iMaxDistanceAt].pMatchWord); + oFuzzystruct[iMaxDistanceAt].pMatchWord = g_strdup(sCheck); + oFuzzystruct[iMaxDistanceAt].iMatchWordDistance = iDistance; + // calc new iMaxDistance + iMaxDistance = iDistance; + for (int j=0; j<reslist_size; j++) { + if (oFuzzystruct[j].iMatchWordDistance > iMaxDistance) + iMaxDistance = oFuzzystruct[j].iMatchWordDistance; + } // calc new iMaxDistance + } // add to list + } // find one + } // each word + } // ok for search + } // each lib + g_free(ucs4_str2); + + if (Found)// sort with distance + std::sort(oFuzzystruct, oFuzzystruct+reslist_size); + + for (gint i=0; i<reslist_size; ++i) + reslist[i]=oFuzzystruct[i].pMatchWord; + + return Found; +} + +inline bool less_for_compare(const char *lh, const char *rh) { + return stardict_strcmp(lh, rh)<0; +} + +gint Libs::LookupWithRule(const gchar *word, gchar **ppMatchWord) +{ + glong aiIndex[MAX_MATCH_ITEM_PER_LIB+1]; + gint iMatchCount = 0; + GPatternSpec *pspec = g_pattern_spec_new(word); + + for (std::vector<Dict *>::size_type iLib=0; iLib<oLib.size(); iLib++) { + //if(oLibs.LookdupWordsWithRule(pspec,aiIndex,MAX_MATCH_ITEM_PER_LIB+1-iMatchCount,iLib)) + // -iMatchCount,so save time,but may got less result and the word may repeat. + + if (oLib[iLib]->LookupWithRule(pspec,aiIndex, MAX_MATCH_ITEM_PER_LIB+1)) { + if (progress_func) + progress_func(); + for (int i=0; aiIndex[i]!=-1; i++) { + const gchar * sMatchWord = poGetWord(aiIndex[i],iLib); + bool bAlreadyInList = false; + for (int j=0; j<iMatchCount; j++) { + if (strcmp(ppMatchWord[j],sMatchWord)==0) {//already in list + bAlreadyInList = true; + break; + } + } + if (!bAlreadyInList) + ppMatchWord[iMatchCount++] = g_strdup(sMatchWord); + } + } + } + g_pattern_spec_free(pspec); + + if (iMatchCount)// sort it. + std::sort(ppMatchWord, ppMatchWord+iMatchCount, less_for_compare); + + return iMatchCount; +} + +bool Libs::LookupData(const gchar *sWord, std::vector<gchar *> *reslist) +{ + std::vector<std::string> SearchWords; + std::string SearchWord; + const char *p=sWord; + while (*p) { + if (*p=='\\') { + p++; + switch (*p) { + case ' ': + SearchWord+=' '; + break; + case '\\': + SearchWord+='\\'; + break; + case 't': + SearchWord+='\t'; + break; + case 'n': + SearchWord+='\n'; + break; + default: + SearchWord+=*p; + } + } else if (*p == ' ') { + if (!SearchWord.empty()) { + SearchWords.push_back(SearchWord); + SearchWord.clear(); + } + } else { + SearchWord+=*p; + } + p++; + } + if (!SearchWord.empty()) { + SearchWords.push_back(SearchWord); + SearchWord.clear(); + } + if (SearchWords.empty()) + return false; + + guint32 max_size =0; + gchar *origin_data = NULL; + for (std::vector<Dict *>::size_type i=0; i<oLib.size(); ++i) { + if (!oLib[i]->containSearchData()) + continue; + if (progress_func) + progress_func(); + const gulong iwords = narticles(i); + const gchar *key; + guint32 offset, size; + for (gulong j=0; j<iwords; ++j) { + oLib[i]->get_key_and_data(j, &key, &offset, &size); + if (size>max_size) { + origin_data = (gchar *)g_realloc(origin_data, size); + max_size = size; + } + if (oLib[i]->SearchData(SearchWords, offset, size, origin_data)) + reslist[i].push_back(g_strdup(key)); + } + } + g_free(origin_data); + + std::vector<Dict *>::size_type i; + for (i=0; i<oLib.size(); ++i) + if (!reslist[i].empty()) + break; + + return i!=oLib.size(); +} + +/**************************************************/ +query_t analyze_query(const char *s, std::string& res) +{ + if (!s || !*s) { + res=""; + return qtSIMPLE; + } + if (*s=='/') { + res=s+1; + return qtFUZZY; + } + + if (*s=='|') { + res=s+1; + return qtDATA; + } + + bool regexp=false; + const char *p=s; + res=""; + for (; *p; res+=*p, ++p) { + if (*p=='\\') { + ++p; + if (!*p) + break; + continue; + } + if (*p=='*' || *p=='?') + regexp=true; + } + if (regexp) + return qtREGEXP; + + return qtSIMPLE; +} diff --git a/src/lib/lib.h b/src/lib/lib.h new file mode 100644 index 0000000..3ba8894 --- /dev/null +++ b/src/lib/lib.h @@ -0,0 +1,161 @@ +#ifndef __SD_LIB_H__ +#define __SD_LIB_H__ + +#include <cstdio> +#include <list> +#include <memory> +#include <string> +#include <vector> + +#include "dictziplib.hpp" + +const int MAX_MATCH_ITEM_PER_LIB=100; +const int MAX_FUZZY_DISTANCE= 3; // at most MAX_FUZZY_DISTANCE-1 differences allowed when find similar words + +struct cacheItem { + guint32 offset; + gchar *data; + //write code here to make it inline + cacheItem() {data= NULL;} + ~cacheItem() {g_free(data);} +}; + +const int WORDDATA_CACHE_NUM = 10; +const int INVALID_INDEX=-100; + +class DictBase { +public: + DictBase(); + ~DictBase(); + gchar * GetWordData(guint32 idxitem_offset, guint32 idxitem_size); + bool containSearchData(); + bool SearchData(std::vector<std::string> &SearchWords, guint32 idxitem_offset, guint32 idxitem_size, gchar *origin_data); +protected: + std::string sametypesequence; + FILE *dictfile; + std::auto_ptr<dictData> dictdzfile; +private: + cacheItem cache[WORDDATA_CACHE_NUM]; + gint cache_cur; +}; + +//this structure contain all information about dictionary +struct DictInfo { + std::string ifo_file_name; + guint32 wordcount; + std::string bookname; + std::string author; + std::string email; + std::string website; + std::string date; + std::string description; + guint32 index_file_size; + std::string sametypesequence; + bool load_from_ifo_file(const std::string& ifofilename, bool istreedict); +}; + +class index_file { +public: + guint32 wordentry_offset; + guint32 wordentry_size; + + virtual ~index_file() {} + virtual bool load(const std::string& url, gulong wc, gulong fsize) = 0; + virtual const gchar *get_key(glong idx) = 0; + virtual void get_data(glong idx) = 0; + virtual const gchar *get_key_and_data(glong idx) = 0; + virtual bool lookup(const char *str, glong &idx) = 0; +}; + +class Dict : public DictBase { +private: + struct DictInfo mDict_info; + std::string ifo_file_name; + gulong wordcount; + std::string bookname; + + std::auto_ptr<index_file> idx_file; + + bool load_ifofile(const std::string& ifofilename, gulong &idxfilesize); +public: + Dict() {} + bool load(const std::string& ifofilename); + struct DictInfo dict_info() { return mDict_info; } + + gulong narticles() { return wordcount; } + const std::string& dict_name() { return bookname; } + const std::string& ifofilename() { return ifo_file_name; } + + const gchar *get_key(glong index) { return idx_file->get_key(index); } + gchar *get_data(glong index) + { + idx_file->get_data(index); + return DictBase::GetWordData(idx_file->wordentry_offset, idx_file->wordentry_size); + } + void get_key_and_data(glong index, const gchar **key, guint32 *offset, guint32 *size) + { + *key = idx_file->get_key_and_data(index); + *offset = idx_file->wordentry_offset; + *size = idx_file->wordentry_size; + } + bool Lookup(const char *str, glong &idx) { return idx_file->lookup(str, idx); } + + bool LookupWithRule(GPatternSpec *pspec, glong *aIndex, int iBuffLen); +}; + +typedef std::list<std::string> strlist_t; + +class Libs { +public: + typedef void (*progress_func_t)(void); + + Libs(progress_func_t f=NULL); + ~Libs(); + struct DictInfo dict_info(int idict) { return oLib[idict]->dict_info();} + void load_dict(const std::string& url); + void load(const strlist_t& dicts_dirs, + const strlist_t& order_list, + const strlist_t& disable_list); + void reload(const strlist_t& dicts_dirs, + const strlist_t& order_list, + const strlist_t& disable_list); + + glong narticles(int idict) { return oLib[idict]->narticles(); } + const std::string& dict_name(int idict) { return oLib[idict]->dict_name(); } + gint ndicts() { return oLib.size(); } + + const gchar * poGetWord(glong iIndex,int iLib) { + return oLib[iLib]->get_key(iIndex); + } + gchar * poGetWordData(glong iIndex,int iLib) { + if (iIndex==INVALID_INDEX) + return NULL; + return oLib[iLib]->get_data(iIndex); + } + const gchar *poGetCurrentWord(glong *iCurrent); + const gchar *poGetNextWord(const gchar *word, glong *iCurrent); + const gchar *poGetPreWord(glong *iCurrent); + bool LookupWord(const gchar* sWord, glong& iWordIndex, int iLib) { + return oLib[iLib]->Lookup(sWord, iWordIndex); + } + bool LookupSimilarWord(const gchar* sWord, glong & iWordIndex, int iLib); + bool SimpleLookupWord(const gchar* sWord, glong & iWordIndex, int iLib); + + + bool LookupWithFuzzy(const gchar *sWord, gchar *reslist[], gint reslist_size); + gint LookupWithRule(const gchar *sWord, gchar *reslist[]); + bool LookupData(const gchar *sWord, std::vector<gchar *> *reslist); +private: + std::vector<Dict *> oLib; // word Libs. + int iMaxFuzzyDistance; + progress_func_t progress_func; +}; + + +typedef enum { + qtSIMPLE, qtREGEXP, qtFUZZY, qtDATA +} query_t; + +extern query_t analyze_query(const char *s, std::string& res); + +#endif//!__SD_LIB_H__ diff --git a/src/lib/mapfile.hpp b/src/lib/mapfile.hpp new file mode 100644 index 0000000..6d237f2 --- /dev/null +++ b/src/lib/mapfile.hpp @@ -0,0 +1,94 @@ +#ifndef _MAPFILE_HPP_ +#define _MAPFILE_HPP_ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#ifdef HAVE_MMAP +# include <sys/types.h> +# include <fcntl.h> +# include <sys/mman.h> +#endif +#ifdef _WIN32 +# include <windows.h> +#endif +#include <glib.h> + +class MapFile { +public: + MapFile(void) : + data(NULL) +#ifdef HAVE_MMAP + mmap_fd(-1) +#elif defined(_WIN32) + hFile(0), + hFileMap(0) +#endif + { + } + ~MapFile(); + bool open(const char *file_name, unsigned long file_size); + inline gchar *begin(void) { return data; } +private: + char *data; + unsigned long size; +#ifdef HAVE_MMAP + int mmap_fd; +#elif defined(_WIN32) + HANDLE hFile; + HANDLE hFileMap; +#endif +}; + +inline bool MapFile::open(const char *file_name, unsigned long file_size) +{ + size=file_size; +#ifdef HAVE_MMAP + if ((mmap_fd = ::open(file_name, O_RDONLY)) < 0) { + //g_print("Open file %s failed!\n",fullfilename); + return false; + } + data = (gchar *)mmap( NULL, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0); + if ((void *)data == (void *)(-1)) { + //g_print("mmap file %s failed!\n",idxfilename); + data=NULL; + return false; + } +#elif defined( _WIN32) + hFile = CreateFile(file_name, GENERIC_READ, 0, NULL, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, 0); + hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, + file_size, NULL); + data = (gchar *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, file_size); +#else + gsize read_len; + if (!g_file_get_contents(file_name, &data, &read_len, NULL)) + return false; + + if (read_len!=file_size) + return false; +#endif + + return true; +} + +inline MapFile::~MapFile() +{ + if (!data) + return; +#ifdef HAVE_MMAP + munmap(data, size); + close(mmap_fd); +#else +# ifdef _WIN32 + UnmapViewOfFile(data); + CloseHandle(hFileMap); + CloseHandle(hFile); +# else + g_free(data); +# endif +#endif +} + +#endif//!_MAPFILE_HPP_ diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..6e6e2d2 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,5 @@ +#include <qtopiaapplication.h> +#include "qdictopia.h" + +QTOPIA_ADD_APPLICATION(QTOPIA_TARGET, QDictOpia) +QTOPIA_MAIN diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp new file mode 100644 index 0000000..1d619d7 --- /dev/null +++ b/src/mainwindow.cpp @@ -0,0 +1,171 @@ +#include <QMessageBox> +#include <QTimer> + +#include "mainwindow.h" + +MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f), mLineEdit(NULL) +{ + if (loadDicts() == false) { + QTimer::singleShot(0, this, SLOT(slotWarning())); + } else { + // Build UI + mLayout = new QGridLayout(this); + + mLineEdit = new QLineEdit(this); + mLineEdit->setFocusPolicy(Qt::NoFocus); + connect(mLineEdit, SIGNAL(textChanged(const QString&)), + this, SLOT(slotTextChanged(const QString&))); + + mMenu = QSoftMenuBar::menuFor(mLineEdit); + mActionClear = mMenu->addAction(tr("Clear text"), this, SLOT(slotClearText())); + mActionClear->setVisible(false); + mActionDList = mMenu->addAction(tr("Dictionaries..."), this, SLOT(slotDictList())); + + mListWidget = new QListWidget(this); + mListWidget->setFocusPolicy(Qt::NoFocus); + connect(mListWidget, SIGNAL(itemActivated(QListWidgetItem*)), + this, SLOT(slotItemActivated(QListWidgetItem*))); + + mLayout->addWidget(mLineEdit, 0, 0); + mLayout->addWidget(mListWidget, 1, 0); + } +} + +MainWindow::~MainWindow() +{ + if (mLibs) + delete mLibs; +} + +void MainWindow::keyPressEvent(QKeyEvent* event) +{ + switch(event->key()) + { + case Qt::Key_Up: + if (mListWidget->count() > 0) + { + if (mListWidget->currentRow() <= 0) + mListWidget->setCurrentRow(mListWidget->count() - 1); + else + mListWidget->setCurrentRow(mListWidget->currentRow() - 1); + } + break; + + case Qt::Key_Down: + + if (mListWidget->count() > 0) + { + if (mListWidget->currentRow() < (mListWidget->count() - 1)) + mListWidget->setCurrentRow(mListWidget->currentRow() + 1); + else + mListWidget->setCurrentRow(0); + } + break; + + case Qt::Key_Select: + QString word; + + if (mListWidget->currentRow() >= 0) + word = mListWidget->item(mListWidget->currentRow())->text(); + else + word = mLineEdit->text(); + + mWordBrowser = new WordBrowser(this, Qt::Popup); + mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); + mWordBrowser->showMaximized(); + mWordBrowser->lookup(word, mLibs); + + break; + } + + QWidget::keyPressEvent(event); +} + +bool MainWindow::slotTextChanged(const QString& text) +{ + glong* index = (glong*)malloc(sizeof(glong) * mLibs->ndicts()); + const gchar* word; + bool bfound = false; + + if (text.isEmpty() && mActionClear->isVisible()) + mActionClear->setVisible(false); + else if (!text.isEmpty() && !mActionClear->isVisible()) + mActionClear->setVisible(true); + + for (int i = 0; i < mLibs->ndicts(); i++) + if (mLibs->LookupWord((const gchar*)text.toLatin1().data(), index[i], i)) + bfound = true; + + for (int i = 0; i < mLibs->ndicts(); i++) + if (mLibs->LookupSimilarWord((const gchar*)text.toLatin1().data(), index[i], i)) + bfound = true; + + if (bfound) + { + mListWidget->clear(); + + word = mLibs->poGetCurrentWord(index); + mListWidget->addItem(tr((const char*)word)); + + for (int j = 0; j < MAX_FUZZY; j++) + { + if ((word = mLibs->poGetNextWord(NULL, index))) + mListWidget->addItem(tr((const char*)word)); + else + break; + } + } + + free(index); + return true; +} + +void MainWindow::paintEvent(QPaintEvent* event) +{ + if (mLineEdit) + mLineEdit->setEditFocus(true); + + QWidget::paintEvent(event); +} + +void MainWindow::slotItemActivated(QListWidgetItem* item) +{ + QString word = item->text(); + + mWordBrowser = new WordBrowser(this, Qt::Popup); + mWordBrowser->setAttribute(Qt::WA_DeleteOnClose); + mWordBrowser->showMaximized(); + mWordBrowser->lookup(word, mLibs); +} + +void MainWindow::slotClearText() +{ + mLineEdit->clear(); +} + +void MainWindow::slotDictList() +{ + mDictBrowser= new DictBrowser(this, Qt::Popup, mLibs); + mDictBrowser->setAttribute(Qt::WA_DeleteOnClose); + mDictBrowser->showMaximized(); +} + +void MainWindow::slotWarning() +{ + QMessageBox::warning(this, tr("Dictionary"), tr("There are no dictionary loaded!")); +} + +bool MainWindow::loadDicts() +{ + mLibs = new Libs(); + + // Retrieve all dict infors + mDictDir = QDir(DIC_PATH, "*.ifo"); + for (unsigned int i = 0; i < mDictDir.count(); i++) + mLibs->load_dict(mDictDir.absoluteFilePath(mDictDir[i]).toLatin1().data()); + + if (mLibs->ndicts() == 0) + return false; + else + return true; +} diff --git a/src/mainwindow.h b/src/mainwindow.h new file mode 100644 index 0000000..4d07093 --- /dev/null +++ b/src/mainwindow.h @@ -0,0 +1,57 @@ +#ifndef MAIN_WINDOW_H +#define MAIN_WINDOW_H + +#include <QWidget> +#include <QGridLayout> +#include <QLineEdit> +#include <QListWidget> +#include <QDir> +#include <QKeyEvent> +#include <QSoftMenuBar> +#include <QMenu> +#include <QAction> + +#include "lib/lib.h" +#include "wordbrowser.h" +#include "dictbrowser.h" + +#define MAX_FUZZY 30 +#define DIC_PATH "/usr/share/stardict/dic/" + +class MainWindow : public QWidget +{ + Q_OBJECT + +public: + MainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); + ~MainWindow(); + +protected: + void keyPressEvent(QKeyEvent* event); + void paintEvent(QPaintEvent* event); + +private: + bool loadDicts(); + +private slots: + bool slotTextChanged(const QString& text); + void slotItemActivated(QListWidgetItem* item); + void slotClearText(); + void slotDictList(); + void slotWarning(); + +private: + QGridLayout* mLayout; + QLineEdit* mLineEdit; + QListWidget* mListWidget; + WordBrowser* mWordBrowser; + DictBrowser* mDictBrowser; + QMenu* mMenu; + QAction* mActionClear; + QAction* mActionDList; + + Libs* mLibs; + QDir mDictDir; +}; + +#endif diff --git a/src/qdictopia.cpp b/src/qdictopia.cpp new file mode 100644 index 0000000..ee9aacd --- /dev/null +++ b/src/qdictopia.cpp @@ -0,0 +1,9 @@ +#include "qdictopia.h" + +QDictOpia::QDictOpia(QWidget* parent, Qt::WindowFlags flags) : QMainWindow(parent, flags) +{ + setWindowTitle(tr("QDictopia")); + + mMainWindow = new MainWindow(this); + setCentralWidget(mMainWindow); +} diff --git a/src/qdictopia.h b/src/qdictopia.h new file mode 100644 index 0000000..7a1a7ed --- /dev/null +++ b/src/qdictopia.h @@ -0,0 +1,17 @@ +#ifndef _QDICTOPIA_H_ +#define _QDICTOPIA_H_ + +#include <QMainWindow> + +#include "mainwindow.h" + +class QDictOpia : public QMainWindow +{ +public: + QDictOpia(QWidget* parent = 0, Qt::WindowFlags flags = 0); + +private: + MainWindow* mMainWindow; +}; + +#endif diff --git a/src/wordbrowser.cpp b/src/wordbrowser.cpp new file mode 100644 index 0000000..f3a8422 --- /dev/null +++ b/src/wordbrowser.cpp @@ -0,0 +1,186 @@ +#include <QTextCodec> +#include "wordbrowser.h" + +WordBrowser::WordBrowser(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) +{ + mLayout = new QGridLayout(this); + + mTextEdit = new QTextEdit(this); + mTextEdit->setFocusPolicy(Qt::NoFocus); + mTextEdit->setReadOnly(true); + + mLayout->addWidget(mTextEdit, 0, 0); +} + +bool WordBrowser::lookup(QString& word, Libs* lib) +{ + glong index; + QString translation; + + for (int i = 0; i < lib->ndicts(); i++) + { + if (lib->LookupWord((gchar*)(word.toLatin1().data()), index, i)) + { + QString result = QString((char*)lib->poGetWord(index, i)); + + if (result == word) + { + const char* utf8_cstr; + QString uni_str; + QTextCodec* codec = QTextCodec::codecForName("UTF-8"); + + translation.append("<---"); + utf8_cstr = lib->dict_name(i).data(); + uni_str = codec->toUnicode(utf8_cstr); + translation.append(uni_str); + translation.append("--->"); + + utf8_cstr = (parse_data(lib->poGetWordData(index, i))).data(); + uni_str = codec->toUnicode(utf8_cstr); + translation.append(uni_str); + translation.append(tr("\n\n")); + } + } + } + + if (translation.isEmpty()) + translation = QString("Not found!"); + + mTextEdit->setText(translation); + + return true; +} + +std::string WordBrowser::xdxf2text(const char* p) +{ + std::string res; + for (; *p; ++p) { + if (*p!='<') { + if (g_str_has_prefix(p, "&gt;")) { + res+=">"; + p+=3; + } else if (g_str_has_prefix(p, "&lt;")) { + res+="<"; + p+=3; + } else if (g_str_has_prefix(p, "&amp;")) { + res+="&"; + p+=4; + } else if (g_str_has_prefix(p, "&quot;")) { + res+="\""; + p+=5; + } else + res+=*p; + continue; + } + + const char *next=strchr(p, '>'); + if (!next) + continue; + + std::string name(p+1, next-p-1); + + if (name=="abr") + res+=""; + else if (name=="/abr") + res+=""; + else if (name=="k") { + const char *begin=next; + if ((next=strstr(begin, "</k>"))!=NULL) + next+=sizeof("</k>")-1-1; + else + next=begin; + } else if (name=="b") + res+=""; + else if (name=="/b") + res+=""; + else if (name=="i") + res+=""; + else if (name=="/i") + res+=""; + else if (name=="tr") + res+="["; + else if (name=="/tr") + res+="]"; + else if (name=="ex") + res+=""; + else if (name=="/ex") + res+=""; + else if (!name.empty() && name[0]=='c' && name!="co") { + std::string::size_type pos=name.find("code"); + if (pos!=std::string::size_type(-1)) { + pos+=sizeof("code=\"")-1; + std::string::size_type end_pos=name.find("\""); + std::string color(name, pos, end_pos-pos); + res+=""; + } else { + res+=""; + } + } else if (name=="/c") + res+=""; + + p=next; + } + return res; +} + +std::string WordBrowser::parse_data(const gchar* data) +{ + if (!data) + return ""; + + std::string res; + guint32 data_size, sec_size=0; + gchar *m_str; + const gchar *p=data; + data_size=*((guint32 *)p); + p+=sizeof(guint32); + while (guint32(p - data)<data_size) { + switch (*p++) { + case 'm': + case 'l': //need more work... + case 'g': + sec_size = strlen(p); + if (sec_size) { + res+="\n"; + m_str = g_strndup(p, sec_size); + res += m_str; + g_free(m_str); + } + sec_size++; + break; + case 'x': + sec_size = strlen(p); + if (sec_size) { + res+="\n"; + m_str = g_strndup(p, sec_size); + res += xdxf2text(m_str); + g_free(m_str); + } + sec_size++; + break; + case 't': + sec_size = strlen(p); + if(sec_size){ + res+="\n"; + m_str = g_strndup(p, sec_size); + res += "["+std::string(m_str)+"]"; + g_free(m_str); + } + sec_size++; + break; + case 'y': + sec_size = strlen(p); + sec_size++; + break; + case 'W': + case 'P': + sec_size=*((guint32 *)p); + sec_size+=sizeof(guint32); + break; + } + p += sec_size; + } + + + return res; +} diff --git a/src/wordbrowser.h b/src/wordbrowser.h new file mode 100644 index 0000000..4005510 --- /dev/null +++ b/src/wordbrowser.h @@ -0,0 +1,27 @@ +#ifndef WORD_BROWSER_H +#define WORD_BROWSER_H + +#include <string> + +#include <QWidget> +#include <QTextEdit> +#include <QGridLayout> + +#include "lib/lib.h" + +class WordBrowser : public QWidget +{ +public: + WordBrowser(QWidget* parent = 0, Qt::WindowFlags f = 0); + bool lookup(QString& word, Libs* lib); + +private: + std::string parse_data(const gchar* data); + std::string xdxf2text(const char* p); + +private: + QGridLayout* mLayout; + QTextEdit* mTextEdit; +}; + +#endif
axelGschaider/PimpedScalaTable
abb586a41dc10626b7410f8cbb709eb4850cf4db
fixed a column computation gug and added some paint magic to example
diff --git a/PimpedTable.scala b/PimpedTable.scala index 626a853..9480ffa 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,537 +1,583 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable -import javax.swing.table.TableCellEditor +import javax.swing.JButton +import javax.swing.table.{TableCellRenderer, TableCellEditor} import javax.swing.AbstractCellEditor import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.RowSorter.SortKey import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter, ActionListener,ActionEvent} import java.util.EventObject import java.util.Comparator import java.awt.Color import scala.annotation.unchecked.uncheckedVariance trait ColumnValue[-A] { val father:Row[_ >: A] } trait Row[+A] { val data:A } case class DeadTree[A](data:A) extends Row[A] case class LivingTree[A](data:A, leafData:List[A], internal:Option[Comparator[Leaf[A]]], var expanded:Boolean = false) extends Row[A] { var leaves:List[Leaf[A]] = leafData.map(x => Leaf(x, this)) } case class Leaf[A](data:A, father:LivingTree[A]) extends Row[A] trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean def refresh():Unit } trait ComparatorRelais[+B] extends java.util.Comparator[B @uncheckedVariance] case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 //println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { //println("Margin changed") takeNewData = true } if(takeNewData) { //println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } sealed trait PimpedRenderer case class LeaveMeAloneRenderer(c:Component) extends PimpedRenderer case class SetMyBackgroundRenderer(c:Component, setBackground:(Color=>Unit), setForeground:(Color=>Unit) = (_ => {})) extends PimpedRenderer trait ColumnDescription[-A, +B] { val name:String def extractValue(x:Row[A]):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:Row[A], isSelected: Boolean, focused: Boolean):PimpedRenderer def comparator: Option[ComparatorRelais[B]] //def comparator: /*Option[Comparator[ColumnValue[_ <: A]]]*/Option[Comparator[_ <: B]] } /*class ExtractorRelais[A,B](descr:ColumnDescription[A,B]) { def ex(x:Row[A]):ColumnValue[B] = descr extractValue x }*/ class PimpedTableModel[A,B <: ColumnValue[A] ](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { //data(row).isExpandable.asInstanceOf[java.lang.Object] data(row) match { case LivingTree(_,_,_,_) => true.asInstanceOf[java.lang.Object] case _ => false.asInstanceOf[java.lang.Object] } } else { (columns(column - expOffset) extractValue data(row)/*.data*/).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class PimpedColumnComparator[A,B <: ColumnValue[A]](comp:Comparator[B], col:ColumnDescription[A,B], colIndex:Int, mother:SortInfo) extends Comparator[B] { override def compare(o1:B, o2:B):Int = internalCompare(o1,o2) match { case Some(i) => i case None => comp.compare(o1, o2) } private def internalCompare(v1:B, v2:B):Option[Int] = (v1.father, v2.father) match { case(t:LivingTree[A], l:Leaf[A]) => Some(handleLivingtree(t,l)) case(l:Leaf[A], t:LivingTree[A]) => Some(handleLivingtree(t,l) * (-1)) case(d:DeadTree[A], l:Leaf[A]) => Some(comp.compare(v1, col extractValue l.father)) case(l:Leaf[A], d:DeadTree[A]) => Some(comp.compare(col extractValue l.father, v2)) case(l1:Leaf[A], l2:Leaf[A]) => Some(handleTwoLeaves(l1,l2)) case(_,_) => None } private def handleTwoLeaves(l1:Leaf[A], l2:Leaf[A]):Int = (l1.father, l2.father) match { case (f1, f2) if f1 == f2 => f1.internal match { case None => comp.compare(col extractValue l1, col extractValue l2) case Some(c) => mother.getSortOrder match { case Descending => c.compare(l1, l2) * (-1) case _ => c.compare(l1, l2) } } case (f1,f2) => comp.compare(col extractValue f1, col extractValue f2) } private def handleLivingtree(t:LivingTree[A], l:Leaf[A]):Int = (t, l.father) match { case (t1, t2) if t1 == t2 => over case (t1, t2) => comp.compare(col extractValue t1, col extractValue t2) } private def over = mother.getSortOrder match { case Descending => 1 case _ => -1 } } sealed trait SortOrder case object Ascending extends SortOrder case object Descending extends SortOrder case object NoSort extends SortOrder class SortInfo(sorter:TableRowSorter[_], val column:Int ) { def getSortOrder():SortOrder = { val i = sorter.getSortKeys().iterator var ret:SortOrder = NoSort while(i.hasNext) { val key = i.next if(key.getColumn == column) { val ord = key.getSortOrder if(ord == javax.swing.SortOrder.ASCENDING) ret = Ascending else if(ord == javax.swing.SortOrder.DESCENDING) ret = Descending } } ret } } class ConvenientPimpedTable[A, B <: ColumnValue[A]](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B <: ColumnValue[A]](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient with ExpansionColumnEditorProvider { - - private var groupBackground:Color = Color.LIGHT_GRAY - private var groupForeground:Color = Color.BLACK - private var expansionRowBackground:Color = Color.WHITE + + var groupBackground:Color = Color.LIGHT_GRAY + var groupBackgroundSelected = selectionBackground.darker//groupBackground.darker + var groupForeground:Color = Color.BLACK + var groupForegroundSelected = selectionBackground.darker//groupForeground.darker + var groupFatherBackground:Color = Color.GRAY + var groupFatherBackgroundSelected = selectionBackground.darker.darker//groupFatherBackground.darker + var groupFatherForeground:Color = Color.BLACK + var groupFatherForegroundSelected = selectionForeground.darker.darker//groupFatherForeground.darker + var expansionRowBackground:Color = Color.WHITE private var fallbackDat = initData private var filteredDat = fallbackDat private val expansionButtons:scala.collection.mutable.HashMap[Int, LivingTreeButton] = scala.collection.mutable.HashMap.empty[Int, LivingTreeButton] private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() sorter.setSortsOnUpdates(true) this.peer.setRowSorter(sorter) private def refreshExpansionButtons = { expansionButtons.clear filteredData.zipWithIndex.foreach(x => x match { case (l@LivingTree(_,_,_,_), i) => expansionButtons += ((i,new LivingTreeButton(l, this))) case (_,_) => {} }) } private def fillSorter = { val offset = if(paintExpandColumn) { sorter.setSortable(0, false) 1 } else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => sorter.setSortable(i, true) case Some(c) => { sorter.setComparator(i+offset, new PimpedColumnComparator[A,B](c, colDes, i+offset, new SortInfo(sorter, i+offset))) sorter.setSortable(i,true) } } } } } columns.zipWithIndex foreach { x => x match { case (colDes,i) => if (!colDes.isSortable) sorter.setSortable(i, false) } } } def refresh() = { data = data } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } private def expandData(l:List[Row[A]]):List[Row[A]] = l match { case List() => List.empty[Row[A]] case _ => l.head match { case a@LivingTree(_,_,_,true) => (l.head +: a.leaves) ++ expandData(l.tail) case _ => l.head +: expandData(l.tail) } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() var sortkeys = sorter.getSortKeys blockSelectionEvents = true filteredDat = expandData(d) refreshExpansionButtons tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter //sorter.sort() if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } sorter setSortKeys sortkeys if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 - col setCellEditor new ExpansionCellEditor(this) + //col setCellEditor new ExpansionCellEditor(this) + val gaga = new ExpansionColumnWorker() + col setCellRenderer gaga + col setCellEditor gaga } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) - private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) + private def convertedColumn(column:Int) = { + if(paintExpandColumn) { + this.peer.convertColumnIndexToModel(column)-1 + } + else { + this.peer.convertColumnIndexToModel(column) + } + } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { - val columnOffset = if (paintExpandColumn) 1 else 0 + //val columnOffset = if (paintExpandColumn) 1 else 0 if(paintExpandColumn && column == 0) { //TODO filteredData(convertedRow(row)) match { - case Leaf(_,_) => new Label(){ - opaque = true - if (isSelected) background = selectionBackground - else background = expansionRowBackground - } - case DeadTree(_) => new Label(){background = expansionRowBackground} case lt@LivingTree(_,_,_,_) => { expansionButtons.get(convertedRow(row)) match { case Some(b) => b case None => new Label() } } + case _ => new Label(){ + opaque = true + if (isSelected) background = selectionBackground + else background = expansionRowBackground + } } } else { - val colDescr = columns(convertedColumn(column-columnOffset)) + //println("gagagaga: " + column + " - " + columnOffset + " -> " + convertedColumn(column-columnOffset)) + //convertedColumn(column-columnOffset) + val colDescr = columns(convertedColumn(column)) val data = filteredData(convertedRow(row)) data match { case Leaf(_,_) if colDescr.ignoreWhileExpanding => { new Label() { - if(colDescr.paintGroupColourWhileExpanding) { + if(isSelected && colDescr.paintGroupColourWhileExpanding) { + background = groupBackgroundSelected + } + else { + if(colDescr.paintGroupColourWhileExpanding) { background = groupBackground opaque = true } + if(isSelected) { + background = selectionBackground + opaque = true + } + + } } } - case _ => columns(convertedColumn(column-columnOffset)).renderComponent(data, isSelected, focused) match { + case _ => columns(convertedColumn(column)).renderComponent(data, isSelected, focused) match { case LeaveMeAloneRenderer(r) => r case SetMyBackgroundRenderer(r, b, f) => { - if(isSelected) { - b(selectionBackground) - f(selectionForeground) - } else { - data match { - case t@LivingTree(_,_,_,_) if(t.expanded) => { - b(groupBackground) - f(groupForeground) + //b(selectionBackground) + //f(selectionForeground) + data match { + case t@LivingTree(_,_,_,_) if(t.expanded) => { + if(isSelected) { + b(groupFatherBackgroundSelected) + f(groupFatherForegroundSelected) + } + else { + b(groupFatherBackground) + f(groupFatherForeground) } - case t@Leaf(_,_) if(colDescr.paintGroupColourWhileExpanding) => { - b(groupBackground) + } + case t@Leaf(_,_) if(colDescr.paintGroupColourWhileExpanding) => { + if(isSelected) { + b(groupBackgroundSelected) + f(groupForegroundSelected) + } else { + b(groupBackground) f(groupForeground) } - case _ => {} + } + case _ => if (isSelected) { + b(selectionBackground) + f(selectionForeground) } } + r } } } } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) def gimmeEditor(row:Int):java.awt.Component = expansionButtons.get(row) match { case Some(e) => { println("return editor for " + row) e.peer } case None => { println("da ist was faul im Staate Denver") new Label().peer } } - //peer.isCellEditable(true) - - /*def getTableCellEditorComponent(table:JTable, value:Object, isSelected:Boolean, row:Int, column:Int):java.awt.Component = expansionButtons.get(row) match { - case Some(e) => { - println("return editor for " + row) - e.peer - } - case None => { - println("da ist was faul im Staate Denver") - new Label().peer - } - } - - def removeCellEditorListener(l:javax.swing.event.CellEditorListener):Unit = {} - def addCellEditorListener(l:javax.swing.event.CellEditorListener):Unit = {} - def cancelCellEditing():Unit = {} - def stopCellEditing():Boolean = true - def shouldSelectCell(e:java.util.EventObject):Boolean = true - def isCellEditable(e:java.util.EventObject):Boolean = true - def getCellEditorValue():Object = null*/ - - fallbackData = initData } class LivingTreeButton(lt:LivingTree[_], client:TableBehaviourClient) extends Button(){ action = Action("xx") { println("gaga") lt.expanded = !lt.expanded client.refresh } //println("Gottverdammt") } class ExpansionCellEditor(provider:ExpansionColumnEditorProvider) extends AbstractCellEditor with TableCellEditor{ def getTableCellEditorComponent(table:JTable, value:Object, isSelected:Boolean, row:Int, column:Int) = provider gimmeEditor row - def getCellEditorValue():java.lang.Object = null + def getCellEditorValue():java.lang.Object = { + println("da will wer Daten") + null + } } trait ExpansionColumnEditorProvider { def gimmeEditor(row:Int):java.awt.Component } +class ExpansionColumnWorker() extends AbstractCellEditor with TableCellRenderer with TableCellEditor with ActionListener { + + def getTableCellRendererComponent(table:JTable, value:Object, isSelected:Boolean, hasFocus:Boolean, row:Int, column:Int):java.awt.Component = { + val a = new JButton("oo") + println("give render button") + a + } + + def getTableCellEditorComponent(table:JTable, value:Object, isSelected:Boolean, row:Int, column:Int):java.awt.Component = { + val a = new JButton("uu") + a.setFocusPainted(false) + println("give cell button") + a.addActionListener(this) + a + } + + def getCellEditorValue():Object = "oo" + + def actionPerformed(e:ActionEvent):Unit = { + fireEditingStopped() + println("bin da") + } + +} + diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 7b123fe..e7b0805 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,219 +1,253 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator +import java.awt.Graphics2D case class Data(i:Int, s:String) sealed trait Value extends ColumnValue[Data] case class IntValue(i:Int, father:Row[Data]) extends Value case class StringValue(s:String, father:Row[Data]) extends Value /*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } }*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true def renderComponent(data:Row[Data], isSelected: Boolean, focused: Boolean):PimpedRenderer = { val l = new Label(extractValue(data) match { case StringValue(s,_) => s case IntValue(i,_) => i.toString - }) + }) { + override def paint(g: Graphics2D) { + super.paint(g) + + val c = g.getColor + + val height = this.size.getHeight.toInt + val width = this.size.getWidth.toInt + + extractValue(data) match { + case StringValue(_,_) => { + g setColor Color.GREEN + /*val xPoints = new java.util.ArrayList[Int] + val yPoints = new java.util.ArrayList[Int] + + xPoints add width + yPoints add height + + xPoints add width + yPoints add (height - 10) + + xPoints add (width - 10) + yPoints add height + + g.fillPolygon(xPoints.toArray[Int], yPoints.toArray, 3)*/ + + g.fillPolygon(Array(width, width, width-10), Array(height, height-10, height), 3) + } + case _ => {} + } + + g setColor c + } + } SetMyBackgroundRenderer(l, (x => { l.opaque = true l.background = x })) } } case class StringColumn(name:String) extends MyColumns[StringValue] { //override val isSortable = false def extractValue(x:Row[Data]) = StringValue(x.data.s, x) override val paintGroupColourWhileExpanding = true def comparator = Some(new ComparatorRelais[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1,_), StringValue(s2,_)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Row[Data]) = IntValue(x.data.i, x) override val ignoreWhileExpanding = true def comparator = Some(new ComparatorRelais[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1,_), IntValue(i2,_)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object InternalIntColumnComparator extends Comparator[Leaf[Data]] { def compare(d1:Leaf[Data], d2:Leaf[Data]):Int = (d1.data, d2.data) match { case(Data(i1,_),Data(i2,_)) if i1 == i2 => 0 case(Data(i1,_),Data(i2,_)) if i1 > i2 => 1 case _ => -1 } } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 val lt1 = LivingTree(Data(101, "201xxx") , (0 to 9).toList.map(y => Data(y+1, "201xxx"+y.toString)) , Some(InternalIntColumnComparator) , true ) val lt2 = LivingTree(Data(102, "202xxx") , (0 to 9).toList.map(y => Data(y+1, "202xxx"+y.toString)) , None , true ) val data:List[Row[Data]] = (0 to 100).toList.filter(_%3 == 0).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 1).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 2).map(x => (LivingTree((Data(x, (100-x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(x, (100-x).toString + "xxx" + y.toString)) ,None ,false)) ) ++ List(lt1, lt2) /*++ (101 to 102).toList.map(x => (LivingTree((Data(x, (100+x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(y+1, (100+x).toString + "xxx" + y.toString)) ,None ,true)) ) */ /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) }) */ val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN paintExpandColumn = true } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { //println("Test:") //table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ lt2.expanded = !lt2.expanded table.refresh /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { //println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") /*table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) })*/ } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
ed3fd3405162f5a89950505be58bf52b9c667ce0
moved selection and expansion rendering into PimpedTable
diff --git a/PimpedTable.scala b/PimpedTable.scala index dad1d05..626a853 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,440 +1,537 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable +import javax.swing.table.TableCellEditor +import javax.swing.AbstractCellEditor import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.RowSorter.SortKey import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} -import java.awt.event.{MouseEvent, MouseAdapter} +import java.awt.event.{MouseEvent, MouseAdapter, ActionListener,ActionEvent} import java.util.EventObject import java.util.Comparator import java.awt.Color import scala.annotation.unchecked.uncheckedVariance -/*trait Row[A] { - val data:A - val isExpandable:Boolean = false - def expandedData():List[A] = List.empty[A] - var expanded:Boolean = false - //val internalComparator:Option[Comparator[A]] = None -}*/ - trait ColumnValue[-A] { val father:Row[_ >: A] } trait Row[+A] { val data:A } case class DeadTree[A](data:A) extends Row[A] case class LivingTree[A](data:A, leafData:List[A], internal:Option[Comparator[Leaf[A]]], var expanded:Boolean = false) extends Row[A] { var leaves:List[Leaf[A]] = leafData.map(x => Leaf(x, this)) } case class Leaf[A](data:A, father:LivingTree[A]) extends Row[A] trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean + def refresh():Unit } trait ComparatorRelais[+B] extends java.util.Comparator[B @uncheckedVariance] case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} + + override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 - println("fixed it") + //println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { - println("Margin changed") + //println("Margin changed") takeNewData = true } if(takeNewData) { - println("take new data") + //println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } +sealed trait PimpedRenderer +case class LeaveMeAloneRenderer(c:Component) extends PimpedRenderer +case class SetMyBackgroundRenderer(c:Component, setBackground:(Color=>Unit), setForeground:(Color=>Unit) = (_ => {})) extends PimpedRenderer trait ColumnDescription[-A, +B] { val name:String def extractValue(x:Row[A]):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false - def renderComponent(data:Row[A], isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component + def renderComponent(data:Row[A], isSelected: Boolean, focused: Boolean):PimpedRenderer def comparator: Option[ComparatorRelais[B]] //def comparator: /*Option[Comparator[ColumnValue[_ <: A]]]*/Option[Comparator[_ <: B]] } /*class ExtractorRelais[A,B](descr:ColumnDescription[A,B]) { def ex(x:Row[A]):ColumnValue[B] = descr extractValue x }*/ class PimpedTableModel[A,B <: ColumnValue[A] ](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { //data(row).isExpandable.asInstanceOf[java.lang.Object] data(row) match { case LivingTree(_,_,_,_) => true.asInstanceOf[java.lang.Object] case _ => false.asInstanceOf[java.lang.Object] } } else { (columns(column - expOffset) extractValue data(row)/*.data*/).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class PimpedColumnComparator[A,B <: ColumnValue[A]](comp:Comparator[B], col:ColumnDescription[A,B], colIndex:Int, mother:SortInfo) extends Comparator[B] { override def compare(o1:B, o2:B):Int = internalCompare(o1,o2) match { case Some(i) => i case None => comp.compare(o1, o2) } private def internalCompare(v1:B, v2:B):Option[Int] = (v1.father, v2.father) match { case(t:LivingTree[A], l:Leaf[A]) => Some(handleLivingtree(t,l)) case(l:Leaf[A], t:LivingTree[A]) => Some(handleLivingtree(t,l) * (-1)) case(d:DeadTree[A], l:Leaf[A]) => Some(comp.compare(v1, col extractValue l.father)) case(l:Leaf[A], d:DeadTree[A]) => Some(comp.compare(col extractValue l.father, v2)) case(l1:Leaf[A], l2:Leaf[A]) => Some(handleTwoLeaves(l1,l2)) case(_,_) => None } private def handleTwoLeaves(l1:Leaf[A], l2:Leaf[A]):Int = (l1.father, l2.father) match { case (f1, f2) if f1 == f2 => f1.internal match { case None => comp.compare(col extractValue l1, col extractValue l2) case Some(c) => mother.getSortOrder match { case Descending => c.compare(l1, l2) * (-1) case _ => c.compare(l1, l2) } } case (f1,f2) => comp.compare(col extractValue f1, col extractValue f2) } private def handleLivingtree(t:LivingTree[A], l:Leaf[A]):Int = (t, l.father) match { case (t1, t2) if t1 == t2 => over case (t1, t2) => comp.compare(col extractValue t1, col extractValue t2) } private def over = mother.getSortOrder match { case Descending => 1 case _ => -1 } } sealed trait SortOrder case object Ascending extends SortOrder case object Descending extends SortOrder case object NoSort extends SortOrder class SortInfo(sorter:TableRowSorter[_], val column:Int ) { def getSortOrder():SortOrder = { val i = sorter.getSortKeys().iterator var ret:SortOrder = NoSort while(i.hasNext) { val key = i.next if(key.getColumn == column) { val ord = key.getSortOrder if(ord == javax.swing.SortOrder.ASCENDING) ret = Ascending else if(ord == javax.swing.SortOrder.DESCENDING) ret = Descending } } ret } } + class ConvenientPimpedTable[A, B <: ColumnValue[A]](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) -class PimpedTable[A, B <: ColumnValue[A]](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { +class PimpedTable[A, B <: ColumnValue[A]](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient with ExpansionColumnEditorProvider { + private var groupBackground:Color = Color.LIGHT_GRAY + private var groupForeground:Color = Color.BLACK + private var expansionRowBackground:Color = Color.WHITE private var fallbackDat = initData private var filteredDat = fallbackDat - + private val expansionButtons:scala.collection.mutable.HashMap[Int, LivingTreeButton] = scala.collection.mutable.HashMap.empty[Int, LivingTreeButton] + private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() sorter.setSortsOnUpdates(true) this.peer.setRowSorter(sorter) + private def refreshExpansionButtons = { + expansionButtons.clear + + filteredData.zipWithIndex.foreach(x => x match { + case (l@LivingTree(_,_,_,_), i) => expansionButtons += ((i,new LivingTreeButton(l, this))) + case (_,_) => {} + }) + + } + private def fillSorter = { val offset = if(paintExpandColumn) { sorter.setSortable(0, false) 1 } else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => sorter.setSortable(i, true) case Some(c) => { sorter.setComparator(i+offset, new PimpedColumnComparator[A,B](c, colDes, i+offset, new SortInfo(sorter, i+offset))) sorter.setSortable(i,true) } } } } } columns.zipWithIndex foreach { x => x match { case (colDes,i) => if (!colDes.isSortable) sorter.setSortable(i, false) } } } def refresh() = { data = data } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } private def expandData(l:List[Row[A]]):List[Row[A]] = l match { case List() => List.empty[Row[A]] case _ => l.head match { case a@LivingTree(_,_,_,true) => (l.head +: a.leaves) ++ expandData(l.tail) case _ => l.head +: expandData(l.tail) } } - + def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() var sortkeys = sorter.getSortKeys blockSelectionEvents = true filteredDat = expandData(d) + refreshExpansionButtons tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter //sorter.sort() if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } sorter setSortKeys sortkeys if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 + col setCellEditor new ExpansionCellEditor(this) } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { - if(paintExpandColumn) { - if(column == 0) { - //TODO - new Label() { + val columnOffset = if (paintExpandColumn) 1 else 0 + + if(paintExpandColumn && column == 0) { + //TODO + filteredData(convertedRow(row)) match { + case Leaf(_,_) => new Label(){ opaque = true - filteredData(convertedRow(row)) match { - case DeadTree(_) => background = Color.BLACK//RED - case LivingTree(_,_,_,_) => background = Color.GREEN - case Leaf(_,_) => background = Color.WHITE - } - if(isSelected) { - background = Color.BLUE + if (isSelected) background = selectionBackground + else background = expansionRowBackground + } + case DeadTree(_) => new Label(){background = expansionRowBackground} + case lt@LivingTree(_,_,_,_) => { + expansionButtons.get(convertedRow(row)) match { + case Some(b) => b + case None => new Label() } } } - else { - val c = convertedColumn(column)-1 - if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) - else {/*println("Föhlah: " + c); */new Label("")} - } } else { - columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) + val colDescr = columns(convertedColumn(column-columnOffset)) + val data = filteredData(convertedRow(row)) + data match { + case Leaf(_,_) if colDescr.ignoreWhileExpanding => { + new Label() { + if(colDescr.paintGroupColourWhileExpanding) { + background = groupBackground + opaque = true + } + } + } + case _ => columns(convertedColumn(column-columnOffset)).renderComponent(data, isSelected, focused) match { + case LeaveMeAloneRenderer(r) => r + case SetMyBackgroundRenderer(r, b, f) => { + if(isSelected) { + b(selectionBackground) + f(selectionForeground) + } else { + data match { + case t@LivingTree(_,_,_,_) if(t.expanded) => { + b(groupBackground) + f(groupForeground) + } + case t@Leaf(_,_) if(colDescr.paintGroupColourWhileExpanding) => { + b(groupBackground) + f(groupForeground) + } + case _ => {} + } + } + r + } + } + } } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) + def gimmeEditor(row:Int):java.awt.Component = expansionButtons.get(row) match { + case Some(e) => { + println("return editor for " + row) + e.peer + } + case None => { + println("da ist was faul im Staate Denver") + new Label().peer + } + } + + //peer.isCellEditable(true) + /*def getTableCellEditorComponent(table:JTable, value:Object, isSelected:Boolean, row:Int, column:Int):java.awt.Component = expansionButtons.get(row) match { + case Some(e) => { + println("return editor for " + row) + e.peer + } + case None => { + println("da ist was faul im Staate Denver") + new Label().peer + } + } + + def removeCellEditorListener(l:javax.swing.event.CellEditorListener):Unit = {} + def addCellEditorListener(l:javax.swing.event.CellEditorListener):Unit = {} + def cancelCellEditing():Unit = {} + def stopCellEditing():Boolean = true + def shouldSelectCell(e:java.util.EventObject):Boolean = true + def isCellEditable(e:java.util.EventObject):Boolean = true + def getCellEditorValue():Object = null*/ + fallbackData = initData } +class LivingTreeButton(lt:LivingTree[_], client:TableBehaviourClient) extends Button(){ + action = Action("xx") { + println("gaga") + lt.expanded = !lt.expanded + client.refresh + } + //println("Gottverdammt") +} + +class ExpansionCellEditor(provider:ExpansionColumnEditorProvider) extends AbstractCellEditor with TableCellEditor{ + def getTableCellEditorComponent(table:JTable, value:Object, isSelected:Boolean, row:Int, column:Int) = provider gimmeEditor row + def getCellEditorValue():java.lang.Object = null +} + +trait ExpansionColumnEditorProvider { + def gimmeEditor(row:Int):java.awt.Component +} + diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 3e76249..7b123fe 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,217 +1,219 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value extends ColumnValue[Data] case class IntValue(i:Int, father:Row[Data]) extends Value case class StringValue(s:String, father:Row[Data]) extends Value /*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } }*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true - def renderComponent(data:Row[Data], isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { - - val l = new Label() - - extractValue(data) match { - case StringValue(s,_) => l.text = s - case IntValue(i,_) => l.text = i.toString - } - - if(isSelected) { - l.opaque = true - l.background = Color.BLUE - } + def renderComponent(data:Row[Data], isSelected: Boolean, focused: Boolean):PimpedRenderer = { + val l = new Label(extractValue(data) match { + case StringValue(s,_) => s + case IntValue(i,_) => i.toString + }) - l + SetMyBackgroundRenderer(l, (x => { + l.opaque = true + l.background = x + })) } - + + + } case class StringColumn(name:String) extends MyColumns[StringValue] { //override val isSortable = false def extractValue(x:Row[Data]) = StringValue(x.data.s, x) + + override val paintGroupColourWhileExpanding = true + def comparator = Some(new ComparatorRelais[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1,_), StringValue(s2,_)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Row[Data]) = IntValue(x.data.i, x) + + override val ignoreWhileExpanding = true def comparator = Some(new ComparatorRelais[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1,_), IntValue(i2,_)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object InternalIntColumnComparator extends Comparator[Leaf[Data]] { def compare(d1:Leaf[Data], d2:Leaf[Data]):Int = (d1.data, d2.data) match { case(Data(i1,_),Data(i2,_)) if i1 == i2 => 0 case(Data(i1,_),Data(i2,_)) if i1 > i2 => 1 case _ => -1 } } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 val lt1 = LivingTree(Data(101, "201xxx") , (0 to 9).toList.map(y => Data(y+1, "201xxx"+y.toString)) , Some(InternalIntColumnComparator) , true ) val lt2 = LivingTree(Data(102, "202xxx") , (0 to 9).toList.map(y => Data(y+1, "202xxx"+y.toString)) , None , true ) val data:List[Row[Data]] = (0 to 100).toList.filter(_%3 == 0).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 1).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 2).map(x => (LivingTree((Data(x, (100-x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(x, (100-x).toString + "xxx" + y.toString)) ,None ,false)) ) ++ List(lt1, lt2) /*++ (101 to 102).toList.map(x => (LivingTree((Data(x, (100+x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(y+1, (100+x).toString + "xxx" + y.toString)) ,None ,true)) ) */ /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) }) */ val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN paintExpandColumn = true } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { - println("Test:") + //println("Test:") //table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ - lt1.expanded = !lt1.expanded + lt2.expanded = !lt2.expanded table.refresh /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { - println("\nCLICK.") + //println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") - table.selectedData.foreach(_ match { + /*table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) - }) + })*/ } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
fa28b11f11c67270348f1c03c8ee553f6192f2fd
internal sorting works too
diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 6673e5b..3e76249 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,211 +1,217 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value extends ColumnValue[Data] case class IntValue(i:Int, father:Row[Data]) extends Value case class StringValue(s:String, father:Row[Data]) extends Value /*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } }*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true def renderComponent(data:Row[Data], isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s,_) => l.text = s case IntValue(i,_) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { //override val isSortable = false def extractValue(x:Row[Data]) = StringValue(x.data.s, x) def comparator = Some(new ComparatorRelais[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1,_), StringValue(s2,_)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Row[Data]) = IntValue(x.data.i, x) def comparator = Some(new ComparatorRelais[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1,_), IntValue(i2,_)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } - +object InternalIntColumnComparator extends Comparator[Leaf[Data]] { + def compare(d1:Leaf[Data], d2:Leaf[Data]):Int = (d1.data, d2.data) match { + case(Data(i1,_),Data(i2,_)) if i1 == i2 => 0 + case(Data(i1,_),Data(i2,_)) if i1 > i2 => 1 + case _ => -1 + } +} object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 val lt1 = LivingTree(Data(101, "201xxx") , (0 to 9).toList.map(y => Data(y+1, "201xxx"+y.toString)) - , None + , Some(InternalIntColumnComparator) , true ) val lt2 = LivingTree(Data(102, "202xxx") , (0 to 9).toList.map(y => Data(y+1, "202xxx"+y.toString)) , None , true ) val data:List[Row[Data]] = (0 to 100).toList.filter(_%3 == 0).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 1).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 2).map(x => (LivingTree((Data(x, (100-x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(x, (100-x).toString + "xxx" + y.toString)) ,None ,false)) ) ++ List(lt1, lt2) /*++ (101 to 102).toList.map(x => (LivingTree((Data(x, (100+x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(y+1, (100+x).toString + "xxx" + y.toString)) ,None ,true)) ) */ /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) }) */ val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN paintExpandColumn = true } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { println("Test:") //table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ lt1.expanded = !lt1.expanded table.refresh /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
294fac7cca60884076ca0fa24c46279ce4bc07b3
sortin now works for expanded rows
diff --git a/PimpedTable.scala b/PimpedTable.scala index d27ba60..dad1d05 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,416 +1,440 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.RowSorter.SortKey import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color import scala.annotation.unchecked.uncheckedVariance /*trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[A] = List.empty[A] var expanded:Boolean = false //val internalComparator:Option[Comparator[A]] = None }*/ trait ColumnValue[-A] { val father:Row[_ >: A] } trait Row[+A] { val data:A } case class DeadTree[A](data:A) extends Row[A] -case class LivingTree[A](data:A, leafData:List[A], internal:Option[Comparator[A]], var expanded:Boolean = false) extends Row[A] { +case class LivingTree[A](data:A, leafData:List[A], internal:Option[Comparator[Leaf[A]]], var expanded:Boolean = false) extends Row[A] { var leaves:List[Leaf[A]] = leafData.map(x => Leaf(x, this)) } case class Leaf[A](data:A, father:LivingTree[A]) extends Row[A] trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } trait ComparatorRelais[+B] extends java.util.Comparator[B @uncheckedVariance] case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { println("Margin changed") takeNewData = true } if(takeNewData) { println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } trait ColumnDescription[-A, +B] { val name:String - def extractValue(x:Row[A]):ColumnValue[_ <: B] + def extractValue(x:Row[A]):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:Row[A], isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[ComparatorRelais[B]] //def comparator: /*Option[Comparator[ColumnValue[_ <: A]]]*/Option[Comparator[_ <: B]] } - +/*class ExtractorRelais[A,B](descr:ColumnDescription[A,B]) { + def ex(x:Row[A]):ColumnValue[B] = descr extractValue x +}*/ class PimpedTableModel[A,B <: ColumnValue[A] ](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { //data(row).isExpandable.asInstanceOf[java.lang.Object] data(row) match { case LivingTree(_,_,_,_) => true.asInstanceOf[java.lang.Object] case _ => false.asInstanceOf[java.lang.Object] } } else { (columns(column - expOffset) extractValue data(row)/*.data*/).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class PimpedColumnComparator[A,B <: ColumnValue[A]](comp:Comparator[B], col:ColumnDescription[A,B], colIndex:Int, mother:SortInfo) extends Comparator[B] { - override def compare(o1:B, o2:B):Int = (o1, o2) match { - case (s1:ColumnValue[A], s2:ColumnValue[A]) => internalCompare(s1,s2) match { - case Some(i) => i - case None => comp.compare(o1, o2) - } - case _ => comp.compare(o1, o2) + override def compare(o1:B, o2:B):Int = internalCompare(o1,o2) match { + case Some(i) => i + case None => comp.compare(o1, o2) } - private def internalCompare(v1:ColumnValue[A], v2:ColumnValue[A]):Option[Int] = (v1, v2) match { - + private def internalCompare(v1:B, v2:B):Option[Int] = (v1.father, v2.father) match { + case(t:LivingTree[A], l:Leaf[A]) => Some(handleLivingtree(t,l)) + case(l:Leaf[A], t:LivingTree[A]) => Some(handleLivingtree(t,l) * (-1)) + case(d:DeadTree[A], l:Leaf[A]) => Some(comp.compare(v1, col extractValue l.father)) + case(l:Leaf[A], d:DeadTree[A]) => Some(comp.compare(col extractValue l.father, v2)) + case(l1:Leaf[A], l2:Leaf[A]) => Some(handleTwoLeaves(l1,l2)) case(_,_) => None } + private def handleTwoLeaves(l1:Leaf[A], l2:Leaf[A]):Int = (l1.father, l2.father) match { + case (f1, f2) if f1 == f2 => f1.internal match { + case None => comp.compare(col extractValue l1, col extractValue l2) + case Some(c) => mother.getSortOrder match { + case Descending => c.compare(l1, l2) * (-1) + case _ => c.compare(l1, l2) + } + } + case (f1,f2) => comp.compare(col extractValue f1, col extractValue f2) + } + + private def handleLivingtree(t:LivingTree[A], l:Leaf[A]):Int = (t, l.father) match { + case (t1, t2) if t1 == t2 => over + case (t1, t2) => comp.compare(col extractValue t1, col extractValue t2) + } + + private def over = mother.getSortOrder match { + case Descending => 1 + case _ => -1 + } + } sealed trait SortOrder case object Ascending extends SortOrder case object Descending extends SortOrder case object NoSort extends SortOrder class SortInfo(sorter:TableRowSorter[_], val column:Int ) { def getSortOrder():SortOrder = { val i = sorter.getSortKeys().iterator var ret:SortOrder = NoSort while(i.hasNext) { val key = i.next if(key.getColumn == column) { val ord = key.getSortOrder if(ord == javax.swing.SortOrder.ASCENDING) ret = Ascending else if(ord == javax.swing.SortOrder.DESCENDING) ret = Descending } } ret } } class ConvenientPimpedTable[A, B <: ColumnValue[A]](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B <: ColumnValue[A]](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() sorter.setSortsOnUpdates(true) this.peer.setRowSorter(sorter) private def fillSorter = { val offset = if(paintExpandColumn) { sorter.setSortable(0, false) 1 } else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => sorter.setSortable(i, true) case Some(c) => { sorter.setComparator(i+offset, new PimpedColumnComparator[A,B](c, colDes, i+offset, new SortInfo(sorter, i+offset))) sorter.setSortable(i,true) } } } } } columns.zipWithIndex foreach { x => x match { case (colDes,i) => if (!colDes.isSortable) sorter.setSortable(i, false) } } } def refresh() = { data = data } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } private def expandData(l:List[Row[A]]):List[Row[A]] = l match { case List() => List.empty[Row[A]] case _ => l.head match { case a@LivingTree(_,_,_,true) => (l.head +: a.leaves) ++ expandData(l.tail) case _ => l.head +: expandData(l.tail) } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() var sortkeys = sorter.getSortKeys blockSelectionEvents = true filteredDat = expandData(d) tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter //sorter.sort() if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } sorter setSortKeys sortkeys if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true filteredData(convertedRow(row)) match { case DeadTree(_) => background = Color.BLACK//RED case LivingTree(_,_,_,_) => background = Color.GREEN case Leaf(_,_) => background = Color.WHITE } if(isSelected) { background = Color.BLUE } } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 5e80a6a..6673e5b 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,211 +1,211 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value extends ColumnValue[Data] case class IntValue(i:Int, father:Row[Data]) extends Value case class StringValue(s:String, father:Row[Data]) extends Value /*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } }*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true def renderComponent(data:Row[Data], isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s,_) => l.text = s case IntValue(i,_) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { //override val isSortable = false def extractValue(x:Row[Data]) = StringValue(x.data.s, x) def comparator = Some(new ComparatorRelais[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1,_), StringValue(s2,_)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Row[Data]) = IntValue(x.data.i, x) def comparator = Some(new ComparatorRelais[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1,_), IntValue(i2,_)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 val lt1 = LivingTree(Data(101, "201xxx") , (0 to 9).toList.map(y => Data(y+1, "201xxx"+y.toString)) , None , true ) - val lt2 = LivingTree(Data(101, "202xxx") + val lt2 = LivingTree(Data(102, "202xxx") , (0 to 9).toList.map(y => Data(y+1, "202xxx"+y.toString)) , None , true ) val data:List[Row[Data]] = (0 to 100).toList.filter(_%3 == 0).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 1).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 2).map(x => (LivingTree((Data(x, (100-x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(x, (100-x).toString + "xxx" + y.toString)) ,None ,false)) ) ++ List(lt1, lt2) /*++ (101 to 102).toList.map(x => (LivingTree((Data(x, (100+x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(y+1, (100+x).toString + "xxx" + y.toString)) ,None ,true)) ) */ /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) }) */ val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN paintExpandColumn = true } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { println("Test:") //table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ lt1.expanded = !lt1.expanded table.refresh /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
07c3f402f973eca6935e84275c65b2dbc9dbbd3c
solved some puzzles. Better Test.
diff --git a/PimpedTable.scala b/PimpedTable.scala index b405a1c..d27ba60 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,429 +1,416 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.RowSorter.SortKey import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color +import scala.annotation.unchecked.uncheckedVariance /*trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[A] = List.empty[A] var expanded:Boolean = false //val internalComparator:Option[Comparator[A]] = None }*/ trait ColumnValue[-A] { val father:Row[_ >: A] } trait Row[+A] { val data:A } case class DeadTree[A](data:A) extends Row[A] case class LivingTree[A](data:A, leafData:List[A], internal:Option[Comparator[A]], var expanded:Boolean = false) extends Row[A] { var leaves:List[Leaf[A]] = leafData.map(x => Leaf(x, this)) } case class Leaf[A](data:A, father:LivingTree[A]) extends Row[A] trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } +trait ComparatorRelais[+B] extends java.util.Comparator[B @uncheckedVariance] + case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { println("Margin changed") takeNewData = true } if(takeNewData) { println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } trait ColumnDescription[-A, +B] { val name:String def extractValue(x:Row[A]):ColumnValue[_ <: B] val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:Row[A], isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component - def comparator: Option[Comparator[_ <: B]] + def comparator: Option[ComparatorRelais[B]] + //def comparator: /*Option[Comparator[ColumnValue[_ <: A]]]*/Option[Comparator[_ <: B]] } -//trait ColumnDescriptionDirtyWorkaround[A, B <: ColumnValue[A] ] extends ColumnDescription[A, B] class PimpedTableModel[A,B <: ColumnValue[A] ](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { //data(row).isExpandable.asInstanceOf[java.lang.Object] data(row) match { case LivingTree(_,_,_,_) => true.asInstanceOf[java.lang.Object] case _ => false.asInstanceOf[java.lang.Object] } } else { (columns(column - expOffset) extractValue data(row)/*.data*/).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } -class PimpedColumnComparator[A, B](comp:Comparator[B], myColumn:Int, mother:SortInfo) extends Comparator[B] { +class PimpedColumnComparator[A,B <: ColumnValue[A]](comp:Comparator[B], col:ColumnDescription[A,B], colIndex:Int, mother:SortInfo) extends Comparator[B] { override def compare(o1:B, o2:B):Int = (o1, o2) match { case (s1:ColumnValue[A], s2:ColumnValue[A]) => internalCompare(s1,s2) match { case Some(i) => i case None => comp.compare(o1, o2) } case _ => comp.compare(o1, o2) } private def internalCompare(v1:ColumnValue[A], v2:ColumnValue[A]):Option[Int] = (v1, v2) match { + case(_,_) => None - //println("BIN DA!!!!!! " + v1 + " / " + v2) - //println(mother.column + ": " +mother.getSortOrder) - //None + } - - - //comp.compare(o1, o2) - - //def blabla(o1:B):A = o1.father } sealed trait SortOrder case object Ascending extends SortOrder case object Descending extends SortOrder case object NoSort extends SortOrder -class SortInfo(sorter:TableRowSorter[_], val column:Int) { +class SortInfo(sorter:TableRowSorter[_], val column:Int ) { def getSortOrder():SortOrder = { val i = sorter.getSortKeys().iterator var ret:SortOrder = NoSort while(i.hasNext) { val key = i.next if(key.getColumn == column) { val ord = key.getSortOrder if(ord == javax.swing.SortOrder.ASCENDING) ret = Ascending else if(ord == javax.swing.SortOrder.DESCENDING) ret = Descending } } ret } } class ConvenientPimpedTable[A, B <: ColumnValue[A]](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B <: ColumnValue[A]](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() sorter.setSortsOnUpdates(true) this.peer.setRowSorter(sorter) private def fillSorter = { val offset = if(paintExpandColumn) { sorter.setSortable(0, false) 1 } else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => sorter.setSortable(i, true) case Some(c) => { - sorter.setComparator(i+offset, new PimpedColumnComparator(c,i+offset, new SortInfo(sorter, i+offset))) + sorter.setComparator(i+offset, new PimpedColumnComparator[A,B](c, colDes, i+offset, new SortInfo(sorter, i+offset))) sorter.setSortable(i,true) } } } } } columns.zipWithIndex foreach { x => x match { case (colDes,i) => if (!colDes.isSortable) sorter.setSortable(i, false) } } } + def refresh() = { + data = data + } + private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } private def expandData(l:List[Row[A]]):List[Row[A]] = l match { case List() => List.empty[Row[A]] case _ => l.head match { case a@LivingTree(_,_,_,true) => (l.head +: a.leaves) ++ expandData(l.tail) case _ => l.head +: expandData(l.tail) } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() var sortkeys = sorter.getSortKeys blockSelectionEvents = true filteredDat = expandData(d) tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter //sorter.sort() if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } sorter setSortKeys sortkeys if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da - /*var sel = selectedData() - blockSelectionEvents = true - fallbackData = da - //triggerDataChange() - tableModel = new PimpedTableModel(filteredData, columns) - this.model = tableModel - sorter setModel tableModel - fillSorter - if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { - //System.out.println("something changed") - blockSelectionEvents = false - publish(TableRowsSelected(this, Range(0,0), true)) - } - blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true filteredData(convertedRow(row)) match { case DeadTree(_) => background = Color.BLACK//RED case LivingTree(_,_,_,_) => background = Color.GREEN case Leaf(_,_) => background = Color.WHITE } if(isSelected) { background = Color.BLUE } } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 733ef71..5e80a6a 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,194 +1,211 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value extends ColumnValue[Data] case class IntValue(i:Int, father:Row[Data]) extends Value case class StringValue(s:String, father:Row[Data]) extends Value /*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } }*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true def renderComponent(data:Row[Data], isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s,_) => l.text = s case IntValue(i,_) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { //override val isSortable = false def extractValue(x:Row[Data]) = StringValue(x.data.s, x) - def comparator = Some(new Comparator[StringValue] { + def comparator = Some(new ComparatorRelais[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1,_), StringValue(s2,_)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Row[Data]) = IntValue(x.data.i, x) - def comparator = Some(new Comparator[IntValue] { + def comparator = Some(new ComparatorRelais[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1,_), IntValue(i2,_)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 + val lt1 = LivingTree(Data(101, "201xxx") + , (0 to 9).toList.map(y => + Data(y+1, "201xxx"+y.toString)) + , None + , true + ) + + val lt2 = LivingTree(Data(101, "202xxx") + , (0 to 9).toList.map(y => + Data(y+1, "202xxx"+y.toString)) + , None + , true + ) + val data:List[Row[Data]] = (0 to 100).toList.filter(_%3 == 0).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 1).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) ++ (0 to 100).toList.filter(_%3 == 2).map(x => (LivingTree((Data(x, (100-x).toString + "xxx")) ,(0 to 9).toList.map(y => Data(x, (100-x).toString + "xxx" + y.toString)) ,None ,false)) - ) ++ (101 to 102).toList.map(x => - (LivingTree((Data(x, (100-x).toString + "xxx")) + ) ++ List(lt1, lt2) + /*++ (101 to 102).toList.map(x => + (LivingTree((Data(x, (100+x).toString + "xxx")) ,(0 to 9).toList.map(y => - Data(x, (100-x).toString + "xxx" + y.toString)) + Data(y+1, (100+x).toString + "xxx" + y.toString)) ,None ,true)) - ) + ) */ /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) }) */ val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN paintExpandColumn = true } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { - //println("Test:") + println("Test:") //table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ - if(table.isFiltered) table.unfilter + lt1.expanded = !lt1.expanded + table.refresh + /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 - }) + })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
8e59d0fb24851d2cf89acd049988e63d30d3c16f
expanded nodes get expandend. Basic destinction in expansion column rendering.
diff --git a/PimpedTable.scala b/PimpedTable.scala index 2e9d322..b405a1c 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,415 +1,429 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.RowSorter.SortKey import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color /*trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[A] = List.empty[A] var expanded:Boolean = false //val internalComparator:Option[Comparator[A]] = None }*/ trait ColumnValue[-A] { val father:Row[_ >: A] } trait Row[+A] { val data:A } case class DeadTree[A](data:A) extends Row[A] -case class Tree[A](data:A, leafData:List[A], internal:Option[Comparator[A]], var expanded:Boolean = false) extends Row[A] { +case class LivingTree[A](data:A, leafData:List[A], internal:Option[Comparator[A]], var expanded:Boolean = false) extends Row[A] { var leaves:List[Leaf[A]] = leafData.map(x => Leaf(x, this)) } -case class Leaf[A](data:A, father:Tree[A]) extends Row[A] +case class Leaf[A](data:A, father:LivingTree[A]) extends Row[A] trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { println("Margin changed") takeNewData = true } if(takeNewData) { println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } trait ColumnDescription[-A, +B] { val name:String def extractValue(x:Row[A]):ColumnValue[_ <: B] val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:Row[A], isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } //trait ColumnDescriptionDirtyWorkaround[A, B <: ColumnValue[A] ] extends ColumnDescription[A, B] class PimpedTableModel[A,B <: ColumnValue[A] ](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { //data(row).isExpandable.asInstanceOf[java.lang.Object] data(row) match { - case Tree(_,_,_,_) => true.asInstanceOf[java.lang.Object] - case _ => false.asInstanceOf[java.lang.Object] + case LivingTree(_,_,_,_) => true.asInstanceOf[java.lang.Object] + case _ => false.asInstanceOf[java.lang.Object] } } else { (columns(column - expOffset) extractValue data(row)/*.data*/).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class PimpedColumnComparator[A, B](comp:Comparator[B], myColumn:Int, mother:SortInfo) extends Comparator[B] { override def compare(o1:B, o2:B):Int = (o1, o2) match { case (s1:ColumnValue[A], s2:ColumnValue[A]) => internalCompare(s1,s2) match { case Some(i) => i case None => comp.compare(o1, o2) } case _ => comp.compare(o1, o2) } private def internalCompare(v1:ColumnValue[A], v2:ColumnValue[A]):Option[Int] = (v1, v2) match { case(_,_) => None //println("BIN DA!!!!!! " + v1 + " / " + v2) //println(mother.column + ": " +mother.getSortOrder) //None } //comp.compare(o1, o2) //def blabla(o1:B):A = o1.father } sealed trait SortOrder case object Ascending extends SortOrder case object Descending extends SortOrder case object NoSort extends SortOrder class SortInfo(sorter:TableRowSorter[_], val column:Int) { def getSortOrder():SortOrder = { val i = sorter.getSortKeys().iterator var ret:SortOrder = NoSort while(i.hasNext) { val key = i.next if(key.getColumn == column) { val ord = key.getSortOrder if(ord == javax.swing.SortOrder.ASCENDING) ret = Ascending else if(ord == javax.swing.SortOrder.DESCENDING) ret = Descending } } ret } } class ConvenientPimpedTable[A, B <: ColumnValue[A]](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B <: ColumnValue[A]](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() sorter.setSortsOnUpdates(true) this.peer.setRowSorter(sorter) private def fillSorter = { val offset = if(paintExpandColumn) { sorter.setSortable(0, false) 1 } else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => sorter.setSortable(i, true) case Some(c) => { sorter.setComparator(i+offset, new PimpedColumnComparator(c,i+offset, new SortInfo(sorter, i+offset))) sorter.setSortable(i,true) } } } } } columns.zipWithIndex foreach { x => x match { case (colDes,i) => if (!colDes.isSortable) sorter.setSortable(i, false) } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } + private def expandData(l:List[Row[A]]):List[Row[A]] = l match { + case List() => List.empty[Row[A]] + case _ => l.head match { + case a@LivingTree(_,_,_,true) => (l.head +: a.leaves) ++ expandData(l.tail) + case _ => l.head +: expandData(l.tail) + } + } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() var sortkeys = sorter.getSortKeys blockSelectionEvents = true - filteredDat = d + filteredDat = expandData(d) tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter //sorter.sort() if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } sorter setSortKeys sortkeys if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true - background = Color.RED + filteredData(convertedRow(row)) match { + case DeadTree(_) => background = Color.BLACK//RED + case LivingTree(_,_,_,_) => background = Color.GREEN + case Leaf(_,_) => background = Color.WHITE + } + if(isSelected) { + background = Color.BLUE + } } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index eadfca9..733ef71 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,178 +1,194 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value extends ColumnValue[Data] case class IntValue(i:Int, father:Row[Data]) extends Value case class StringValue(s:String, father:Row[Data]) extends Value /*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } }*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true def renderComponent(data:Row[Data], isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s,_) => l.text = s case IntValue(i,_) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { //override val isSortable = false def extractValue(x:Row[Data]) = StringValue(x.data.s, x) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1,_), StringValue(s2,_)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Row[Data]) = IntValue(x.data.i, x) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1,_), IntValue(i2,_)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } + + object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 - val data:List[Row[Data]] = (0 to 100).toList.map(x => + val data:List[Row[Data]] = (0 to 100).toList.filter(_%3 == 0).map(x => + DeadTree(Data(x, (100-x).toString + "xxx")) + ) ++ (0 to 100).toList.filter(_%3 == 1).map(x => DeadTree(Data(x, (100-x).toString + "xxx")) - ) + ) ++ (0 to 100).toList.filter(_%3 == 2).map(x => + (LivingTree((Data(x, (100-x).toString + "xxx")) + ,(0 to 9).toList.map(y => + Data(x, (100-x).toString + "xxx" + y.toString)) + ,None + ,false)) + ) ++ (101 to 102).toList.map(x => + (LivingTree((Data(x, (100-x).toString + "xxx")) + ,(0 to 9).toList.map(y => + Data(x, (100-x).toString + "xxx" + y.toString)) + ,None + ,true)) + ) /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) }) */ val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN paintExpandColumn = true } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { //println("Test:") //table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 }) //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
aaacebde481a150908c2d3cbb348c703eab9e9fc
did lot's of "lifting". Finally I can start nailing that expansion stuff.
diff --git a/PimpedTable.scala b/PimpedTable.scala index 8485085..2e9d322 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,357 +1,415 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter +import javax.swing.RowSorter.SortKey import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color /*trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[A] = List.empty[A] var expanded:Boolean = false //val internalComparator:Option[Comparator[A]] = None }*/ -trait ColumnValue[A] { - val father:A +trait ColumnValue[-A] { + val father:Row[_ >: A] } -trait Row[A] { +trait Row[+A] { val data:A } case class DeadTree[A](data:A) extends Row[A] case class Tree[A](data:A, leafData:List[A], internal:Option[Comparator[A]], var expanded:Boolean = false) extends Row[A] { var leaves:List[Leaf[A]] = leafData.map(x => Leaf(x, this)) } case class Leaf[A](data:A, father:Tree[A]) extends Row[A] trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { println("Margin changed") takeNewData = true } if(takeNewData) { println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } -trait ColumnDescription[-A,+B] { +trait ColumnDescription[-A, +B] { val name:String - def extractValue(x:A):B + def extractValue(x:Row[A]):ColumnValue[_ <: B] val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false - def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component + def renderComponent(data:Row[A], isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } -class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { +//trait ColumnDescriptionDirtyWorkaround[A, B <: ColumnValue[A] ] extends ColumnDescription[A, B] + + +class PimpedTableModel[A,B <: ColumnValue[A] ](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { //data(row).isExpandable.asInstanceOf[java.lang.Object] data(row) match { case Tree(_,_,_,_) => true.asInstanceOf[java.lang.Object] case _ => false.asInstanceOf[java.lang.Object] } } else { - (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] + (columns(column - expOffset) extractValue data(row)/*.data*/).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } +class PimpedColumnComparator[A, B](comp:Comparator[B], myColumn:Int, mother:SortInfo) extends Comparator[B] { + override def compare(o1:B, o2:B):Int = (o1, o2) match { + case (s1:ColumnValue[A], s2:ColumnValue[A]) => internalCompare(s1,s2) match { + case Some(i) => i + case None => comp.compare(o1, o2) + } + case _ => comp.compare(o1, o2) + } + + private def internalCompare(v1:ColumnValue[A], v2:ColumnValue[A]):Option[Int] = (v1, v2) match { + case(_,_) => None + //println("BIN DA!!!!!! " + v1 + " / " + v2) + //println(mother.column + ": " +mother.getSortOrder) + //None + } + + + //comp.compare(o1, o2) + + //def blabla(o1:B):A = o1.father + +} + +sealed trait SortOrder +case object Ascending extends SortOrder +case object Descending extends SortOrder +case object NoSort extends SortOrder + +class SortInfo(sorter:TableRowSorter[_], val column:Int) { + + def getSortOrder():SortOrder = { + val i = sorter.getSortKeys().iterator + var ret:SortOrder = NoSort + + while(i.hasNext) { + val key = i.next + if(key.getColumn == column) { + val ord = key.getSortOrder + if(ord == javax.swing.SortOrder.ASCENDING) ret = Ascending + else if(ord == javax.swing.SortOrder.DESCENDING) ret = Descending + } + } + + ret + } +} + class ConvenientPimpedTable[A, B <: ColumnValue[A]](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B <: ColumnValue[A]](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) + private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None private var blockSelectionEvents:Boolean = false - val sorter = new TableRowSorter[PimpedTableModel[A,B]]() + val sorter = new TableRowSorter[PimpedTableModel[A,B]]() + sorter.setSortsOnUpdates(true) this.peer.setRowSorter(sorter) private def fillSorter = { val offset = if(paintExpandColumn) { sorter.setSortable(0, false) 1 } else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => sorter.setSortable(i, true) case Some(c) => { - sorter.setComparator(i+offset, c) + sorter.setComparator(i+offset, new PimpedColumnComparator(c,i+offset, new SortInfo(sorter, i+offset))) sorter.setSortable(i,true) } } } } } columns.zipWithIndex foreach { x => x match { case (colDes,i) => if (!colDes.isSortable) sorter.setSortable(i, false) } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() + var sortkeys = sorter.getSortKeys blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter + //sorter.sort() if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } + + sorter setSortKeys sortkeys if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 } + blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { val c = convertedColumn(column)-1 - if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) + if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { - columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) + columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)), isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index d0afc8a..eadfca9 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,179 +1,178 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) -sealed trait Value extends ColumnValue[Data] { - val father = null -} +sealed trait Value extends ColumnValue[Data] -case class IntValue(i:Int) extends Value -case class StringValue(s:String) extends Value +case class IntValue(i:Int, father:Row[Data]) extends Value +case class StringValue(s:String, father:Row[Data]) extends Value /*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } }*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true - def renderComponent(data:Data, isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { + def renderComponent(data:Row[Data], isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { - case StringValue(s) => l.text = s - case IntValue(i) => l.text = i.toString + case StringValue(s,_) => l.text = s + case IntValue(i,_) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { - override val isSortable = false - def extractValue(x:Data) = StringValue(x.s) + //override val isSortable = false + def extractValue(x:Row[Data]) = StringValue(x.data.s, x) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { - case (StringValue(s1), StringValue(s2)) => + case (StringValue(s1,_), StringValue(s2,_)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { - def extractValue(x:Data) = IntValue(x.i) + def extractValue(x:Row[Data]) = IntValue(x.data.i, x) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { - case (IntValue(i1), IntValue(i2)) => + case (IntValue(i1,_), IntValue(i2,_)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 val data:List[Row[Data]] = (0 to 100).toList.map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) }) */ val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN + paintExpandColumn = true } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { //println("Test:") - table.paintExpandColumn = !table.paintExpandColumn + //table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ - /*if(table.isFiltered) table.unfilter + if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 - })*/ + }) //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
91f91042befaf171ce3b9546cca28efc68198d21
looking good on the type side. On my way to extension
diff --git a/PimpedTable.scala b/PimpedTable.scala index 85408ca..8485085 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,359 +1,357 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color /*trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[A] = List.empty[A] var expanded:Boolean = false //val internalComparator:Option[Comparator[A]] = None }*/ +trait ColumnValue[A] { + val father:A +} + trait Row[A] { val data:A } case class DeadTree[A](data:A) extends Row[A] case class Tree[A](data:A, leafData:List[A], internal:Option[Comparator[A]], var expanded:Boolean = false) extends Row[A] { var leaves:List[Leaf[A]] = leafData.map(x => Leaf(x, this)) } case class Leaf[A](data:A, father:Tree[A]) extends Row[A] -/*trait UnexpandAbleRow[A] extends Row[A] { - val isExpandable:Boolean = false - def expandedData():List[A] = List.empty[A] - var expanded:Boolean = false -} - -trait ExpandableRow[A] extends Row[A] { - val isExpandable:Boolean = false - var expanded:Boolean = false - -}*/ - -/*trait ExpandedData[A] extends Row[A]{ - val father:A -}*/ - - - trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { println("Margin changed") takeNewData = true } if(takeNewData) { println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } trait ColumnDescription[-A,+B] { val name:String def extractValue(x:A):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { //data(row).isExpandable.asInstanceOf[java.lang.Object] data(row) match { case Tree(_,_,_,_) => true.asInstanceOf[java.lang.Object] case _ => false.asInstanceOf[java.lang.Object] } } else { (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } -class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) +class ConvenientPimpedTable[A, B <: ColumnValue[A]](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) -class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { +class PimpedTable[A, B <: ColumnValue[A]](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { - val offset = if(paintExpandColumn) 1 else 0 + val offset = if(paintExpandColumn) { + sorter.setSortable(0, false) + 1 + } else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { - case (colDes,i) => { colDes.comparator match { - case None => {} - case Some(c) => sorter.setComparator(i+offset, c) + case (colDes,i) => { colDes.comparator match { + case None => sorter.setSortable(i, true) + case Some(c) => { + sorter.setComparator(i+offset, c) + sorter.setSortable(i,true) + } + } } } + } + + columns.zipWithIndex foreach { + x => x match { + case (colDes,i) => if (!colDes.isSortable) sorter.setSortable(i, false) } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 3631b74..d0afc8a 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,176 +1,179 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) -sealed trait Value +sealed trait Value extends ColumnValue[Data] { + val father = null +} case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value /*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } }*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { + override val isSortable = false def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 val data:List[Row[Data]] = (0 to 100).toList.map(x => DeadTree(Data(x, (100-x).toString + "xxx")) ) /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) }) */ val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { //println("Test:") table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
3d6313156b3c629d03e7e67b7f1cf433572a3a0b
wasn't all that bad, was it?
diff --git a/PimpedTable.scala b/PimpedTable.scala index 3e49886..85408ca 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,353 +1,359 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color -trait Row[A] { +/*trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[A] = List.empty[A] var expanded:Boolean = false //val internalComparator:Option[Comparator[A]] = None -} +}*/ -trait Rowa[A] { +trait Row[A] { val data:A } -case class DeadTree[A](data:A) extends Rowa[A] -case class Tree[A](data:A, leaves:List[Leaf[A]], internal:Option[Comparator[A]]) extends Rowa[A] -case class Leaf[A](data:A, father:Tree[A]) extends Rowa[A] +case class DeadTree[A](data:A) extends Row[A] +case class Tree[A](data:A, leafData:List[A], internal:Option[Comparator[A]], var expanded:Boolean = false) extends Row[A] { + var leaves:List[Leaf[A]] = leafData.map(x => Leaf(x, this)) +} +case class Leaf[A](data:A, father:Tree[A]) extends Row[A] /*trait UnexpandAbleRow[A] extends Row[A] { val isExpandable:Boolean = false def expandedData():List[A] = List.empty[A] var expanded:Boolean = false } trait ExpandableRow[A] extends Row[A] { val isExpandable:Boolean = false var expanded:Boolean = false }*/ /*trait ExpandedData[A] extends Row[A]{ val father:A }*/ trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { println("Margin changed") takeNewData = true } if(takeNewData) { println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } trait ColumnDescription[-A,+B] { val name:String def extractValue(x:A):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { - data(row).isExpandable.asInstanceOf[java.lang.Object] + //data(row).isExpandable.asInstanceOf[java.lang.Object] + data(row) match { + case Tree(_,_,_,_) => true.asInstanceOf[java.lang.Object] + case _ => false.asInstanceOf[java.lang.Object] + } } else { (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { val offset = if(paintExpandColumn) 1 else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i+offset, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index d1f448b..3631b74 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,171 +1,176 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value -case class RowData(data:Data) extends Row[Data] { +/*case class RowData(data:Data) extends Row[Data] { override val isExpandable = true override def expandedData() = { (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) } -} +}*/ /*case class UnexpandableRowData(data:Data) extends RowData(data) { override val isExpandable = false override def expandedData() = List.empty[RowData] }*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 - val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))/*{ + val data:List[Row[Data]] = (0 to 100).toList.map(x => + DeadTree(Data(x, (100-x).toString + "xxx")) + ) + /*val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx")){ isExpandable = true expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) - }*/) + }) */ + + val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { //println("Test:") table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
30c41eb5cc948ba717780a8c00d715a5fd61b8ca
last stop bevore refactoring the whole data model
diff --git a/PimpedTable.scala b/PimpedTable.scala index 9c68eb1..3e49886 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,338 +1,353 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color trait Row[A] { val data:A val isExpandable:Boolean = false - def expandedData():List[ExpandedData[A]] = List.empty[ExpandedData[A]] + def expandedData():List[A] = List.empty[A] var expanded:Boolean = false - val internalComparator:Option[Comparator[A]] = None + //val internalComparator:Option[Comparator[A]] = None } -trait ExpandedData[A] extends Row[A]{ - val father:A +trait Rowa[A] { + val data:A +} + +case class DeadTree[A](data:A) extends Rowa[A] +case class Tree[A](data:A, leaves:List[Leaf[A]], internal:Option[Comparator[A]]) extends Rowa[A] +case class Leaf[A](data:A, father:Tree[A]) extends Rowa[A] + +/*trait UnexpandAbleRow[A] extends Row[A] { + val isExpandable:Boolean = false + def expandedData():List[A] = List.empty[A] + var expanded:Boolean = false } +trait ExpandableRow[A] extends Row[A] { + val isExpandable:Boolean = false + var expanded:Boolean = false + +}*/ + +/*trait ExpandedData[A] extends Row[A]{ + val father:A +}*/ + trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 println("fixed it") } } if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) takeNewData = true } if(marginChanged) { println("Margin changed") takeNewData = true } if(takeNewData) { println("take new data") } columnNewValue = -1 columnValue = -1 marginChanged = false } } trait ColumnDescription[-A,+B] { val name:String def extractValue(x:A):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { data(row).isExpandable.asInstanceOf[java.lang.Object] } else { (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] } } override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed - //peer.getColumnModel().addColumnModelListener(ColumFixingColumListener(this)) private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) - //val groupColour:Option[java.awt.Color] = Some(Color.LIGHT_GRAY) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None - //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) - //peer.getColumnModel.addColumnModelListener() - private def fillSorter = { val offset = if(paintExpandColumn) 1 else 0 columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i+offset, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } if(paintExpandColumn) { val col = peer.getTableHeader.getColumnModel.getColumn(0) col setWidth 30 col setMinWidth 30 col setMaxWidth 30 } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index d6bded7..d1f448b 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,158 +1,171 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value -case class RowData(data:Data) extends Row[Data] +case class RowData(data:Data) extends Row[Data] { + override val isExpandable = true + override def expandedData() = { + (1 to 10).toList.map(x => Data(data.i, data.s + x.toString)) + } +} + +/*case class UnexpandableRowData(data:Data) extends RowData(data) { + override val isExpandable = false + override def expandedData() = List.empty[RowData] +}*/ sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 - val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) + val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))/*{ + isExpandable = true + expandedData = (0 to 10).toList.map(y => RowData(Data(x, (100-x).toString + "xxx"+y.toString))) + }*/) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { //println("Test:") table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } } diff --git a/Utils.scala b/Utils.scala index bed7253..f167d7d 100644 --- a/Utils.scala +++ b/Utils.scala @@ -1,18 +1,19 @@ +package at.axelGschaider.utils object Twister { private def doDaTwist[A](target:List[A], move:((Int, Int, List[A])=>List[A]), source:List[Int], done:List[Int], to:Int):List[A] = { if(source.length==0) { target } else { val i = source.head + done.filter(x => x >= source.head).size doDaTwist(move(i, to, target), move, source.tail, source.head +: done, to+1) } } def twist[A](target:List[A], source:List[Int], move:((Int, Int, List[A])=>List[A])) = { if(target.length != source.length) throw new Error("Lists need to be the same size") doDaTwist(target, move, source, List.empty[Int], 0) } }
axelGschaider/PimpedScalaTable
be6c4c74d13b942297868c1bb0fb393e302d01fe
fix bug that resulted in bad sorter when there is a expansion column
diff --git a/PimpedTable.scala b/PimpedTable.scala index e563102..9c68eb1 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,331 +1,338 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[ExpandedData[A]] = List.empty[ExpandedData[A]] var expanded:Boolean = false val internalComparator:Option[Comparator[A]] = None } trait ExpandedData[A] extends Row[A]{ val father:A } trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { marginChanged = true } def columnMoved(e: TableColumnModelEvent) { - //println("column moved") if(columnValue == -1) columnValue = e.getFromIndex columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { + var takeNewData = false if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) columnNewValue = -1 columnValue = -1 println("fixed it") } } - if(columnValue != -1) { + if(columnValue != -1 && columnValue != columnNewValue) { println(columnValue + " -> " + columnNewValue) + takeNewData = true } if(marginChanged) { println("Margin changed") + takeNewData = true + } + + if(takeNewData) { + println("take new data") } columnNewValue = -1 columnValue = -1 - marginChanged = true + marginChanged = false } } trait ColumnDescription[-A,+B] { val name:String def extractValue(x:A):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } - def getRowCount():Int = data.length + expOffset + def getRowCount():Int = data.length def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } - + if(paintExpander && column == 0) { data(row).isExpandable.asInstanceOf[java.lang.Object] } else { (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] } - } - /*def getNiceValue(row:Int, column:Int): B = { - if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { - throw new Error("Bad Table Index: row " + row + " column " + column) - } - columns(column) extractValue data(row).data - }*/ - override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed //peer.getColumnModel().addColumnModelListener(ColumFixingColumListener(this)) private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) //val groupColour:Option[java.awt.Color] = Some(Color.LIGHT_GRAY) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) //peer.getColumnModel.addColumnModelListener() private def fillSorter = { + val offset = if(paintExpandColumn) 1 else 0 + columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} - case Some(c) => sorter.setComparator(i, c) + case Some(c) => sorter.setComparator(i+offset, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { - //System.out.println("something changed") blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } + + if(paintExpandColumn) { + val col = peer.getTableHeader.getColumnModel.getColumn(0) + col setWidth 30 + col setMinWidth 30 + col setMaxWidth 30 + } + blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 839d972..d6bded7 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,160 +1,158 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { - /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { - case (IntValue(i1), IntValue(i2)) => i1 > i2 - case (StringValue(s1), StringValue(s2)) => s1 > s2 - }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { - case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 - else if (s1 > s2) 1 - else 0 + case (StringValue(s1), StringValue(s2)) => + if(s1 < s2) -1 + else if (s1 > s2) 1 + else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { - case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 - else if (i1 > i2) 1 - else 0 + case (IntValue(i1), IntValue(i2)) => + if(i1 < i2) -1 + else if (i1 > i2) 1 + else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 480 val frameheight = 480 val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { //println("Test:") table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
f49040114050dcfe50e358df5afa66bfee6c44d6
Set up new Utils.scala, needed for Column Remembering
diff --git a/PimpedTable.scala b/PimpedTable.scala index 41a733e..e563102 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,320 +1,331 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[ExpandedData[A]] = List.empty[ExpandedData[A]] var expanded:Boolean = false val internalComparator:Option[Comparator[A]] = None } trait ExpandedData[A] extends Row[A]{ val father:A } trait TableBehaviourClient { def paintExpandColumn:Boolean = false def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { private var columnValue:Int = -1 private var columnNewValue:Int = -1 + private var marginChanged:Boolean = false def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) { - + marginChanged = true } def columnMoved(e: TableColumnModelEvent) { - if(x.paintExpandColumn) { //println("column moved") - if(columnValue == -1) columnValue = e.getFromIndex - columnNewValue = e.getToIndex - } + if(columnValue == -1) columnValue = e.getFromIndex + columnNewValue = e.getToIndex } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} override def mouseReleased(e:MouseEvent) { if(x.paintExpandColumn) { if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { x.moveColumn(columnNewValue, columnValue) + columnNewValue = -1 + columnValue = -1 + println("fixed it") } - columnNewValue = -1 - columnValue = -1 } + if(columnValue != -1) { + println(columnValue + " -> " + columnNewValue) + } + + if(marginChanged) { + println("Margin changed") + } + + columnNewValue = -1 + columnValue = -1 + marginChanged = true } } trait ColumnDescription[-A,+B] { val name:String def extractValue(x:A):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length + expOffset def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { data(row).isExpandable.asInstanceOf[java.lang.Object] } else { (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] } } /*def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data }*/ override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) -class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with ColumnFixer with TableBehaviourClient { +class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed //peer.getColumnModel().addColumnModelListener(ColumFixingColumListener(this)) private val behaviourWorker = TableBehaviourWorker(this) peer.getColumnModel().addColumnModelListener(behaviourWorker) peer.getTableHeader().addMouseListener(behaviourWorker) //val groupColour:Option[java.awt.Color] = Some(Color.LIGHT_GRAY) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) //peer.getColumnModel.addColumnModelListener() private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData } diff --git a/Utils.scala b/Utils.scala new file mode 100644 index 0000000..bed7253 --- /dev/null +++ b/Utils.scala @@ -0,0 +1,18 @@ + +object Twister { + + private def doDaTwist[A](target:List[A], move:((Int, Int, List[A])=>List[A]), source:List[Int], done:List[Int], to:Int):List[A] = { + if(source.length==0) { + target + } + else { + val i = source.head + done.filter(x => x >= source.head).size + doDaTwist(move(i, to, target), move, source.tail, source.head +: done, to+1) + } + } + + def twist[A](target:List[A], source:List[Int], move:((Int, Int, List[A])=>List[A])) = { + if(target.length != source.length) throw new Error("Lists need to be the same size") + doDaTwist(target, move, source, List.empty[Int], 0) + } +}
axelGschaider/PimpedScalaTable
fa7ed0ac4f031635dc4a29b90d70ebb6c61870fa
refactored the 2 listeners into one
diff --git a/PimpedTable.scala b/PimpedTable.scala index 2bb7dd1..41a733e 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,314 +1,320 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[ExpandedData[A]] = List.empty[ExpandedData[A]] var expanded:Boolean = false val internalComparator:Option[Comparator[A]] = None } trait ExpandedData[A] extends Row[A]{ val father:A } -trait ColumnFixer { + + + +trait TableBehaviourClient { def paintExpandColumn:Boolean = false - var columnValue:Int = -1 - var columnNewValue:Int = -1 def moveColumn(oldIndex:Int, newIndex:Int):Unit def reordering_=(allowe:Boolean) def reordering:Boolean } -case class ColumFixingColumListener(x: ColumnFixer) extends TableColumnModelListener{ +case class TableBehaviourWorker(x: TableBehaviourClient) extends MouseAdapter with TableColumnModelListener { + + private var columnValue:Int = -1 + private var columnNewValue:Int = -1 + def columnSelectionChanged(e: ListSelectionEvent) {} - def columnMarginChanged(e: ChangeEvent) {} + def columnMarginChanged(e: ChangeEvent) { + + } def columnMoved(e: TableColumnModelEvent) { if(x.paintExpandColumn) { //println("column moved") - if(x.columnValue == -1) x.columnValue = e.getFromIndex - x.columnNewValue = e.getToIndex + if(columnValue == -1) columnValue = e.getFromIndex + columnNewValue = e.getToIndex } } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} -} -case class ColumnFixingMouseListener(x: ColumnFixer) extends MouseAdapter { override def mouseReleased(e:MouseEvent) { if(x.paintExpandColumn) { - println("can i kick it?") - if(x.columnValue != -1 && (x.columnValue == 0 || x.columnNewValue == 0)) { - x.moveColumn(x.columnNewValue, x.columnValue) - println("get back!!!!") + if(columnValue != -1 && (columnValue == 0 || columnNewValue == 0)) { + x.moveColumn(columnNewValue, columnValue) } - x.columnNewValue = -1 - x.columnValue = -1 + columnNewValue = -1 + columnValue = -1 } } } + trait ColumnDescription[-A,+B] { val name:String def extractValue(x:A):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length + expOffset def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { data(row).isExpandable.asInstanceOf[java.lang.Object] } else { (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] } } /*def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data }*/ override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) -class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with ColumnFixer { +class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with ColumnFixer with TableBehaviourClient { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe def reordering:Boolean = peer.getTableHeader.getReorderingAllowed - peer.getColumnModel().addColumnModelListener(ColumFixingColumListener(this)) - peer.getTableHeader().addMouseListener(ColumnFixingMouseListener(this)) + //peer.getColumnModel().addColumnModelListener(ColumFixingColumListener(this)) + private val behaviourWorker = TableBehaviourWorker(this) + peer.getColumnModel().addColumnModelListener(behaviourWorker) + peer.getTableHeader().addMouseListener(behaviourWorker) //val groupColour:Option[java.awt.Color] = Some(Color.LIGHT_GRAY) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) //peer.getColumnModel.addColumnModelListener() private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { val c = convertedColumn(column)-1 if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData }
axelGschaider/PimpedScalaTable
0a2e49b6b635e166990e31843f653023d73569e9
now i nailed the column dragging error (while haveing a fixed first column).
diff --git a/PimpedTable.scala b/PimpedTable.scala index 5d8412c..2bb7dd1 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,303 +1,314 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} import java.awt.event.{MouseEvent, MouseAdapter} import java.util.EventObject import java.util.Comparator import java.awt.Color trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[ExpandedData[A]] = List.empty[ExpandedData[A]] var expanded:Boolean = false val internalComparator:Option[Comparator[A]] = None } trait ExpandedData[A] extends Row[A]{ val father:A } trait ColumnFixer { def paintExpandColumn:Boolean = false var columnValue:Int = -1 var columnNewValue:Int = -1 def moveColumn(oldIndex:Int, newIndex:Int):Unit + def reordering_=(allowe:Boolean) + def reordering:Boolean } case class ColumFixingColumListener(x: ColumnFixer) extends TableColumnModelListener{ def columnSelectionChanged(e: ListSelectionEvent) {} def columnMarginChanged(e: ChangeEvent) {} def columnMoved(e: TableColumnModelEvent) { if(x.paintExpandColumn) { + //println("column moved") if(x.columnValue == -1) x.columnValue = e.getFromIndex x.columnNewValue = e.getToIndex } } def columnRemoved(e: TableColumnModelEvent) {} def columnAdded(e: TableColumnModelEvent) {} } case class ColumnFixingMouseListener(x: ColumnFixer) extends MouseAdapter { override def mouseReleased(e:MouseEvent) { if(x.paintExpandColumn) { - if(x.columnValue != -1 && (x.columnValue == 0 && x.columnNewValue == 0)) { - + println("can i kick it?") + if(x.columnValue != -1 && (x.columnValue == 0 || x.columnNewValue == 0)) { + x.moveColumn(x.columnNewValue, x.columnValue) + println("get back!!!!") } + x.columnNewValue = -1 + x.columnValue = -1 } } } trait ColumnDescription[-A,+B] { val name:String def extractValue(x:A):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length + expOffset def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { data(row).isExpandable.asInstanceOf[java.lang.Object] } else { (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] } } /*def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data }*/ override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with ColumnFixer { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) + def reordering_=(allowe:Boolean) = peer.getTableHeader setReorderingAllowed allowe + def reordering:Boolean = peer.getTableHeader.getReorderingAllowed peer.getColumnModel().addColumnModelListener(ColumFixingColumListener(this)) peer.getTableHeader().addMouseListener(ColumnFixingMouseListener(this)) //val groupColour:Option[java.awt.Color] = Some(Color.LIGHT_GRAY) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) //peer.getColumnModel.addColumnModelListener() private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { - columns(convertedColumn(column-1)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) + val c = convertedColumn(column)-1 + if(c >= 0) columns(c).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) + else {/*println("Föhlah: " + c); */new Label("")} } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData }
axelGschaider/PimpedScalaTable
fec12f06d6a2bd8c531110ee56c59ed5a2498433
expansion column is always the first one (still problem with header thoug)
diff --git a/PimpedTable.scala b/PimpedTable.scala index a1e1f85..5d8412c 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,265 +1,303 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter +import javax.swing.event.{ListSelectionEvent, TableColumnModelListener, ChangeEvent, TableColumnModelEvent} +import java.awt.event.{MouseEvent, MouseAdapter} +import java.util.EventObject import java.util.Comparator import java.awt.Color trait Row[A] { val data:A val isExpandable:Boolean = false def expandedData():List[ExpandedData[A]] = List.empty[ExpandedData[A]] var expanded:Boolean = false val internalComparator:Option[Comparator[A]] = None } trait ExpandedData[A] extends Row[A]{ val father:A } +trait ColumnFixer { + def paintExpandColumn:Boolean = false + var columnValue:Int = -1 + var columnNewValue:Int = -1 + def moveColumn(oldIndex:Int, newIndex:Int):Unit +} + +case class ColumFixingColumListener(x: ColumnFixer) extends TableColumnModelListener{ + def columnSelectionChanged(e: ListSelectionEvent) {} + def columnMarginChanged(e: ChangeEvent) {} + def columnMoved(e: TableColumnModelEvent) { + if(x.paintExpandColumn) { + if(x.columnValue == -1) x.columnValue = e.getFromIndex + x.columnNewValue = e.getToIndex + } + } + def columnRemoved(e: TableColumnModelEvent) {} + def columnAdded(e: TableColumnModelEvent) {} +} + +case class ColumnFixingMouseListener(x: ColumnFixer) extends MouseAdapter { + override def mouseReleased(e:MouseEvent) { + if(x.paintExpandColumn) { + if(x.columnValue != -1 && (x.columnValue == 0 && x.columnNewValue == 0)) { + + } + } + } +} + trait ColumnDescription[-A,+B] { val name:String def extractValue(x:A):B val isSortable:Boolean = false val ignoreWhileExpanding:Boolean = false val paintGroupColourWhileExpanding:Boolean = false def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length + expOffset def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } if(paintExpander && column == 0) { data(row).isExpandable.asInstanceOf[java.lang.Object] } else { (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] } } /*def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data }*/ override def getColumnName(column: Int): String = { if(paintExpander && column == 0) { "" } else { columns(column - expOffset).name } } } -class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) +class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) -class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { +class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table with ColumnFixer { private var fallbackDat = initData private var filteredDat = fallbackDat private var expandColumn:Boolean = false - def paintExpandColumn:Boolean = expandColumn + override def paintExpandColumn:Boolean = expandColumn def paintExpandColumn_=(paint:Boolean) = { expandColumn = paint //TODO fallbackData = fallbackData } + def moveColumn(oldIndex:Int, newIndex:Int) = peer.moveColumn(oldIndex, newIndex) + peer.getColumnModel().addColumnModelListener(ColumFixingColumListener(this)) + peer.getTableHeader().addMouseListener(ColumnFixingMouseListener(this)) //val groupColour:Option[java.awt.Color] = Some(Color.LIGHT_GRAY) private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) + //peer.getColumnModel.addColumnModelListener() + private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { if(paintExpandColumn) { if(column == 0) { //TODO new Label() { opaque = true background = Color.RED } } else { columns(convertedColumn(column-1)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } else { columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) } } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) fallbackData = initData }
axelGschaider/PimpedScalaTable
1a2772fa0cc1cf347df9d9ae010c578a6eb0f640
laid basis for expanding
diff --git a/PimpedTable.scala b/PimpedTable.scala index a59b21d..a1e1f85 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,235 +1,265 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator +import java.awt.Color trait Row[A] { val data:A - val isExpandAble:Boolean = false - def expand():List[ExpandedData[A]] = List.empty[ExpandedData[A]] + val isExpandable:Boolean = false + def expandedData():List[ExpandedData[A]] = List.empty[ExpandedData[A]] + var expanded:Boolean = false + val internalComparator:Option[Comparator[A]] = None } trait ExpandedData[A] extends Row[A]{ val father:A } - trait ColumnDescription[-A,+B] { - val name:String; + val name:String + + def extractValue(x:A):B - def extractValue(x:A):B; + val isSortable:Boolean = false - val isSortable:Boolean = false; + val ignoreWhileExpanding:Boolean = false - val ignoreWhileExpanding:Boolean = false; + val paintGroupColourWhileExpanding:Boolean = false - def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component + def renderComponent(data:A, isSelected: Boolean, focused: Boolean, isExpanded: Boolean):Component def comparator: Option[Comparator[_ <: B]] } -class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { +class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]], var paintExpander:Boolean = false) extends AbstractTableModel { private var lokalData = dat + + private def expOffset = if (paintExpander) 1 else 0 def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } - def getRowCount():Int = data.length + def getRowCount():Int = data.length + expOffset - def getColumnCount():Int = columns.length + def getColumnCount():Int = columns.length + expOffset override def getValueAt(row:Int, column:Int): java.lang.Object = { - if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { + if(row < 0 || column < 0 || column >= columns.length + expOffset || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } - //(columns(column) extractValue data(row)).toString - //null - (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] + + if(paintExpander && column == 0) { + data(row).isExpandable.asInstanceOf[java.lang.Object] + } + else { + (columns(column - expOffset) extractValue data(row).data).asInstanceOf[java.lang.Object] + } + } - def getNiceValue(row:Int, column:Int): B = { + /*def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data - } + }*/ - override def getColumnName(column: Int): String = columns(column).name + override def getColumnName(column: Int): String = { + if(paintExpander && column == 0) { + "" + } else { + columns(column - expOffset).name + } + } } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var fallbackDat = initData private var filteredDat = fallbackDat + + private var expandColumn:Boolean = false + def paintExpandColumn:Boolean = expandColumn + def paintExpandColumn_=(paint:Boolean) = { + expandColumn = paint + //TODO + fallbackData = fallbackData + } - private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns) + //val groupColour:Option[java.awt.Color] = Some(Color.LIGHT_GRAY) + + private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns, paintExpandColumn) private var savedFilter:Option[(A => Boolean)] = None //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d - tableModel = new PimpedTableModel(filteredData, columns) + tableModel = new PimpedTableModel(filteredData, columns, paintExpandColumn) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(PimpedTableSelectionEvent(this)) } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } - /*private def triggerDataChange() = { - - }*/ - def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { - //data = dat.filter(x => p(x.data)) savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { - /*data = dat - lokalFiltered = false*/ savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) - } - /*override def publish(e: Event):Unit = { - //println("there something going on") - //blockSelectionEvents = true - super.publish(e) - //blockSelectionEvents = false - }*/ - def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } + private def convertedRow(row:Int) = this.peer.convertRowIndexToModel(row) + private def convertedColumn(column:Int) = this.peer.convertColumnIndexToModel(column) + def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { - columns(column).renderComponent(filteredData(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) + if(paintExpandColumn) { + if(column == 0) { + //TODO + new Label() { + opaque = true + background = Color.RED + } + } + else { + columns(convertedColumn(column-1)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) + } + } else { + columns(convertedColumn(column)).renderComponent(filteredData(convertedRow(row)).data, isSelected, focused, /*TODO*/false) + } } - def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(this.peer.convertRowIndexToModel(i)).data) + def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(convertedRow(i)).data) + + fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 80c98c7..839d972 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,159 +1,160 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true - def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { + def renderComponent(data:Data, isSelected: Boolean, focused: Boolean, isExpanded:Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION - val framewidth = 640 + val framewidth = 480 val frameheight = 480 val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { //println("Test:") + table.paintExpandColumn = !table.paintExpandColumn //table unselectAll// data(0).data*/ - if(table.isFiltered) table.unfilter + /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 - }) + })*/ //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { case PimpedTableSelectionEvent(_) => { println("\nCLICK.") //println(" Adjusting: " + adjusting) //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
173d792ef3e1c564879e84b36a088ac9146686cf
introduced PimpedTableSelectionEvent
diff --git a/PimpedTable.scala b/PimpedTable.scala index 81c46ab..a59b21d 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,232 +1,235 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[ExpandedData[A]] = List.empty[ExpandedData[A]] } trait ExpandedData[A] extends Row[A]{ val father:A } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data } override def getColumnName(column: Int): String = columns(column).name } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) +case class PimpedTableSelectionEvent(s:Table) extends TableEvent(s) + class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var fallbackDat = initData private var filteredDat = fallbackDat private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns) private var savedFilter:Option[(A => Boolean)] = None //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } private def fallbackData = fallbackDat private def fallbackData_=(d:List[Row[A]]) = { fallbackDat = d savedFilter match { case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) case None => filteredData = fallbackData } } def filteredData = filteredDat private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true filteredDat = d tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false - publish(TableRowsSelected(this, Range(0,0), true)) + publish(PimpedTableSelectionEvent(this)) } blockSelectionEvents = false } def data:List[Row[A]] = fallbackData def data_=(da:List[Row[A]])= { fallbackData = da /*var sel = selectedData() blockSelectionEvents = true fallbackData = da //triggerDataChange() tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false*/ } /*private def triggerDataChange() = { }*/ def isFiltered() = savedFilter match { case None => false case Some(_) => true } def filter(p: (A) => Boolean):Unit = { //data = dat.filter(x => p(x.data)) savedFilter = Some(p) filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { /*data = dat lokalFiltered = false*/ savedFilter = None filteredData = fallbackData } def select(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { - case e@TableRowsSelected(_,_,_) => if(!blockSelectionEvents) publish(e) + case e@TableRowsSelected(_,_,true) => if(!blockSelectionEvents) publish(PimpedTableSelectionEvent(this)) + } - override def publish(e: Event):Unit = { + /*override def publish(e: Event):Unit = { //println("there something going on") - blockSelectionEvents = true + //blockSelectionEvents = true super.publish(e) - blockSelectionEvents = false - } + //blockSelectionEvents = false + }*/ def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(filteredData(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(this.peer.convertRowIndexToModel(i)).data) fallbackData = initData } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 21f4f14..80c98c7 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,157 +1,159 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { - /*println("Test:") - table unselectAll// data(0).data*/ + //println("Test:") + //table unselectAll// data(0).data*/ if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 }) + //table.data = (0 to 101).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table/*.selection*/) reactions += { - case TableRowsSelected(`table`, range, adjusting) => { + case PimpedTableSelectionEvent(_) => { println("\nCLICK.") - println(" Adjusting: " + adjusting) - println("range: " + range + "\n") + //println(" Adjusting: " + adjusting) + //println("range: " + range + "\n") table.selectedData.foreach(_ match { case Data(i, s) => println("i:"+i+" s:"+s) }) } + //case _ => println("da ist was faul im Staate Denver") } } }
axelGschaider/PimpedScalaTable
339d8531de3830d136609d89acbf76f53549c07d
refactored so data can be changed from the outside
diff --git a/PimpedTable.scala b/PimpedTable.scala index f78e612..81c46ab 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,193 +1,232 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[ExpandedData[A]] = List.empty[ExpandedData[A]] } trait ExpandedData[A] extends Row[A]{ val father:A } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data } override def getColumnName(column: Int): String = columns(column).name } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) -class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { +class PimpedTable[A, B](initData:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { - private var lokalData = dat - private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(data, columns) - private var lokalFiltered:Boolean = false + private var fallbackDat = initData + private var filteredDat = fallbackDat + + private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(filteredData, columns) + private var savedFilter:Option[(A => Boolean)] = None + + //private var lokalFiltered:Boolean = false private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } + + private def fallbackData = fallbackDat + private def fallbackData_=(d:List[Row[A]]) = { + fallbackDat = d + savedFilter match { + case Some(f) => filteredData = fallbackData.filter(x => f(x.data)) + case None => filteredData = fallbackData + } - def data:List[Row[A]] = lokalData + } - def data_=(d:List[Row[A]])= { + + def filteredData = filteredDat + private def filteredData_= (d:List[Row[A]]) = { var sel = selectedData() blockSelectionEvents = true - lokalData = d - //triggerDataChange() - tableModel = new PimpedTableModel(data, columns) + filteredDat = d + tableModel = new PimpedTableModel(filteredData, columns) this.model = tableModel sorter setModel tableModel fillSorter if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { //System.out.println("something changed") blockSelectionEvents = false publish(TableRowsSelected(this, Range(0,0), true)) } blockSelectionEvents = false } + def data:List[Row[A]] = fallbackData + + def data_=(da:List[Row[A]])= { + fallbackData = da + /*var sel = selectedData() + blockSelectionEvents = true + fallbackData = da + //triggerDataChange() + tableModel = new PimpedTableModel(filteredData, columns) + this.model = tableModel + sorter setModel tableModel + fillSorter + if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { + //System.out.println("something changed") + blockSelectionEvents = false + publish(TableRowsSelected(this, Range(0,0), true)) + } + blockSelectionEvents = false*/ + } + /*private def triggerDataChange() = { }*/ - def isFiltered() = lokalFiltered + def isFiltered() = savedFilter match { + case None => false + case Some(_) => true + } def filter(p: (A) => Boolean):Unit = { - data = dat.filter(x => p(x.data)) - lokalFiltered = true + //data = dat.filter(x => p(x.data)) + savedFilter = Some(p) + filteredData = fallbackData.filter(x => p(x.data)) } def unfilter():Unit = { - data = dat - lokalFiltered = false + /*data = dat + lokalFiltered = false*/ + savedFilter = None + filteredData = fallbackData } def select(x:A):Boolean = { - data.map(_.data).indexOf(x) match { + filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows += i true } } } def unselect(x:A):Boolean = { - data.map(_.data).indexOf(x) match { + filteredData.map(_.data).indexOf(x) match { case -1 => {false} case i => { this.selection.rows -= i true } } } listenTo(this.selection) reactions += { - case e@TableRowsSelected(_,_,_) => if(!blockSelectionEvents) publish(e) + case e@TableRowsSelected(_,_,_) => if(!blockSelectionEvents) publish(e) } override def publish(e: Event):Unit = { //println("there something going on") blockSelectionEvents = true super.publish(e) blockSelectionEvents = false } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { - columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) + columns(column).renderComponent(filteredData(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } - def selectedData():List[A] = this.selection.rows.toList.map(i => data(this.peer.convertRowIndexToModel(i)).data) + def selectedData():List[A] = this.selection.rows.toList.map(i => filteredData(this.peer.convertRowIndexToModel(i)).data) - data = dat + fallbackData = initData }
axelGschaider/PimpedScalaTable
8792424e21f38538da232fd9defcaff4c528be39
listening to table now also reveals a TableRowsSelected that is ONLY fired, when something realy changed
diff --git a/PimpedTable.scala b/PimpedTable.scala index 559e152..f78e612 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,165 +1,193 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable +import scala.swing.event._ import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false - def expand():List[A] = List.empty[A] + def expand():List[ExpandedData[A]] = List.empty[ExpandedData[A]] } - +trait ExpandedData[A] extends Row[A]{ + val father:A +} trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data } override def getColumnName(column: Int): String = columns(column).name } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var lokalData = dat private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(data, columns) private var lokalFiltered:Boolean = false + private var blockSelectionEvents:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { var sel = selectedData() + blockSelectionEvents = true lokalData = d //triggerDataChange() tableModel = new PimpedTableModel(data, columns) this.model = tableModel sorter setModel tableModel fillSorter - sel.foreach(select(_)) + if(sel.size!=0 && !sel.map(select(_)).forall(x => x)) { + //System.out.println("something changed") + blockSelectionEvents = false + publish(TableRowsSelected(this, Range(0,0), true)) + } + blockSelectionEvents = false } /*private def triggerDataChange() = { }*/ def isFiltered() = lokalFiltered def filter(p: (A) => Boolean):Unit = { data = dat.filter(x => p(x.data)) lokalFiltered = true } def unfilter():Unit = { data = dat lokalFiltered = false } - def select(x:A):Unit = { + def select(x:A):Boolean = { data.map(_.data).indexOf(x) match { - case -1 => {} - case i => this.selection.rows += i + case -1 => {false} + case i => { + this.selection.rows += i + true + } } } - def unselect(x:A):Unit = { + def unselect(x:A):Boolean = { data.map(_.data).indexOf(x) match { - case -1 => {} - case i => this.selection.rows -= i + case -1 => {false} + case i => { + this.selection.rows -= i + true + } } } + + listenTo(this.selection) + reactions += { + case e@TableRowsSelected(_,_,_) => if(!blockSelectionEvents) publish(e) + } + + override def publish(e: Event):Unit = { + //println("there something going on") + blockSelectionEvents = true + super.publish(e) + blockSelectionEvents = false + } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } def selectedData():List[A] = this.selection.rows.toList.map(i => data(this.peer.convertRowIndexToModel(i)).data) data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index c19ea8f..21f4f14 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,152 +1,157 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 - val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) + val data:List[RowData] = (0 to 100).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { /*println("Test:") table unselectAll// data(0).data*/ if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 }) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) - listenTo(table.selection) + listenTo(table/*.selection*/) reactions += { case TableRowsSelected(`table`, range, adjusting) => { - + println("\nCLICK.") + println(" Adjusting: " + adjusting) + println("range: " + range + "\n") + table.selectedData.foreach(_ match { + case Data(i, s) => println("i:"+i+" s:"+s) + }) } } } }
axelGschaider/PimpedScalaTable
b1deae51ba9fe5bfad9a88aa280fcd7ceef63105
Keep Selection when ever the data changes (includes filtering)
diff --git a/PimpedTable.scala b/PimpedTable.scala index c20819d..559e152 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,162 +1,165 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data } override def getColumnName(column: Int): String = columns(column).name } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var lokalData = dat private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(data, columns) private var lokalFiltered:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { + var sel = selectedData() lokalData = d - triggerDataChange() - } - - private def triggerDataChange() = { + //triggerDataChange() tableModel = new PimpedTableModel(data, columns) this.model = tableModel sorter setModel tableModel fillSorter + sel.foreach(select(_)) } + /*private def triggerDataChange() = { + + }*/ + def isFiltered() = lokalFiltered def filter(p: (A) => Boolean):Unit = { data = dat.filter(x => p(x.data)) lokalFiltered = true } def unfilter():Unit = { data = dat lokalFiltered = false } def select(x:A):Unit = { data.map(_.data).indexOf(x) match { case -1 => {} case i => this.selection.rows += i } } def unselect(x:A):Unit = { data.map(_.data).indexOf(x) match { case -1 => {} case i => this.selection.rows -= i } } def unselectAll():Unit = this.selection.rows.clear override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } def selectedData():List[A] = this.selection.rows.toList.map(i => data(this.peer.convertRowIndexToModel(i)).data) data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 6b25c3c..c19ea8f 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,152 +1,152 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { - println("Test:") - table unselectAll// data(0).data - /*if(table.isFiltered) table.unfilter + /*println("Test:") + table unselectAll// data(0).data*/ + if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 - })*/ + }) }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
db9aca85653b70e324b4bd92f472fe2cf0f2a994
basic selection manipulation
diff --git a/PimpedTable.scala b/PimpedTable.scala index cba5e06..c20819d 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,146 +1,162 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data } override def getColumnName(column: Int): String = columns(column).name } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var lokalData = dat private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(data, columns) private var lokalFiltered:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } private def triggerDataChange() = { tableModel = new PimpedTableModel(data, columns) this.model = tableModel sorter setModel tableModel fillSorter } def isFiltered() = lokalFiltered def filter(p: (A) => Boolean):Unit = { data = dat.filter(x => p(x.data)) lokalFiltered = true } def unfilter():Unit = { data = dat lokalFiltered = false } + def select(x:A):Unit = { + data.map(_.data).indexOf(x) match { + case -1 => {} + case i => this.selection.rows += i + } + } + + def unselect(x:A):Unit = { + data.map(_.data).indexOf(x) match { + case -1 => {} + case i => this.selection.rows -= i + } + } + + def unselectAll():Unit = this.selection.rows.clear + override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } def selectedData():List[A] = this.selection.rows.toList.map(i => data(this.peer.convertRowIndexToModel(i)).data) data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index c990658..6b25c3c 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,151 +1,152 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { println("Test:") - if(table.isFiltered) table.unfilter + table unselectAll// data(0).data + /*if(table.isFiltered) table.unfilter else table filter (_ match { case Data(i, _) => i%2 == 0 - }) + })*/ }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
4b7983b114dc01aec8129d376d4b76b58ad06703
basic filtering support. ToDo: keep selection
diff --git a/PimpedTable.scala b/PimpedTable.scala index 4aea271..cba5e06 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,140 +1,146 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data } override def getColumnName(column: Int): String = columns(column).name } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var lokalData = dat private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(data, columns) + private var lokalFiltered:Boolean = false val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } private def triggerDataChange() = { tableModel = new PimpedTableModel(data, columns) this.model = tableModel sorter setModel tableModel fillSorter } - /*def filter(p: (RowData[A]) => Boolean):Unit = { - - }*/ + def isFiltered() = lokalFiltered + + def filter(p: (A) => Boolean):Unit = { + data = dat.filter(x => p(x.data)) + lokalFiltered = true + } + + def unfilter():Unit = { + data = dat + lokalFiltered = false + } - /*def unfilter():Unit = { - - }*/ override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } def selectedData():List[A] = this.selection.rows.toList.map(i => data(this.peer.convertRowIndexToModel(i)).data) data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 4279080..c990658 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,150 +1,151 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { println("Test:") - table.selectedData.foreach(_ match { - case Data(i,s) => println("i:" + i + " s:"+s) + if(table.isFiltered) table.unfilter + else table filter (_ match { + case Data(i, _) => i%2 == 0 }) - }) {background = Color.BLUE} + }) , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
cbc4a53916195b9e6dc797a1e4fef7bcf3569f1e
minor changes to license
diff --git a/PimpedTable.scala b/PimpedTable.scala index 6ea7358..4aea271 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,139 +1,140 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. -If you would like to obtain this programm under another license, feel free to contact me: +If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. + axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data } override def getColumnName(column: Int): String = columns(column).name } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var lokalData = dat private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(data, columns) val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } private def triggerDataChange() = { tableModel = new PimpedTableModel(data, columns) this.model = tableModel sorter setModel tableModel fillSorter } /*def filter(p: (RowData[A]) => Boolean):Unit = { }*/ /*def unfilter():Unit = { }*/ override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } def selectedData():List[A] = this.selection.rows.toList.map(i => data(this.peer.convertRowIndexToModel(i)).data) data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 854bbca..4279080 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,150 +1,150 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. -If you would like to obtain this programm under another license, feel free to contact me: +If you would like to obtain this programm under another license, feel free to contact me. Probably I won't charge you for commercial projects. Just would like to receive a courtesy call. axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.opaque = true l.background = Color.BLUE } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { println("Test:") table.selectedData.foreach(_ match { case Data(i,s) => println("i:" + i + " s:"+s) }) }) {background = Color.BLUE} , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
a0f9d79093cddc6a0dad00f596a7595c65335dd3
fixed Label-Rendering Problem in Example
diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 2864833..854bbca 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,151 +1,150 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { + l.opaque = true l.background = Color.BLUE - l.foreground = Color.GREEN - //println(l.text + ": I am elected!!!!!") } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button(Action("Test") { println("Test:") table.selectedData.foreach(_ match { case Data(i,s) => println("i:" + i + " s:"+s) }) - }) + }) {background = Color.BLUE} , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
c63ded1535606be6a58ae2f6e70993647ee14e17
support for selecting data
diff --git a/PimpedTable.scala b/PimpedTable.scala index 5f1c225..6ea7358 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,136 +1,139 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } def getNiceValue(row:Int, column:Int): B = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } columns(column) extractValue data(row).data } override def getColumnName(column: Int): String = columns(column).name } class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var lokalData = dat + private var tableModel:PimpedTableModel[A,B] = new PimpedTableModel(data, columns) val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } private def triggerDataChange() = { - val m = new PimpedTableModel(data, columns) - this.model = m - sorter setModel m + tableModel = new PimpedTableModel(data, columns) + this.model = tableModel + sorter setModel tableModel fillSorter } /*def filter(p: (RowData[A]) => Boolean):Unit = { }*/ /*def unfilter():Unit = { }*/ override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } - + def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } + def selectedData():List[A] = this.selection.rows.toList.map(i => data(this.peer.convertRowIndexToModel(i)).data) + data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 3bb7941..2864833 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,146 +1,151 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.background = Color.BLUE l.foreground = Color.GREEN //println(l.text + ": I am elected!!!!!") } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { - add(new Button("Test"), - new Constraints() { + add(new Button(Action("Test") { + println("Test:") + table.selectedData.foreach(_ match { + case Data(i,s) => println("i:" + i + " s:"+s) + }) + }) + , new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
3453c07671388115630ee57085a9f3e01c84d58e
some convenience stuff
diff --git a/PimpedTable.scala b/PimpedTable.scala index a3b7628..5f1c225 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,135 +1,136 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } + def getNiceValue(row:Int, column:Int): B = { + if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { + throw new Error("Bad Table Index: row " + row + " column " + column) + } + columns(column) extractValue data(row).data + } + override def getColumnName(column: Int): String = columns(column).name } +class ConvenientPimpedTable[A, B](dat:List[A], columns:List[ColumnDescription[A,B]]) extends PimpedTable[A, B](dat.map(x => new Row[A] {val data = x}),columns) class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { + private var lokalData = dat val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } - //def tablePeer:Table = lokalTable - - /*def tablePeer_=(t:Table) = { - lokalTable = t - }*/ - - - private def triggerDataChange() = { val m = new PimpedTableModel(data, columns) this.model = m sorter setModel m fillSorter } /*def filter(p: (RowData[A]) => Boolean):Unit = { }*/ /*def unfilter():Unit = { }*/ override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } data = dat }
axelGschaider/PimpedScalaTable
730979287d2eb589d71283face3ba79c2f2922bf
sorting works. blocking single column from sorting doesn't.
diff --git a/PimpedTable.scala b/PimpedTable.scala index ca31ead..a3b7628 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,150 +1,135 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Option[Comparator[_ <: B]] - } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { - private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } override def getColumnName(column: Int): String = columns(column).name - } class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { - - - private var lokalData = dat val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { colDes.comparator match { case None => {} case Some(c) => sorter.setComparator(i, c) } } } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } //def tablePeer:Table = lokalTable /*def tablePeer_=(t:Table) = { lokalTable = t }*/ private def triggerDataChange() = { val m = new PimpedTableModel(data, columns) this.model = m sorter setModel m fillSorter } /*def filter(p: (RowData[A]) => Boolean):Unit = { }*/ /*def unfilter():Unit = { }*/ override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { - columns(column).renderComponent(data(row).data, isSelected, focused) + columns(column).renderComponent(data(this.peer.convertRowIndexToModel(row)).data, isSelected, focused) } - - - //lokalTable.peer.setAutoCreateRowSorter() - //val sorter = lokalTable.peer.getRowSorter() - - /*columns.zipWithIndex foreach (x => x match { - case (a,i) => sorter.setComparator(i, a.comparator) - } )*/ - data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 0fe2ae8..3bb7941 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,150 +1,146 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.background = Color.BLUE l.foreground = Color.GREEN //println(l.text + ": I am elected!!!!!") } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) - def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } }) } object Test extends SimpleSwingApplication { - def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 - val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x,/* (100-x).toString + */"xxx"))) + val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button("Test"), new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } - - }
axelGschaider/PimpedScalaTable
a2c25604c6ba67eeef1ce22e27a04731fd3b3c4f
changed to Some[Comparator]
diff --git a/PimpedTable.scala b/PimpedTable.scala index 92d1eb8..ca31ead 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,147 +1,150 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component - def comparator: Comparator[_ <: B] + def comparator: Option[Comparator[_ <: B]] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } override def getColumnName(column: Int): String = columns(column).name } class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var lokalData = dat val sorter = new TableRowSorter[PimpedTableModel[A,B]]() this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { - case (colDes,i) => { - sorter.setComparator(i, colDes.comparator)} + case (colDes,i) => { colDes.comparator match { + case None => {} + case Some(c) => sorter.setComparator(i, c) + } } + } } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } //def tablePeer:Table = lokalTable /*def tablePeer_=(t:Table) = { lokalTable = t }*/ private def triggerDataChange() = { val m = new PimpedTableModel(data, columns) this.model = m sorter setModel m fillSorter } /*def filter(p: (RowData[A]) => Boolean):Unit = { }*/ /*def unfilter():Unit = { }*/ override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(row).data, isSelected, focused) } //lokalTable.peer.setAutoCreateRowSorter() //val sorter = lokalTable.peer.getRowSorter() /*columns.zipWithIndex foreach (x => x match { case (a,i) => sorter.setComparator(i, a.comparator) } )*/ data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 31e7cec..0fe2ae8 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,150 +1,150 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.background = Color.BLUE l.foreground = Color.GREEN //println(l.text + ": I am elected!!!!!") } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) - def comparator: Comparator[StringValue] = new Comparator[StringValue] { + def comparator = Some(new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } - } + }) } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) - def comparator: Comparator[IntValue] = new Comparator[IntValue] { + def comparator = Some(new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } - } + }) } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x,/* (100-x).toString + */"xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button("Test"), new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
c21b3d3f4acd6a48606284e1caf6116cc01b7055
Sort test works but soes nothing
diff --git a/PimpedTable.scala b/PimpedTable.scala index e97651a..92d1eb8 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,147 +1,147 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Comparator[_ <: B] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } override def getColumnName(column: Int): String = columns(column).name } class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { private var lokalData = dat val sorter = new TableRowSorter[PimpedTableModel[A,B]]() + this.peer.setRowSorter(sorter) private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { - println("registering in column " + colDes.name + " (" +i+"") sorter.setComparator(i, colDes.comparator)} - }} - + } + } } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } //def tablePeer:Table = lokalTable /*def tablePeer_=(t:Table) = { lokalTable = t }*/ private def triggerDataChange() = { val m = new PimpedTableModel(data, columns) this.model = m sorter setModel m fillSorter } /*def filter(p: (RowData[A]) => Boolean):Unit = { }*/ /*def unfilter():Unit = { }*/ override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(row).data, isSelected, focused) } //lokalTable.peer.setAutoCreateRowSorter() //val sorter = lokalTable.peer.getRowSorter() /*columns.zipWithIndex foreach (x => x match { case (a,i) => sorter.setComparator(i, a.comparator) } )*/ data = dat } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 122abe5..31e7cec 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,150 +1,150 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.background = Color.BLUE l.foreground = Color.GREEN //println(l.text + ": I am elected!!!!!") } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator: Comparator[StringValue] = new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } } } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator: Comparator[IntValue] = new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } } } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 - val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) + val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x,/* (100-x).toString + */"xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { showGrid = true gridColor = Color.BLACK selectionBackground = Color.RED selectionForeground = Color.GREEN } val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button("Test"), new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } val tablePane = new ScrollPane(table) { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded viewportView = table } contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) listenTo(table.selection) reactions += { case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
98e479de26037ca756acc71473d4f52195e3832c
PimpedTable = ScrollPane????????? What was I thinking?
diff --git a/PimpedTable.scala b/PimpedTable.scala index 8fe672d..e97651a 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,151 +1,147 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Comparator[_ <: B] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } override def getColumnName(column: Int): String = columns(column).name } -class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends ScrollPane { +class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends Table { - horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded - verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded + private var lokalData = dat - private var lokalTable = new Table() { - override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { - rendererComponentForPeerTable(isSelected, focused, row, column) - } - } val sorter = new TableRowSorter[PimpedTableModel[A,B]]() private def fillSorter = { columns.zipWithIndex filter {x => x match { case (colDes,_) => colDes.isSortable }} foreach {x => x match { case (colDes,i) => { println("registering in column " + colDes.name + " (" +i+"") sorter.setComparator(i, colDes.comparator)} }} } def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } - def tablePeer:Table = lokalTable + //def tablePeer:Table = lokalTable - def tablePeer_=(t:Table) = { + /*def tablePeer_=(t:Table) = { lokalTable = t - } + }*/ private def triggerDataChange() = { val m = new PimpedTableModel(data, columns) - tablePeer.model = m + this.model = m sorter setModel m fillSorter } /*def filter(p: (RowData[A]) => Boolean):Unit = { }*/ /*def unfilter():Unit = { }*/ + override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { + rendererComponentForPeerTable(isSelected, focused, row, column) + } def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(row).data, isSelected, focused) } //lokalTable.peer.setAutoCreateRowSorter() //val sorter = lokalTable.peer.getRowSorter() /*columns.zipWithIndex foreach (x => x match { case (a,i) => sorter.setComparator(i, a.comparator) } )*/ data = dat - viewportView = tablePeer } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index efb7089..122abe5 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,146 +1,150 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.background = Color.BLUE l.foreground = Color.GREEN //println(l.text + ": I am elected!!!!!") } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) def comparator: Comparator[StringValue] = new Comparator[StringValue] { def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 else if (s1 > s2) 1 else 0 } } } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator: Comparator[IntValue] = new Comparator[IntValue] { def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 else if (i1 > i2) 1 else 0 } } } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { - tablePeer.showGrid = true - tablePeer.gridColor = Color.BLACK - tablePeer.selectionBackground = Color.RED - tablePeer.selectionForeground = Color.GREEN + showGrid = true + gridColor = Color.BLACK + selectionBackground = Color.RED + selectionForeground = Color.GREEN } - val theRealTable = table.tablePeer val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button("Test"), new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } + + val tablePane = new ScrollPane(table) { + horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded + verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded + viewportView = table + } + contents = new SplitPane(Orientation.Vertical, buttonPannel, tablePane) - contents = new SplitPane(Orientation.Vertical, buttonPannel, table) - - listenTo(theRealTable.selection) + listenTo(table.selection) reactions += { - case TableRowsSelected(`theRealTable`, range, adjusting) => { + case TableRowsSelected(`table`, range, adjusting) => { } } } }
axelGschaider/PimpedScalaTable
5355d614163e0bdbbf56779309a8cc42f5ed219c
here comes sorting
diff --git a/PimpedTable.scala b/PimpedTable.scala index f599466..8fe672d 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,123 +1,151 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable import javax.swing.table.AbstractTableModel +import javax.swing.table.TableRowSorter import java.util.Comparator trait Row[A] { val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; val ignoreWhileExpanding:Boolean = false; def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component def comparator: Comparator[_ <: B] } class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { private var lokalData = dat def data = lokalData def data_=(d: List[Row[A]]) = { lokalData = d } def getRowCount():Int = data.length def getColumnCount():Int = columns.length override def getValueAt(row:Int, column:Int): java.lang.Object = { if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { throw new Error("Bad Table Index: row " + row + " column " + column) } //(columns(column) extractValue data(row)).toString //null (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] } override def getColumnName(column: Int): String = columns(column).name } class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends ScrollPane { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded private var lokalData = dat private var lokalTable = new Table() { override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { rendererComponentForPeerTable(isSelected, focused, row, column) } } + val sorter = new TableRowSorter[PimpedTableModel[A,B]]() + + private def fillSorter = { + columns.zipWithIndex filter {x => x match { + case (colDes,_) => colDes.isSortable + }} foreach {x => x match { + case (colDes,i) => { + println("registering in column " + colDes.name + " (" +i+"") + sorter.setComparator(i, colDes.comparator)} + }} + + } + def data:List[Row[A]] = lokalData def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } def tablePeer:Table = lokalTable def tablePeer_=(t:Table) = { lokalTable = t } + + private def triggerDataChange() = { - tablePeer.model = new PimpedTableModel(data, columns) + val m = new PimpedTableModel(data, columns) + tablePeer.model = m + sorter setModel m + fillSorter } /*def filter(p: (RowData[A]) => Boolean):Unit = { }*/ /*def unfilter():Unit = { }*/ def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { columns(column).renderComponent(data(row).data, isSelected, focused) } + + + + //lokalTable.peer.setAutoCreateRowSorter() + //val sorter = lokalTable.peer.getRowSorter() + + /*columns.zipWithIndex foreach (x => x match { + case (a,i) => sorter.setComparator(i, a.comparator) + } )*/ data = dat viewportView = tablePeer } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 8d4524f..efb7089 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,120 +1,146 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ import scala.swing.GridBagPanel.Fill +import event._ import java.awt.Color import java.util.Comparator case class Data(i:Int, s:String) sealed trait Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value case class RowData(data:Data) extends Row[Data] sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => s1 > s2 }*/ + + override val isSortable = true def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { val l = new Label() extractValue(data) match { case StringValue(s) => l.text = s case IntValue(i) => l.text = i.toString } if(isSelected) { l.background = Color.BLUE + l.foreground = Color.GREEN + //println(l.text + ": I am elected!!!!!") } l } } case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) - def comparator: Comparator[StringValue] = null + def comparator: Comparator[StringValue] = new Comparator[StringValue] { + def compare(o1:StringValue, o2:StringValue):Int = (o1,o2) match { + case (StringValue(s1), StringValue(s2)) => if(s1 < s2) -1 + else if (s1 > s2) 1 + else 0 + } + } } case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) def comparator: Comparator[IntValue] = new Comparator[IntValue] { - def compare(o1:IntValue, o2:IntValue):Int = 0 + def compare(o1:IntValue, o2:IntValue):Int = (o1,o2) match { + case (IntValue(i1), IntValue(i2)) => if(i1 < i2) -1 + else if (i1 > i2) 1 + else 0 + } } } object Test extends SimpleSwingApplication { def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 - val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, x.toString + "xxx"))) + val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, (100-x).toString + "xxx"))) val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) val table = new PimpedTable(data, columns) { tablePeer.showGrid = true tablePeer.gridColor = Color.BLACK + tablePeer.selectionBackground = Color.RED + tablePeer.selectionForeground = Color.GREEN } + + val theRealTable = table.tablePeer val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) val buttonPannel = new GridBagPanel() { add(new Button("Test"), new Constraints() { grid = (0,0) gridheight = 1 gridwidth = 1 weightx = 1 weighty = 1 fill = Fill.Both }) } contents = new SplitPane(Orientation.Vertical, buttonPannel, table) + + listenTo(theRealTable.selection) + reactions += { + case TableRowsSelected(`theRealTable`, range, adjusting) => { + + } + } } }
axelGschaider/PimpedScalaTable
9a9eee2bafefe3c3922c571aace0a81a02492693
after lots of type-, variant- and type-boundery-questions ;)
diff --git a/PimpedTable.scala b/PimpedTable.scala index c6e2c3f..f599466 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,79 +1,123 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ import javax.swing.JTable +import javax.swing.table.AbstractTableModel +import java.util.Comparator -trait RowData[A] { +trait Row[A] { + val data:A val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } -trait ColumnDescription[A,B] { + + + +trait ColumnDescription[-A,+B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; - def firstIsBigger(x:B, y:B):Boolean; + val ignoreWhileExpanding:Boolean = false; - def firstValueIsBigger(x:A, y:A):Boolean = firstIsBigger(extractValue(x), extractValue(y)) + def renderComponent(data:A, isSelected: Boolean, focused: Boolean):Component - val ignoreWhileExpanding:Boolean = false; + def comparator: Comparator[_ <: B] } +class PimpedTableModel[A,B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends AbstractTableModel { + + private var lokalData = dat + + def data = lokalData + + def data_=(d: List[Row[A]]) = { + lokalData = d + } + + def getRowCount():Int = data.length + def getColumnCount():Int = columns.length -class PimpedTable[A, B](dat:List[RowData[A]], columns:List[ColumnDescription[A,B]]) extends ScrollPane { + + override def getValueAt(row:Int, column:Int): java.lang.Object = { + if(row < 0 || column < 0 || column >= columns.length || row >= data.length) { + throw new Error("Bad Table Index: row " + row + " column " + column) + } + //(columns(column) extractValue data(row)).toString + //null + (columns(column) extractValue data(row).data).asInstanceOf[java.lang.Object] + } + + override def getColumnName(column: Int): String = columns(column).name + +} + + +class PimpedTable[A, B](dat:List[Row[A]], columns:List[ColumnDescription[A,B]]) extends ScrollPane { horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded private var lokalData = dat - private var lokalTable = new Table() + private var lokalTable = new Table() { + override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { + rendererComponentForPeerTable(isSelected, focused, row, column) + } + } - def data:List[RowData[A]] = lokalData + def data:List[Row[A]] = lokalData - def data_=(d:List[RowData[A]])= { + def data_=(d:List[Row[A]])= { lokalData = d triggerDataChange() } def tablePeer:Table = lokalTable def tablePeer_=(t:Table) = { lokalTable = t } private def triggerDataChange() = { - + tablePeer.model = new PimpedTableModel(data, columns) } - def filter(p: (RowData[A]) => Boolean):Unit = { + /*def filter(p: (RowData[A]) => Boolean):Unit = { - } + }*/ - def unfilter():Unit = { + /*def unfilter():Unit = { + }*/ + + def rendererComponentForPeerTable(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = { + columns(column).renderComponent(data(row).data, isSelected, focused) } + + data = dat + viewportView = tablePeer } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 6e06e40..8d4524f 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,81 +1,120 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ import scala.swing._ +import scala.swing.GridBagPanel.Fill +import java.awt.Color +import java.util.Comparator -case class Container(n:Int, s:String) -sealed abstract class Value -case class IntValue(i:Int) extends Value -case class StringValue(s:String) extends Value +case class Data(i:Int, s:String) -case class Data(i:Int, s:String) extends RowData[Data] { - override val isExpandAble = true; - override def expand() = (1 to 5).toList.map(x => Data(i, s+x.toString)) -} +sealed trait Value + +case class IntValue(i:Int) extends Value +case class StringValue(s:String) extends Value + +case class RowData(data:Data) extends Row[Data] + +sealed trait MyColumns[+Value] extends ColumnDescription[Data, Value] { + /*def firstIsBigger(x:Data, y:Data) = (this extractValue x,this extractValue y) match { + case (IntValue(i1), IntValue(i2)) => i1 > i2 + case (StringValue(s1), StringValue(s2)) => s1 > s2 + }*/ + + def renderComponent(data:Data, isSelected: Boolean, focused: Boolean):Component = { + + val l = new Label() + extractValue(data) match { + case StringValue(s) => l.text = s + case IntValue(i) => l.text = i.toString + } + if(isSelected) { + l.background = Color.BLUE + } + l -sealed abstract class MyColumns[Data, Value] extends ColumnDescription[Data, Value] { - def firstIsBigger(x:Value, y:Value) = (x, y) match { - case (IntValue(i1), IntValue(i2)) => i1 > i2 - case (StringValue(s1), StringValue(s2)) => true - case _ => false } -} +} -case class StringColumn(val name:String) extends MyColumns[Data, Value] { +case class StringColumn(name:String) extends MyColumns[StringValue] { def extractValue(x:Data) = StringValue(x.s) + + def comparator: Comparator[StringValue] = null + } -case class IntColumn(val name:String) extends MyColumns[Data, Value] { +case class IntColumn(name:String) extends MyColumns[IntValue] { def extractValue(x:Data) = IntValue(x.i) - override val ignoreWhileExpanding = true + + def comparator: Comparator[IntValue] = new Comparator[IntValue] { + + def compare(o1:IntValue, o2:IntValue):Int = 0 + } + } + object Test extends SimpleSwingApplication { - + def top = new MainFrame { title = "Table Test" //DO SOME INIT //MainFleetSummaryDistributer registerClient this //SET SIZE AND LOCATION val framewidth = 640 val frameheight = 480 - val data = (0 to 10).toList.map(x => Data(x, x.toString + "xxx")) - val columns = IntColumn("some int") :: StringColumn("some string") :: List.empty[MyColumns[Data,Value]] - val table = new PimpedTable(data, columns) - + val data:List[RowData] = (0 to 50).toList.map(x => RowData(Data(x, x.toString + "xxx"))) + val columns:List[MyColumns[Value]] = List(new IntColumn("some int"), new StringColumn("some string") ) + val table = new PimpedTable(data, columns) { + tablePeer.showGrid = true + tablePeer.gridColor = Color.BLACK + } + val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) minimumSize = new java.awt.Dimension(framewidth, frameheight) - - contents = table - + + val buttonPannel = new GridBagPanel() { + add(new Button("Test"), + new Constraints() { + grid = (0,0) + gridheight = 1 + gridwidth = 1 + weightx = 1 + weighty = 1 + fill = Fill.Both + }) + } + + contents = new SplitPane(Orientation.Vertical, buttonPannel, table) + } }
axelGschaider/PimpedScalaTable
b87a4e9624d61e0ca51c8bb97e12ff5f3825d9e0
started to fill main class Test Programm "ready"
diff --git a/PimpedTable.scala b/PimpedTable.scala index 90d2c07..c6e2c3f 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,47 +1,79 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable import scala.swing._ +import javax.swing.JTable -trait ColumnData[A] { +trait RowData[A] { val isExpandAble:Boolean = false def expand():List[A] = List.empty[A] } trait ColumnDescription[A,B] { val name:String; def extractValue(x:A):B; val isSortable:Boolean = false; def firstIsBigger(x:B, y:B):Boolean; def firstValueIsBigger(x:A, y:A):Boolean = firstIsBigger(extractValue(x), extractValue(y)) val ignoreWhileExpanding:Boolean = false; } -class PimpedTable[A, B](data:List[ColumnData[A]], columns:List[ColumnDescription[A,B]]) { - + + +class PimpedTable[A, B](dat:List[RowData[A]], columns:List[ColumnDescription[A,B]]) extends ScrollPane { + + horizontalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded + verticalScrollBarPolicy = scala.swing.ScrollPane.BarPolicy.AsNeeded + + private var lokalData = dat + private var lokalTable = new Table() + + def data:List[RowData[A]] = lokalData + + def data_=(d:List[RowData[A]])= { + lokalData = d + triggerDataChange() + } + + def tablePeer:Table = lokalTable + + def tablePeer_=(t:Table) = { + lokalTable = t + } + private def triggerDataChange() = { + + } + + def filter(p: (RowData[A]) => Boolean):Unit = { + + } + + def unfilter():Unit = { + + } } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index 7787cc4..6e06e40 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,62 +1,81 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ import at.axelGschaider.pimpedTable._ +import scala.swing._ case class Container(n:Int, s:String) sealed abstract class Value case class IntValue(i:Int) extends Value case class StringValue(s:String) extends Value -case class Data(i:Int, s:String) extends ColumnData[Data] { +case class Data(i:Int, s:String) extends RowData[Data] { override val isExpandAble = true; override def expand() = (1 to 5).toList.map(x => Data(i, s+x.toString)) } sealed abstract class MyColumns[Data, Value] extends ColumnDescription[Data, Value] { def firstIsBigger(x:Value, y:Value) = (x, y) match { case (IntValue(i1), IntValue(i2)) => i1 > i2 case (StringValue(s1), StringValue(s2)) => true case _ => false } } case class StringColumn(val name:String) extends MyColumns[Data, Value] { def extractValue(x:Data) = StringValue(x.s) } case class IntColumn(val name:String) extends MyColumns[Data, Value] { def extractValue(x:Data) = IntValue(x.i) override val ignoreWhileExpanding = true } +object Test extends SimpleSwingApplication { + + def top = new MainFrame { + title = "Table Test" + + //DO SOME INIT + //MainFleetSummaryDistributer registerClient this -object Test { - val data = (0 to 10).toList.map(x => Data(x, x.toString + "xxx")) - val columns = IntColumn("some int") :: StringColumn("some string") :: List.empty[MyColumns[Data,Value]] - //val table = new PimpedTable(data, TheStringColumn :: TheIntColumn :: List[ColumnDescription[Data, Value]].empty) - //val t = new PimpedTable(data,List.empty[ColumnDescription[Data,Value]] ++ TheIntColumn) - val table = new PimpedTable(data, columns) + //SET SIZE AND LOCATION + val framewidth = 640 + val frameheight = 480 + + val data = (0 to 10).toList.map(x => Data(x, x.toString + "xxx")) + val columns = IntColumn("some int") :: StringColumn("some string") :: List.empty[MyColumns[Data,Value]] + val table = new PimpedTable(data, columns) + + val screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize() + location = new java.awt.Point((screenSize.width - framewidth)/2, (screenSize.height - frameheight)/2) + minimumSize = new java.awt.Dimension(framewidth, frameheight) + + contents = table + + } + + } diff --git a/makefile b/makefile index 9a1b094..1dce372 100644 --- a/makefile +++ b/makefile @@ -1,18 +1,20 @@ SC = scalac FSC = fsc all: fsc -deprecation *.scala full: find . -name "*.class" | xargs rm -f fsc -deprecation *.scala clean: find . -name "*.class" | xargs rm -f test: - scala -cp .:./lib/log4j-1.2.16.jar:./lib/opencsv-2.2.jar at.mbm.trending.client.Main + find . -name "*.class" | xargs rm -f + fsc -deprecation *.scala + scala Test
axelGschaider/PimpedScalaTable
19687d6e43682c4e8fe97a1047d1506f32241816
basic structure
diff --git a/PimpedTable.scala b/PimpedTable.scala index 9efa853..90d2c07 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,25 +1,47 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable +import scala.swing._ +trait ColumnData[A] { + val isExpandAble:Boolean = false + def expand():List[A] = List.empty[A] +} + +trait ColumnDescription[A,B] { + val name:String; + + def extractValue(x:A):B; + + val isSortable:Boolean = false; + + def firstIsBigger(x:B, y:B):Boolean; + + def firstValueIsBigger(x:A, y:A):Boolean = firstIsBigger(extractValue(x), extractValue(y)) -class PimpedTable { + val ignoreWhileExpanding:Boolean = false; + +} + +class PimpedTable[A, B](data:List[ColumnData[A]], columns:List[ColumnDescription[A,B]]) { + + } diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index d43731c..7787cc4 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -1,17 +1,62 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ +import at.axelGschaider.pimpedTable._ + +case class Container(n:Int, s:String) + +sealed abstract class Value + +case class IntValue(i:Int) extends Value +case class StringValue(s:String) extends Value + +case class Data(i:Int, s:String) extends ColumnData[Data] { + override val isExpandAble = true; + override def expand() = (1 to 5).toList.map(x => Data(i, s+x.toString)) +} + + + + +sealed abstract class MyColumns[Data, Value] extends ColumnDescription[Data, Value] { + def firstIsBigger(x:Value, y:Value) = (x, y) match { + case (IntValue(i1), IntValue(i2)) => i1 > i2 + case (StringValue(s1), StringValue(s2)) => true + case _ => false + } +} + + +case class StringColumn(val name:String) extends MyColumns[Data, Value] { + def extractValue(x:Data) = StringValue(x.s) +} + +case class IntColumn(val name:String) extends MyColumns[Data, Value] { + def extractValue(x:Data) = IntValue(x.i) + override val ignoreWhileExpanding = true +} + + +object Test { + val data = (0 to 10).toList.map(x => Data(x, x.toString + "xxx")) + val columns = IntColumn("some int") :: StringColumn("some string") :: List.empty[MyColumns[Data,Value]] + //val table = new PimpedTable(data, TheStringColumn :: TheIntColumn :: List[ColumnDescription[Data, Value]].empty) + //val t = new PimpedTable(data,List.empty[ColumnDescription[Data,Value]] ++ TheIntColumn) + val table = new PimpedTable(data, columns) +} + +
axelGschaider/PimpedScalaTable
6465d65e6995ff8e84f50376a55be09c16db6de8
makefile
diff --git a/makefile b/makefile new file mode 100644 index 0000000..9a1b094 --- /dev/null +++ b/makefile @@ -0,0 +1,18 @@ + +SC = scalac +FSC = fsc + +all: + fsc -deprecation *.scala + +full: + find . -name "*.class" | xargs rm -f + fsc -deprecation *.scala + +clean: + find . -name "*.class" | xargs rm -f + +test: + scala -cp .:./lib/log4j-1.2.16.jar:./lib/opencsv-2.2.jar at.mbm.trending.client.Main + +
axelGschaider/PimpedScalaTable
94d063f84f46c287ed334427d7d13e26a3ebc85f
makefile
diff --git a/PimpedTable.scala b/PimpedTable.scala index df9bd7c..9efa853 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -1,21 +1,25 @@ /* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table Copyright (C) 2010 Axel Gschaider This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. If you would like to obtain this programm under another license, feel free to contact me: axel[dot]gschaider[at]gmx[dot]at or http://github.com/axelGschaider */ package at.axelGschaider.pimpedTable +class PimpedTable { + +} +
axelGschaider/PimpedScalaTable
9dbb14fbc0817ebc6490f046f6b476bac7778a22
License stuff
diff --git a/PimpedTable.scala b/PimpedTable.scala index e69de29..df9bd7c 100644 --- a/PimpedTable.scala +++ b/PimpedTable.scala @@ -0,0 +1,21 @@ +/* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table + + +Copyright (C) 2010 Axel Gschaider + +This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. + + +If you would like to obtain this programm under another license, feel free to contact me: +axel[dot]gschaider[at]gmx[dot]at +or http://github.com/axelGschaider +*/ + +package at.axelGschaider.pimpedTable + + + diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala index e69de29..d43731c 100644 --- a/PimpedTableTest.scala +++ b/PimpedTableTest.scala @@ -0,0 +1,17 @@ +/* PimpedScalaTable is a wrapper arround scalas swing.table or Javas JTable (haven't decided jet ;) ) that is meant to evercome all shortcomings I find lacking in scalas swing.table + + +Copyright (C) 2010 Axel Gschaider + +This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. + + +If you would like to obtain this programm under another license, feel free to contact me: +axel[dot]gschaider[at]gmx[dot]at +or http://github.com/axelGschaider +*/ +
axelGschaider/PimpedScalaTable
ffa468adfce545e2ebd2e111b72a99ad7dc5c494
License stuff
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>.
axelGschaider/PimpedScalaTable
e239cada162b858ea8275feeec9fd01ed121dd22
Created the 2 main (and possibly only?) files
diff --git a/PimpedTable.scala b/PimpedTable.scala new file mode 100644 index 0000000..e69de29 diff --git a/PimpedTableTest.scala b/PimpedTableTest.scala new file mode 100644 index 0000000..e69de29
jgknight/Beautiful-Day
70c447e633f089340c0277fea546f072169b27f4
added readme, changed URL
diff --git a/README b/README new file mode 100644 index 0000000..bceadd0 --- /dev/null +++ b/README @@ -0,0 +1,3 @@ +Beautiful Day theme by Arcsin.se Ported to Drupal by Noobbox.com + +For Drupal 6.x diff --git a/noobbox_beautifulday.info b/noobbox_beautifulday.info index 2a90f48..14e4f4a 100644 --- a/noobbox_beautifulday.info +++ b/noobbox_beautifulday.info @@ -1,13 +1,13 @@ name = Beautiful Day screenshot = screenshot.png -description = Beautiful Day theme by Arcsin.com. Ported to Drupal by Noobbox.com +description = Beautiful Day theme by Arcsin.se. Ported to Drupal by Noobbox.com version = VERSION core = 6.x engine = phptemplate stylesheets[all][] = style.css stylesheets[print][] = print.css regions[right] = Right sidebar regions[content] = Content regions[header] = Header regions[footer] = Footer regions[rightbox] = Right box
andrewle/tangovoice
834250380ac614f091211d0ebce434a9ee3edb47
Added analytics
diff --git a/template.html b/template.html index b2e5749..e2f5dbe 100644 --- a/template.html +++ b/template.html @@ -1,272 +1,286 @@ <!DOCTYPE HTML> <html> <head> {block:IndexPage} <title>{Title}</title> <meta name="description" content="{MetaDescription}"> {/block:IndexPage} {block:PostSummary}<title>{PostSummary}</title>{/block:PostSummary} <meta name="viewport" content="width=848"> <meta name="if:Elsewhere" content="0"> <meta name="text:Elsewhere 1 Name" content=""> <meta name="text:Elsewhere 1 URL" content=""> <meta name="text:Elsewhere 2 Name" content=""> <meta name="text:Elsewhere 2 URL" content=""> <meta name="text:Elsewhere 3 Name" content=""> <meta name="text:Elsewhere 3 URL" content=""> <meta name="text:Elsewhere 4 Name" content=""> <meta name="text:Elsewhere 4 URL" content=""> <meta name="text:Elsewhere 5 Name" content=""> <meta name="text:Elsewhere 5 URL" content=""> <meta name="text:Elsewhere 6 Name" content=""> <meta name="text:Elsewhere 6 URL" content=""> <meta name="text:Tagline" content="Your awesome tagline"> + <meta name="text:Google Analytics ID" content=""> <meta name="text:Disqus Shortname" content=""> <link rel="shortcut icon" href="{Favicon}"> <link rel="alternate" href="{RSS}" type="application/rss+xml"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/A1Ukkwf8p/reset.css" type="text/css"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/Nunksbfhp/oldie.css" type="text/css"> <style type="text/css" media="screen"> #inner-sidebar .top { margin: 0 0 25px; } #disqus_thread { margin: 0 0 30px 0 !important; } #nav, .more ul { list-style: none; margin: 0; padding: 0; } .meta + .meta { margin-top: 0; } {CustomCSS} </style> <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function () { $('.meta.posted-by').each(function () { $(this).text($(this).text().replace('andymism', 'Andrew')); $(this).text($(this).text().replace('thisrmykitten', 'Kara')); }); }); </script> + {block:IfGoogleAnalyticsID} + <script type="text/javascript"> + var _gaq = _gaq || []; + _gaq.push(['_setAccount', '{text:Google Analytics ID}']); + _gaq.push(['_trackPageview']); + + (function() { + var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); + })(); + </script> + {/block:IfGoogleAnalyticsID} </head> <body> <div id="main"> <div id="inner"> <div id="header"> <h1><a href="/">{Title}</a></h1> {block:IfTagline}<div class="tagline">{text:Tagline}</div>{/block:IfTagline} </div> <div id="sidebar"> <div id="inner-sidebar"> <div class="top"> <h3>Navigation</h3> <ul id="nav"> <li><a href="http://tangovoice.com/">Home</a></li> <li><a href="http://tangovoice.com/archive">Archive</a></li> {block:HasPages} {block:Pages}<li><a href="{URL}">{Label}</a></li>{/block:Pages} {/block:HasPages} <li><a href="http://tangovoice.com/rss">RSS</a></li> </ul> <div class="clear"></div> </div> <div id="authorbox"> <h3>About</h3> {Description} <div class="clear"></div> </div> {block:IfElsewhere} <div class="more"> <h3>Elsewhere</h3> <p> {block:IfElsewhere1Name}<a href="{text:Elsewhere 1 URL}">{text:Elsewhere 1 Name}</a> <br/>{/block:IfElsewhere1Name} {block:IfElsewhere2Name}<a href="{text:Elsewhere 2 URL}">{text:Elsewhere 2 Name}</a> <br/>{/block:IfElsewhere2Name} {block:IfElsewhere3Name}<a href="{text:Elsewhere 3 URL}">{text:Elsewhere 3 Name}</a> <br/>{/block:IfElsewhere3Name} {block:IfElsewhere4Name}<a href="{text:Elsewhere 4 URL}">{text:Elsewhere 4 Name}</a> <br/>{/block:IfElsewhere4Name} {block:IfElsewhere5Name}<a href="{text:Elsewhere 5 URL}">{text:Elsewhere 5 Name}</a> <br/>{/block:IfElsewhere5Name} {block:IfElsewhere6Name}<a href="{text:Elsewhere 6 URL}">{text:Elsewhere 6 Name}</a> <br/>{/block:IfElsewhere6Name} </p> <div class="clear"></div> </div> {/block:IfElsewhere} <div class="more"> <h3>Links</h3> <ul> {block:Posts} {block:Link} <li> <a href="{URL}" title="{Name}">{name}</a> {block:Description}<div class="content">{Description}</div>{/block:Description} </li> {/block:Link} {/block:Posts} </ul> </div> </div> </div> <div id="entries"> {block:SearchPage} <div id="fake-post" class="entry"> <div class="content">{block:NoSearchResults}Terribly sorry, a total of {/block:NoSearchResults}<strong>{SearchResultCount}</strong> result(s) for <strong>{SearchQuery}</strong></div> </div> {/block:SearchPage} {block:TagPage} <div id="fake-post" class="entry"> <div class="content">Posts tagged <strong>{Tag}</strong></div> </div> {/block:TagPage} {block:Posts} {block:Text} <div id="post-{PostID}" class="entry text"> {block:Title}<h2><a href="{Permalink}" rel="permalink">{Title}</a></h2>{/block:Title} <div class="content">{Body}</div> <div class="meta posted-by">Posted by {PostAuthorName}</div> <div class="meta">{block:Date}{DayOfWeek}, {Month} {DayOfMonth}, {Year}{/block:Date}{block:NoteCount} &mdash; <a href="{Permalink}#notes">{NoteCountWithLabel}</a>{/block:NoteCount}{block:Date}{block:IfDisqusShortname}&nbsp;&nbsp;&nbsp;(<a href="{Permalink}#disqus_thread"></a>){/block:IfDisqusShortname}{/block:Date}{block:More}&nbsp;&nbsp;&nbsp;<a href="{Permalink}">Read more &hellip;</a>{/block:More}</div> </div> {/block:Text} {block:Photo} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{LinkOpenTag}<img src="{PhotoURL-500}" alt="{PhotoAlt}">{LinkCloseTag}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photo} {block:Photoset} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Photoset-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photoset} {block:Quote} <div id="post-{PostID}" class="entry quote"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2>{Quote}</h2> {block:Source}<div class="content">{Source}</div>{/block:Source} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Quote} {block:Chat} <div id="post-{PostID}" class="entry chat"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> {block:Title}<h2>{Title}</h2>{/block:Title} <div class="content"> <ul> {block:Lines}<li class="{Alt}">{block:Label}<span class="label">{Label}</span> {/block:Label}{Line}</li>{/block:Lines} </ul> </div> <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Chat} {block:Audio} <div id="post-{PostID}" class="entry audio"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{AudioPlayerWhite}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Audio} {block:Video} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Video-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Video} {/block:Posts} {block:Permalink} {block:IfDisqusShortname} <div id="disqus_thread"></div> <script type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/embed.js"></script> <noscript><a href="http://{text:Disqus Shortname}.disqus.com/?url=ref">View the discussion thread.</a></noscript> {/block:IfDisqusShortname} {/block:Permalink} {block:PostNotes} <div id="notes"> {PostNotes} </div> {/block:PostNotes} {block:Pagination} <div class="page-navigation"> {block:PreviousPage}<div class="left"><a href="{PreviousPage}">&larr; Previous page</a></div>{/block:PreviousPage} {block:NextPage}<div class="right"><a href="{NextPage}">Next page &rarr;</a></div>{/block:NextPage} <div class="clear"></div> </div> {/block:Pagination} {block:PermalinkPagination} <div class="page-navigation"> {block:PreviousPost}<div class="left"><a href="{PreviousPost}">&larr; Previous post</a></div>{/block:PreviousPost} {block:NextPost}<div class="right"><a href="{NextPost}">Next post &rarr;</a></div>{/block:NextPost} <div class="clear"></div> </div> {/block:PermalinkPagination} </div> <div class="clear"></div> </div> <div id="footer"> <form class="search-footer" action="/search" method="get"> <input class="search-query" type="text" name="q" value="{SearchQuery}"><input class="button" type="submit" value="Search"> </form> <div class="actual-footer"> <p><a href="{RSS}">RSS</a>, <a href="/archive">Archive</a>. We love <a href="http://www.tumblr.com/">Tumblr</a>. Theme (<a href="http://www.tumblr.com/theme/3292">Stationery</a>) by <a href="http://thijsjacobs.com/">Thijs</a></p> </div> <div class="clear"></div> </div> </div> {block:IfDisqusShortname} <script type="text/javascript"> //<![CDATA[ (function() { var links = document.getElementsByTagName('a'); var query = '?'; for(var i = 0; i < links.length; i++) { if(links[i].href.indexOf('#disqus_thread') >= 0) { query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; } } document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/get_num_replies.js' + query + '"></' + 'script>'); })(); //]]> </script> {/block:IfDisqusShortname} </body> </html> \ No newline at end of file
andrewle/tangovoice
963ca64dfa66844e99514701c7d98f284dc94007
Moved links to the sidebar. Need to make a JS widget for it instead though
diff --git a/template.html b/template.html index 0a0a7a4..b2e5749 100644 --- a/template.html +++ b/template.html @@ -1,268 +1,272 @@ <!DOCTYPE HTML> <html> <head> {block:IndexPage} <title>{Title}</title> <meta name="description" content="{MetaDescription}"> {/block:IndexPage} {block:PostSummary}<title>{PostSummary}</title>{/block:PostSummary} <meta name="viewport" content="width=848"> <meta name="if:Elsewhere" content="0"> <meta name="text:Elsewhere 1 Name" content=""> <meta name="text:Elsewhere 1 URL" content=""> <meta name="text:Elsewhere 2 Name" content=""> <meta name="text:Elsewhere 2 URL" content=""> <meta name="text:Elsewhere 3 Name" content=""> <meta name="text:Elsewhere 3 URL" content=""> <meta name="text:Elsewhere 4 Name" content=""> <meta name="text:Elsewhere 4 URL" content=""> <meta name="text:Elsewhere 5 Name" content=""> <meta name="text:Elsewhere 5 URL" content=""> <meta name="text:Elsewhere 6 Name" content=""> <meta name="text:Elsewhere 6 URL" content=""> <meta name="text:Tagline" content="Your awesome tagline"> <meta name="text:Disqus Shortname" content=""> <link rel="shortcut icon" href="{Favicon}"> <link rel="alternate" href="{RSS}" type="application/rss+xml"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/A1Ukkwf8p/reset.css" type="text/css"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/Nunksbfhp/oldie.css" type="text/css"> <style type="text/css" media="screen"> #inner-sidebar .top { margin: 0 0 25px; } #disqus_thread { margin: 0 0 30px 0 !important; } - #nav { + #nav, .more ul { list-style: none; margin: 0; padding: 0; } .meta + .meta { margin-top: 0; } {CustomCSS} </style> <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function () { $('.meta.posted-by').each(function () { $(this).text($(this).text().replace('andymism', 'Andrew')); $(this).text($(this).text().replace('thisrmykitten', 'Kara')); }); }); </script> </head> <body> <div id="main"> <div id="inner"> <div id="header"> <h1><a href="/">{Title}</a></h1> {block:IfTagline}<div class="tagline">{text:Tagline}</div>{/block:IfTagline} </div> <div id="sidebar"> <div id="inner-sidebar"> <div class="top"> <h3>Navigation</h3> <ul id="nav"> <li><a href="http://tangovoice.com/">Home</a></li> <li><a href="http://tangovoice.com/archive">Archive</a></li> {block:HasPages} {block:Pages}<li><a href="{URL}">{Label}</a></li>{/block:Pages} {/block:HasPages} <li><a href="http://tangovoice.com/rss">RSS</a></li> </ul> <div class="clear"></div> </div> <div id="authorbox"> <h3>About</h3> {Description} <div class="clear"></div> </div> {block:IfElsewhere} <div class="more"> <h3>Elsewhere</h3> <p> {block:IfElsewhere1Name}<a href="{text:Elsewhere 1 URL}">{text:Elsewhere 1 Name}</a> <br/>{/block:IfElsewhere1Name} {block:IfElsewhere2Name}<a href="{text:Elsewhere 2 URL}">{text:Elsewhere 2 Name}</a> <br/>{/block:IfElsewhere2Name} {block:IfElsewhere3Name}<a href="{text:Elsewhere 3 URL}">{text:Elsewhere 3 Name}</a> <br/>{/block:IfElsewhere3Name} {block:IfElsewhere4Name}<a href="{text:Elsewhere 4 URL}">{text:Elsewhere 4 Name}</a> <br/>{/block:IfElsewhere4Name} {block:IfElsewhere5Name}<a href="{text:Elsewhere 5 URL}">{text:Elsewhere 5 Name}</a> <br/>{/block:IfElsewhere5Name} {block:IfElsewhere6Name}<a href="{text:Elsewhere 6 URL}">{text:Elsewhere 6 Name}</a> <br/>{/block:IfElsewhere6Name} </p> <div class="clear"></div> </div> {/block:IfElsewhere} + + <div class="more"> + <h3>Links</h3> + <ul> + {block:Posts} + {block:Link} + <li> + <a href="{URL}" title="{Name}">{name}</a> + {block:Description}<div class="content">{Description}</div>{/block:Description} + </li> + {/block:Link} + {/block:Posts} + </ul> + </div> </div> </div> <div id="entries"> {block:SearchPage} <div id="fake-post" class="entry"> <div class="content">{block:NoSearchResults}Terribly sorry, a total of {/block:NoSearchResults}<strong>{SearchResultCount}</strong> result(s) for <strong>{SearchQuery}</strong></div> </div> {/block:SearchPage} {block:TagPage} <div id="fake-post" class="entry"> <div class="content">Posts tagged <strong>{Tag}</strong></div> </div> {/block:TagPage} {block:Posts} {block:Text} <div id="post-{PostID}" class="entry text"> {block:Title}<h2><a href="{Permalink}" rel="permalink">{Title}</a></h2>{/block:Title} <div class="content">{Body}</div> <div class="meta posted-by">Posted by {PostAuthorName}</div> <div class="meta">{block:Date}{DayOfWeek}, {Month} {DayOfMonth}, {Year}{/block:Date}{block:NoteCount} &mdash; <a href="{Permalink}#notes">{NoteCountWithLabel}</a>{/block:NoteCount}{block:Date}{block:IfDisqusShortname}&nbsp;&nbsp;&nbsp;(<a href="{Permalink}#disqus_thread"></a>){/block:IfDisqusShortname}{/block:Date}{block:More}&nbsp;&nbsp;&nbsp;<a href="{Permalink}">Read more &hellip;</a>{/block:More}</div> </div> {/block:Text} {block:Photo} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{LinkOpenTag}<img src="{PhotoURL-500}" alt="{PhotoAlt}">{LinkCloseTag}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photo} {block:Photoset} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Photoset-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photoset} {block:Quote} <div id="post-{PostID}" class="entry quote"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2>{Quote}</h2> {block:Source}<div class="content">{Source}</div>{/block:Source} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Quote} -{block:Link} -<div id="post-{PostID}" class="entry link"> - <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> - <h2><a href="{URL}" {Target}>{Name}</a></h2> - {block:Description}<div class="content">{Description}</div>{/block:Description} - <div class="meta posted-by">Posted by {PostAuthorName}</div> - {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} -</div> -{/block:Link} - {block:Chat} <div id="post-{PostID}" class="entry chat"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> {block:Title}<h2>{Title}</h2>{/block:Title} <div class="content"> <ul> {block:Lines}<li class="{Alt}">{block:Label}<span class="label">{Label}</span> {/block:Label}{Line}</li>{/block:Lines} </ul> </div> <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Chat} {block:Audio} <div id="post-{PostID}" class="entry audio"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{AudioPlayerWhite}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Audio} {block:Video} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Video-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Video} {/block:Posts} {block:Permalink} {block:IfDisqusShortname} <div id="disqus_thread"></div> <script type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/embed.js"></script> <noscript><a href="http://{text:Disqus Shortname}.disqus.com/?url=ref">View the discussion thread.</a></noscript> {/block:IfDisqusShortname} {/block:Permalink} {block:PostNotes} <div id="notes"> {PostNotes} </div> {/block:PostNotes} {block:Pagination} <div class="page-navigation"> {block:PreviousPage}<div class="left"><a href="{PreviousPage}">&larr; Previous page</a></div>{/block:PreviousPage} {block:NextPage}<div class="right"><a href="{NextPage}">Next page &rarr;</a></div>{/block:NextPage} <div class="clear"></div> </div> {/block:Pagination} {block:PermalinkPagination} <div class="page-navigation"> {block:PreviousPost}<div class="left"><a href="{PreviousPost}">&larr; Previous post</a></div>{/block:PreviousPost} {block:NextPost}<div class="right"><a href="{NextPost}">Next post &rarr;</a></div>{/block:NextPost} <div class="clear"></div> </div> {/block:PermalinkPagination} </div> <div class="clear"></div> </div> <div id="footer"> <form class="search-footer" action="/search" method="get"> <input class="search-query" type="text" name="q" value="{SearchQuery}"><input class="button" type="submit" value="Search"> </form> <div class="actual-footer"> <p><a href="{RSS}">RSS</a>, <a href="/archive">Archive</a>. We love <a href="http://www.tumblr.com/">Tumblr</a>. Theme (<a href="http://www.tumblr.com/theme/3292">Stationery</a>) by <a href="http://thijsjacobs.com/">Thijs</a></p> </div> <div class="clear"></div> </div> </div> {block:IfDisqusShortname} <script type="text/javascript"> //<![CDATA[ (function() { var links = document.getElementsByTagName('a'); var query = '?'; for(var i = 0; i < links.length; i++) { if(links[i].href.indexOf('#disqus_thread') >= 0) { query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; } } document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/get_num_replies.js' + query + '"></' + 'script>'); })(); //]]> </script> {/block:IfDisqusShortname} </body> </html> \ No newline at end of file
andrewle/tangovoice
65def8ad6df243a872739090a7477ddcdaf2c86a
Added more elsewheres
diff --git a/template.html b/template.html index 90c328c..0a0a7a4 100644 --- a/template.html +++ b/template.html @@ -1,259 +1,268 @@ <!DOCTYPE HTML> <html> <head> {block:IndexPage} <title>{Title}</title> <meta name="description" content="{MetaDescription}"> {/block:IndexPage} {block:PostSummary}<title>{PostSummary}</title>{/block:PostSummary} <meta name="viewport" content="width=848"> <meta name="if:Elsewhere" content="0"> <meta name="text:Elsewhere 1 Name" content=""> <meta name="text:Elsewhere 1 URL" content=""> <meta name="text:Elsewhere 2 Name" content=""> <meta name="text:Elsewhere 2 URL" content=""> <meta name="text:Elsewhere 3 Name" content=""> <meta name="text:Elsewhere 3 URL" content=""> + <meta name="text:Elsewhere 4 Name" content=""> + <meta name="text:Elsewhere 4 URL" content=""> + <meta name="text:Elsewhere 5 Name" content=""> + <meta name="text:Elsewhere 5 URL" content=""> + <meta name="text:Elsewhere 6 Name" content=""> + <meta name="text:Elsewhere 6 URL" content=""> <meta name="text:Tagline" content="Your awesome tagline"> <meta name="text:Disqus Shortname" content=""> <link rel="shortcut icon" href="{Favicon}"> <link rel="alternate" href="{RSS}" type="application/rss+xml"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/A1Ukkwf8p/reset.css" type="text/css"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/Nunksbfhp/oldie.css" type="text/css"> <style type="text/css" media="screen"> #inner-sidebar .top { margin: 0 0 25px; } #disqus_thread { margin: 0 0 30px 0 !important; } #nav { list-style: none; margin: 0; padding: 0; } .meta + .meta { margin-top: 0; } {CustomCSS} </style> <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function () { $('.meta.posted-by').each(function () { $(this).text($(this).text().replace('andymism', 'Andrew')); $(this).text($(this).text().replace('thisrmykitten', 'Kara')); }); }); </script> </head> <body> <div id="main"> <div id="inner"> <div id="header"> <h1><a href="/">{Title}</a></h1> {block:IfTagline}<div class="tagline">{text:Tagline}</div>{/block:IfTagline} </div> <div id="sidebar"> <div id="inner-sidebar"> <div class="top"> <h3>Navigation</h3> <ul id="nav"> <li><a href="http://tangovoice.com/">Home</a></li> <li><a href="http://tangovoice.com/archive">Archive</a></li> {block:HasPages} {block:Pages}<li><a href="{URL}">{Label}</a></li>{/block:Pages} {/block:HasPages} <li><a href="http://tangovoice.com/rss">RSS</a></li> </ul> <div class="clear"></div> </div> <div id="authorbox"> <h3>About</h3> {Description} <div class="clear"></div> </div> {block:IfElsewhere} <div class="more"> <h3>Elsewhere</h3> <p> - {block:IfElsewhere1Name}<a href="{text:Elsewhere 1 URL}">{text:Elsewhere 1 Name}</a> {/block:IfElsewhere1Name} - {block:IfElsewhere2Name}<a href="{text:Elsewhere 2 URL}">{text:Elsewhere 2 Name}</a> {/block:IfElsewhere2Name} - {block:IfElsewhere3Name}<a href="{text:Elsewhere 3 URL}">{text:Elsewhere 3 Name}</a> {/block:IfElsewhere3Name} + {block:IfElsewhere1Name}<a href="{text:Elsewhere 1 URL}">{text:Elsewhere 1 Name}</a> <br/>{/block:IfElsewhere1Name} + {block:IfElsewhere2Name}<a href="{text:Elsewhere 2 URL}">{text:Elsewhere 2 Name}</a> <br/>{/block:IfElsewhere2Name} + {block:IfElsewhere3Name}<a href="{text:Elsewhere 3 URL}">{text:Elsewhere 3 Name}</a> <br/>{/block:IfElsewhere3Name} + {block:IfElsewhere4Name}<a href="{text:Elsewhere 4 URL}">{text:Elsewhere 4 Name}</a> <br/>{/block:IfElsewhere4Name} + {block:IfElsewhere5Name}<a href="{text:Elsewhere 5 URL}">{text:Elsewhere 5 Name}</a> <br/>{/block:IfElsewhere5Name} + {block:IfElsewhere6Name}<a href="{text:Elsewhere 6 URL}">{text:Elsewhere 6 Name}</a> <br/>{/block:IfElsewhere6Name} </p> <div class="clear"></div> </div> {/block:IfElsewhere} </div> </div> <div id="entries"> {block:SearchPage} <div id="fake-post" class="entry"> <div class="content">{block:NoSearchResults}Terribly sorry, a total of {/block:NoSearchResults}<strong>{SearchResultCount}</strong> result(s) for <strong>{SearchQuery}</strong></div> </div> {/block:SearchPage} {block:TagPage} <div id="fake-post" class="entry"> <div class="content">Posts tagged <strong>{Tag}</strong></div> </div> {/block:TagPage} {block:Posts} {block:Text} <div id="post-{PostID}" class="entry text"> {block:Title}<h2><a href="{Permalink}" rel="permalink">{Title}</a></h2>{/block:Title} <div class="content">{Body}</div> <div class="meta posted-by">Posted by {PostAuthorName}</div> <div class="meta">{block:Date}{DayOfWeek}, {Month} {DayOfMonth}, {Year}{/block:Date}{block:NoteCount} &mdash; <a href="{Permalink}#notes">{NoteCountWithLabel}</a>{/block:NoteCount}{block:Date}{block:IfDisqusShortname}&nbsp;&nbsp;&nbsp;(<a href="{Permalink}#disqus_thread"></a>){/block:IfDisqusShortname}{/block:Date}{block:More}&nbsp;&nbsp;&nbsp;<a href="{Permalink}">Read more &hellip;</a>{/block:More}</div> </div> {/block:Text} {block:Photo} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{LinkOpenTag}<img src="{PhotoURL-500}" alt="{PhotoAlt}">{LinkCloseTag}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photo} {block:Photoset} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Photoset-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photoset} {block:Quote} <div id="post-{PostID}" class="entry quote"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2>{Quote}</h2> {block:Source}<div class="content">{Source}</div>{/block:Source} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Quote} {block:Link} <div id="post-{PostID}" class="entry link"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2><a href="{URL}" {Target}>{Name}</a></h2> {block:Description}<div class="content">{Description}</div>{/block:Description} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Link} {block:Chat} <div id="post-{PostID}" class="entry chat"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> {block:Title}<h2>{Title}</h2>{/block:Title} <div class="content"> <ul> {block:Lines}<li class="{Alt}">{block:Label}<span class="label">{Label}</span> {/block:Label}{Line}</li>{/block:Lines} </ul> </div> <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Chat} {block:Audio} <div id="post-{PostID}" class="entry audio"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{AudioPlayerWhite}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Audio} {block:Video} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Video-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Video} {/block:Posts} {block:Permalink} {block:IfDisqusShortname} <div id="disqus_thread"></div> <script type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/embed.js"></script> <noscript><a href="http://{text:Disqus Shortname}.disqus.com/?url=ref">View the discussion thread.</a></noscript> {/block:IfDisqusShortname} {/block:Permalink} {block:PostNotes} <div id="notes"> {PostNotes} </div> {/block:PostNotes} {block:Pagination} <div class="page-navigation"> {block:PreviousPage}<div class="left"><a href="{PreviousPage}">&larr; Previous page</a></div>{/block:PreviousPage} {block:NextPage}<div class="right"><a href="{NextPage}">Next page &rarr;</a></div>{/block:NextPage} <div class="clear"></div> </div> {/block:Pagination} {block:PermalinkPagination} <div class="page-navigation"> {block:PreviousPost}<div class="left"><a href="{PreviousPost}">&larr; Previous post</a></div>{/block:PreviousPost} {block:NextPost}<div class="right"><a href="{NextPost}">Next post &rarr;</a></div>{/block:NextPost} <div class="clear"></div> </div> {/block:PermalinkPagination} </div> <div class="clear"></div> </div> <div id="footer"> <form class="search-footer" action="/search" method="get"> <input class="search-query" type="text" name="q" value="{SearchQuery}"><input class="button" type="submit" value="Search"> </form> <div class="actual-footer"> <p><a href="{RSS}">RSS</a>, <a href="/archive">Archive</a>. We love <a href="http://www.tumblr.com/">Tumblr</a>. Theme (<a href="http://www.tumblr.com/theme/3292">Stationery</a>) by <a href="http://thijsjacobs.com/">Thijs</a></p> </div> <div class="clear"></div> </div> </div> {block:IfDisqusShortname} <script type="text/javascript"> //<![CDATA[ (function() { var links = document.getElementsByTagName('a'); var query = '?'; for(var i = 0; i < links.length; i++) { if(links[i].href.indexOf('#disqus_thread') >= 0) { query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; } } document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/get_num_replies.js' + query + '"></' + 'script>'); })(); //]]> </script> {/block:IfDisqusShortname} </body> </html> \ No newline at end of file
andrewle/tangovoice
22a6f8ece0f729c01eb6b7ce6d2cffe6f77b99be
Moved navigation links to the top
diff --git a/template.html b/template.html index c54b882..90c328c 100644 --- a/template.html +++ b/template.html @@ -1,253 +1,259 @@ <!DOCTYPE HTML> <html> <head> {block:IndexPage} <title>{Title}</title> <meta name="description" content="{MetaDescription}"> {/block:IndexPage} {block:PostSummary}<title>{PostSummary}</title>{/block:PostSummary} <meta name="viewport" content="width=848"> <meta name="if:Elsewhere" content="0"> <meta name="text:Elsewhere 1 Name" content=""> <meta name="text:Elsewhere 1 URL" content=""> <meta name="text:Elsewhere 2 Name" content=""> <meta name="text:Elsewhere 2 URL" content=""> <meta name="text:Elsewhere 3 Name" content=""> <meta name="text:Elsewhere 3 URL" content=""> <meta name="text:Tagline" content="Your awesome tagline"> <meta name="text:Disqus Shortname" content=""> <link rel="shortcut icon" href="{Favicon}"> <link rel="alternate" href="{RSS}" type="application/rss+xml"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/A1Ukkwf8p/reset.css" type="text/css"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/Nunksbfhp/oldie.css" type="text/css"> <style type="text/css" media="screen"> + #inner-sidebar .top { + margin: 0 0 25px; + } + #disqus_thread { margin: 0 0 30px 0 !important; } #nav { list-style: none; margin: 0; padding: 0; } .meta + .meta { margin-top: 0; } {CustomCSS} </style> <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function () { - $('.meta.posted-by').text( - $('.meta.posted-by').text().replace('andymism', 'Andrew'); - $('.meta.posted-by').text().replace('thisrmykitten', 'Kara'); - ); + $('.meta.posted-by').each(function () { + $(this).text($(this).text().replace('andymism', 'Andrew')); + $(this).text($(this).text().replace('thisrmykitten', 'Kara')); + }); }); </script> </head> <body> <div id="main"> <div id="inner"> <div id="header"> <h1><a href="/">{Title}</a></h1> {block:IfTagline}<div class="tagline">{text:Tagline}</div>{/block:IfTagline} </div> <div id="sidebar"> <div id="inner-sidebar"> - <div id="authorbox"> - <h3>About</h3> - {Description} - <div class="clear"></div> - </div> - <div class="more"> + <div class="top"> <h3>Navigation</h3> <ul id="nav"> <li><a href="http://tangovoice.com/">Home</a></li> <li><a href="http://tangovoice.com/archive">Archive</a></li> {block:HasPages} {block:Pages}<li><a href="{URL}">{Label}</a></li>{/block:Pages} {/block:HasPages} + <li><a href="http://tangovoice.com/rss">RSS</a></li> </ul> <div class="clear"></div> </div> + + <div id="authorbox"> + <h3>About</h3> + {Description} + <div class="clear"></div> + </div> {block:IfElsewhere} <div class="more"> <h3>Elsewhere</h3> <p> {block:IfElsewhere1Name}<a href="{text:Elsewhere 1 URL}">{text:Elsewhere 1 Name}</a> {/block:IfElsewhere1Name} {block:IfElsewhere2Name}<a href="{text:Elsewhere 2 URL}">{text:Elsewhere 2 Name}</a> {/block:IfElsewhere2Name} {block:IfElsewhere3Name}<a href="{text:Elsewhere 3 URL}">{text:Elsewhere 3 Name}</a> {/block:IfElsewhere3Name} </p> <div class="clear"></div> </div> {/block:IfElsewhere} </div> </div> <div id="entries"> {block:SearchPage} <div id="fake-post" class="entry"> <div class="content">{block:NoSearchResults}Terribly sorry, a total of {/block:NoSearchResults}<strong>{SearchResultCount}</strong> result(s) for <strong>{SearchQuery}</strong></div> </div> {/block:SearchPage} {block:TagPage} <div id="fake-post" class="entry"> <div class="content">Posts tagged <strong>{Tag}</strong></div> </div> {/block:TagPage} {block:Posts} {block:Text} <div id="post-{PostID}" class="entry text"> {block:Title}<h2><a href="{Permalink}" rel="permalink">{Title}</a></h2>{/block:Title} <div class="content">{Body}</div> <div class="meta posted-by">Posted by {PostAuthorName}</div> <div class="meta">{block:Date}{DayOfWeek}, {Month} {DayOfMonth}, {Year}{/block:Date}{block:NoteCount} &mdash; <a href="{Permalink}#notes">{NoteCountWithLabel}</a>{/block:NoteCount}{block:Date}{block:IfDisqusShortname}&nbsp;&nbsp;&nbsp;(<a href="{Permalink}#disqus_thread"></a>){/block:IfDisqusShortname}{/block:Date}{block:More}&nbsp;&nbsp;&nbsp;<a href="{Permalink}">Read more &hellip;</a>{/block:More}</div> </div> {/block:Text} {block:Photo} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{LinkOpenTag}<img src="{PhotoURL-500}" alt="{PhotoAlt}">{LinkCloseTag}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photo} {block:Photoset} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Photoset-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photoset} {block:Quote} <div id="post-{PostID}" class="entry quote"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2>{Quote}</h2> {block:Source}<div class="content">{Source}</div>{/block:Source} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Quote} {block:Link} <div id="post-{PostID}" class="entry link"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2><a href="{URL}" {Target}>{Name}</a></h2> {block:Description}<div class="content">{Description}</div>{/block:Description} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Link} {block:Chat} <div id="post-{PostID}" class="entry chat"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> {block:Title}<h2>{Title}</h2>{/block:Title} <div class="content"> <ul> {block:Lines}<li class="{Alt}">{block:Label}<span class="label">{Label}</span> {/block:Label}{Line}</li>{/block:Lines} </ul> </div> <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Chat} {block:Audio} <div id="post-{PostID}" class="entry audio"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{AudioPlayerWhite}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Audio} {block:Video} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Video-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Video} {/block:Posts} {block:Permalink} {block:IfDisqusShortname} <div id="disqus_thread"></div> <script type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/embed.js"></script> <noscript><a href="http://{text:Disqus Shortname}.disqus.com/?url=ref">View the discussion thread.</a></noscript> {/block:IfDisqusShortname} {/block:Permalink} {block:PostNotes} <div id="notes"> {PostNotes} </div> {/block:PostNotes} {block:Pagination} <div class="page-navigation"> {block:PreviousPage}<div class="left"><a href="{PreviousPage}">&larr; Previous page</a></div>{/block:PreviousPage} {block:NextPage}<div class="right"><a href="{NextPage}">Next page &rarr;</a></div>{/block:NextPage} <div class="clear"></div> </div> {/block:Pagination} {block:PermalinkPagination} <div class="page-navigation"> {block:PreviousPost}<div class="left"><a href="{PreviousPost}">&larr; Previous post</a></div>{/block:PreviousPost} {block:NextPost}<div class="right"><a href="{NextPost}">Next post &rarr;</a></div>{/block:NextPost} <div class="clear"></div> </div> {/block:PermalinkPagination} </div> <div class="clear"></div> </div> <div id="footer"> <form class="search-footer" action="/search" method="get"> <input class="search-query" type="text" name="q" value="{SearchQuery}"><input class="button" type="submit" value="Search"> </form> <div class="actual-footer"> <p><a href="{RSS}">RSS</a>, <a href="/archive">Archive</a>. We love <a href="http://www.tumblr.com/">Tumblr</a>. Theme (<a href="http://www.tumblr.com/theme/3292">Stationery</a>) by <a href="http://thijsjacobs.com/">Thijs</a></p> </div> <div class="clear"></div> </div> </div> {block:IfDisqusShortname} <script type="text/javascript"> //<![CDATA[ (function() { var links = document.getElementsByTagName('a'); var query = '?'; for(var i = 0; i < links.length; i++) { if(links[i].href.indexOf('#disqus_thread') >= 0) { query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; } } document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/get_num_replies.js' + query + '"></' + 'script>'); })(); //]]> </script> {/block:IfDisqusShortname} </body> </html> \ No newline at end of file
andrewle/tangovoice
bf2af15e1dd0cd4676dea3a39f35620447aaa726
Forced the page to use our real names
diff --git a/template.html b/template.html index 07496cd..c54b882 100644 --- a/template.html +++ b/template.html @@ -1,233 +1,253 @@ <!DOCTYPE HTML> <html> <head> {block:IndexPage} <title>{Title}</title> <meta name="description" content="{MetaDescription}"> {/block:IndexPage} {block:PostSummary}<title>{PostSummary}</title>{/block:PostSummary} <meta name="viewport" content="width=848"> <meta name="if:Elsewhere" content="0"> <meta name="text:Elsewhere 1 Name" content=""> <meta name="text:Elsewhere 1 URL" content=""> <meta name="text:Elsewhere 2 Name" content=""> <meta name="text:Elsewhere 2 URL" content=""> <meta name="text:Elsewhere 3 Name" content=""> <meta name="text:Elsewhere 3 URL" content=""> <meta name="text:Tagline" content="Your awesome tagline"> <meta name="text:Disqus Shortname" content=""> <link rel="shortcut icon" href="{Favicon}"> <link rel="alternate" href="{RSS}" type="application/rss+xml"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/A1Ukkwf8p/reset.css" type="text/css"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/Nunksbfhp/oldie.css" type="text/css"> <style type="text/css" media="screen"> #disqus_thread { margin: 0 0 30px 0 !important; } #nav { list-style: none; margin: 0; padding: 0; } + .meta + .meta { + margin-top: 0; + } {CustomCSS} </style> + <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> + <script type="text/javascript" charset="utf-8"> + $(document).ready(function () { + $('.meta.posted-by').text( + $('.meta.posted-by').text().replace('andymism', 'Andrew'); + $('.meta.posted-by').text().replace('thisrmykitten', 'Kara'); + ); + }); + </script> </head> <body> <div id="main"> <div id="inner"> <div id="header"> <h1><a href="/">{Title}</a></h1> {block:IfTagline}<div class="tagline">{text:Tagline}</div>{/block:IfTagline} </div> <div id="sidebar"> <div id="inner-sidebar"> <div id="authorbox"> <h3>About</h3> {Description} <div class="clear"></div> </div> <div class="more"> <h3>Navigation</h3> <ul id="nav"> <li><a href="http://tangovoice.com/">Home</a></li> <li><a href="http://tangovoice.com/archive">Archive</a></li> {block:HasPages} {block:Pages}<li><a href="{URL}">{Label}</a></li>{/block:Pages} {/block:HasPages} </ul> <div class="clear"></div> </div> {block:IfElsewhere} <div class="more"> <h3>Elsewhere</h3> <p> {block:IfElsewhere1Name}<a href="{text:Elsewhere 1 URL}">{text:Elsewhere 1 Name}</a> {/block:IfElsewhere1Name} {block:IfElsewhere2Name}<a href="{text:Elsewhere 2 URL}">{text:Elsewhere 2 Name}</a> {/block:IfElsewhere2Name} {block:IfElsewhere3Name}<a href="{text:Elsewhere 3 URL}">{text:Elsewhere 3 Name}</a> {/block:IfElsewhere3Name} </p> <div class="clear"></div> </div> {/block:IfElsewhere} </div> </div> <div id="entries"> {block:SearchPage} <div id="fake-post" class="entry"> <div class="content">{block:NoSearchResults}Terribly sorry, a total of {/block:NoSearchResults}<strong>{SearchResultCount}</strong> result(s) for <strong>{SearchQuery}</strong></div> </div> {/block:SearchPage} {block:TagPage} <div id="fake-post" class="entry"> <div class="content">Posts tagged <strong>{Tag}</strong></div> </div> {/block:TagPage} {block:Posts} {block:Text} <div id="post-{PostID}" class="entry text"> {block:Title}<h2><a href="{Permalink}" rel="permalink">{Title}</a></h2>{/block:Title} <div class="content">{Body}</div> + <div class="meta posted-by">Posted by {PostAuthorName}</div> <div class="meta">{block:Date}{DayOfWeek}, {Month} {DayOfMonth}, {Year}{/block:Date}{block:NoteCount} &mdash; <a href="{Permalink}#notes">{NoteCountWithLabel}</a>{/block:NoteCount}{block:Date}{block:IfDisqusShortname}&nbsp;&nbsp;&nbsp;(<a href="{Permalink}#disqus_thread"></a>){/block:IfDisqusShortname}{/block:Date}{block:More}&nbsp;&nbsp;&nbsp;<a href="{Permalink}">Read more &hellip;</a>{/block:More}</div> </div> {/block:Text} {block:Photo} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{LinkOpenTag}<img src="{PhotoURL-500}" alt="{PhotoAlt}">{LinkCloseTag}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} + <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photo} {block:Photoset} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Photoset-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} + <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photoset} {block:Quote} <div id="post-{PostID}" class="entry quote"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2>{Quote}</h2> {block:Source}<div class="content">{Source}</div>{/block:Source} + <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Quote} {block:Link} <div id="post-{PostID}" class="entry link"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2><a href="{URL}" {Target}>{Name}</a></h2> {block:Description}<div class="content">{Description}</div>{/block:Description} + <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Link} {block:Chat} <div id="post-{PostID}" class="entry chat"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> {block:Title}<h2>{Title}</h2>{/block:Title} <div class="content"> <ul> {block:Lines}<li class="{Alt}">{block:Label}<span class="label">{Label}</span> {/block:Label}{Line}</li>{/block:Lines} </ul> </div> + <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Chat} {block:Audio} <div id="post-{PostID}" class="entry audio"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{AudioPlayerWhite}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} + <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Audio} {block:Video} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Video-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} + <div class="meta posted-by">Posted by {PostAuthorName}</div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Video} {/block:Posts} {block:Permalink} {block:IfDisqusShortname} <div id="disqus_thread"></div> <script type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/embed.js"></script> <noscript><a href="http://{text:Disqus Shortname}.disqus.com/?url=ref">View the discussion thread.</a></noscript> {/block:IfDisqusShortname} {/block:Permalink} {block:PostNotes} <div id="notes"> {PostNotes} </div> {/block:PostNotes} {block:Pagination} <div class="page-navigation"> {block:PreviousPage}<div class="left"><a href="{PreviousPage}">&larr; Previous page</a></div>{/block:PreviousPage} {block:NextPage}<div class="right"><a href="{NextPage}">Next page &rarr;</a></div>{/block:NextPage} <div class="clear"></div> </div> {/block:Pagination} {block:PermalinkPagination} <div class="page-navigation"> {block:PreviousPost}<div class="left"><a href="{PreviousPost}">&larr; Previous post</a></div>{/block:PreviousPost} {block:NextPost}<div class="right"><a href="{NextPost}">Next post &rarr;</a></div>{/block:NextPost} <div class="clear"></div> </div> {/block:PermalinkPagination} </div> <div class="clear"></div> </div> <div id="footer"> <form class="search-footer" action="/search" method="get"> <input class="search-query" type="text" name="q" value="{SearchQuery}"><input class="button" type="submit" value="Search"> </form> <div class="actual-footer"> <p><a href="{RSS}">RSS</a>, <a href="/archive">Archive</a>. We love <a href="http://www.tumblr.com/">Tumblr</a>. Theme (<a href="http://www.tumblr.com/theme/3292">Stationery</a>) by <a href="http://thijsjacobs.com/">Thijs</a></p> </div> <div class="clear"></div> </div> </div> {block:IfDisqusShortname} <script type="text/javascript"> //<![CDATA[ (function() { var links = document.getElementsByTagName('a'); var query = '?'; for(var i = 0; i < links.length; i++) { if(links[i].href.indexOf('#disqus_thread') >= 0) { query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; } } document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/get_num_replies.js' + query + '"></' + 'script>'); })(); //]]> </script> {/block:IfDisqusShortname} </body> </html> \ No newline at end of file
andrewle/tangovoice
98ceeb740e3c61fde9342b33059e6d519b45af6c
Added navigation links
diff --git a/template.html b/template.html index 10741a4..07496cd 100644 --- a/template.html +++ b/template.html @@ -1,221 +1,233 @@ <!DOCTYPE HTML> <html> <head> {block:IndexPage} <title>{Title}</title> <meta name="description" content="{MetaDescription}"> {/block:IndexPage} {block:PostSummary}<title>{PostSummary}</title>{/block:PostSummary} <meta name="viewport" content="width=848"> <meta name="if:Elsewhere" content="0"> <meta name="text:Elsewhere 1 Name" content=""> <meta name="text:Elsewhere 1 URL" content=""> <meta name="text:Elsewhere 2 Name" content=""> <meta name="text:Elsewhere 2 URL" content=""> <meta name="text:Elsewhere 3 Name" content=""> <meta name="text:Elsewhere 3 URL" content=""> <meta name="text:Tagline" content="Your awesome tagline"> <meta name="text:Disqus Shortname" content=""> <link rel="shortcut icon" href="{Favicon}"> <link rel="alternate" href="{RSS}" type="application/rss+xml"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/A1Ukkwf8p/reset.css" type="text/css"> <link rel="stylesheet" href="http://static.tumblr.com/j8lh0bq/Nunksbfhp/oldie.css" type="text/css"> <style type="text/css" media="screen"> #disqus_thread { margin: 0 0 30px 0 !important; } + #nav { + list-style: none; + margin: 0; + padding: 0; + } {CustomCSS} </style> </head> <body> <div id="main"> <div id="inner"> <div id="header"> <h1><a href="/">{Title}</a></h1> {block:IfTagline}<div class="tagline">{text:Tagline}</div>{/block:IfTagline} </div> <div id="sidebar"> <div id="inner-sidebar"> <div id="authorbox"> - <h3>About the author</h3> - <img src="{PortraitURL-48}" class="profilepic" alt="{Title}"> + <h3>About</h3> {Description} <div class="clear"></div> - {block:HasPages} - {block:Pages}<h3><a href="{URL}">{Label}</a></h3>{/block:Pages} - {/block:HasPages} + </div> + <div class="more"> + <h3>Navigation</h3> + <ul id="nav"> + <li><a href="http://tangovoice.com/">Home</a></li> + <li><a href="http://tangovoice.com/archive">Archive</a></li> + {block:HasPages} + {block:Pages}<li><a href="{URL}">{Label}</a></li>{/block:Pages} + {/block:HasPages} + </ul> + <div class="clear"></div> </div> {block:IfElsewhere} <div class="more"> <h3>Elsewhere</h3> <p> {block:IfElsewhere1Name}<a href="{text:Elsewhere 1 URL}">{text:Elsewhere 1 Name}</a> {/block:IfElsewhere1Name} {block:IfElsewhere2Name}<a href="{text:Elsewhere 2 URL}">{text:Elsewhere 2 Name}</a> {/block:IfElsewhere2Name} {block:IfElsewhere3Name}<a href="{text:Elsewhere 3 URL}">{text:Elsewhere 3 Name}</a> {/block:IfElsewhere3Name} </p> <div class="clear"></div> </div> {/block:IfElsewhere} </div> </div> <div id="entries"> {block:SearchPage} <div id="fake-post" class="entry"> <div class="content">{block:NoSearchResults}Terribly sorry, a total of {/block:NoSearchResults}<strong>{SearchResultCount}</strong> result(s) for <strong>{SearchQuery}</strong></div> </div> {/block:SearchPage} {block:TagPage} <div id="fake-post" class="entry"> <div class="content">Posts tagged <strong>{Tag}</strong></div> </div> {/block:TagPage} {block:Posts} {block:Text} <div id="post-{PostID}" class="entry text"> {block:Title}<h2><a href="{Permalink}" rel="permalink">{Title}</a></h2>{/block:Title} <div class="content">{Body}</div> <div class="meta">{block:Date}{DayOfWeek}, {Month} {DayOfMonth}, {Year}{/block:Date}{block:NoteCount} &mdash; <a href="{Permalink}#notes">{NoteCountWithLabel}</a>{/block:NoteCount}{block:Date}{block:IfDisqusShortname}&nbsp;&nbsp;&nbsp;(<a href="{Permalink}#disqus_thread"></a>){/block:IfDisqusShortname}{/block:Date}{block:More}&nbsp;&nbsp;&nbsp;<a href="{Permalink}">Read more &hellip;</a>{/block:More}</div> </div> {/block:Text} {block:Photo} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{LinkOpenTag}<img src="{PhotoURL-500}" alt="{PhotoAlt}">{LinkCloseTag}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photo} {block:Photoset} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Photoset-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Photoset} {block:Quote} <div id="post-{PostID}" class="entry quote"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2>{Quote}</h2> {block:Source}<div class="content">{Source}</div>{/block:Source} {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Quote} {block:Link} <div id="post-{PostID}" class="entry link"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <h2><a href="{URL}" {Target}>{Name}</a></h2> {block:Description}<div class="content">{Description}</div>{/block:Description} {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Link} {block:Chat} <div id="post-{PostID}" class="entry chat"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> {block:Title}<h2>{Title}</h2>{/block:Title} <div class="content"> <ul> {block:Lines}<li class="{Alt}">{block:Label}<span class="label">{Label}</span> {/block:Label}{Line}</li>{/block:Lines} </ul> </div> {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Chat} {block:Audio} <div id="post-{PostID}" class="entry audio"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{AudioPlayerWhite}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Audio} {block:Video} <div id="post-{PostID}" class="entry media"> <div class="minimeta"><a href="{Permalink}" rel="permalink"><img src="http://static.tumblr.com/j8lh0bq/I27krymjj/pointer.png" alt=""></a></div> <div class="container">{Video-500}</div> {block:Caption}<div class="content">{Caption}</div>{/block:Caption} {block:Date}{block:IfDisqusShortname}<div class="meta">(<a href="{Permalink}#disqus_thread"></a>)</div>{/block:IfDisqusShortname}{/block:Date} </div> {/block:Video} {/block:Posts} {block:Permalink} {block:IfDisqusShortname} <div id="disqus_thread"></div> <script type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/embed.js"></script> <noscript><a href="http://{text:Disqus Shortname}.disqus.com/?url=ref">View the discussion thread.</a></noscript> {/block:IfDisqusShortname} {/block:Permalink} {block:PostNotes} <div id="notes"> {PostNotes} </div> {/block:PostNotes} {block:Pagination} <div class="page-navigation"> {block:PreviousPage}<div class="left"><a href="{PreviousPage}">&larr; Previous page</a></div>{/block:PreviousPage} {block:NextPage}<div class="right"><a href="{NextPage}">Next page &rarr;</a></div>{/block:NextPage} <div class="clear"></div> </div> {/block:Pagination} {block:PermalinkPagination} <div class="page-navigation"> {block:PreviousPost}<div class="left"><a href="{PreviousPost}">&larr; Previous post</a></div>{/block:PreviousPost} {block:NextPost}<div class="right"><a href="{NextPost}">Next post &rarr;</a></div>{/block:NextPost} <div class="clear"></div> </div> {/block:PermalinkPagination} </div> <div class="clear"></div> </div> <div id="footer"> <form class="search-footer" action="/search" method="get"> <input class="search-query" type="text" name="q" value="{SearchQuery}"><input class="button" type="submit" value="Search"> </form> <div class="actual-footer"> <p><a href="{RSS}">RSS</a>, <a href="/archive">Archive</a>. We love <a href="http://www.tumblr.com/">Tumblr</a>. Theme (<a href="http://www.tumblr.com/theme/3292">Stationery</a>) by <a href="http://thijsjacobs.com/">Thijs</a></p> </div> <div class="clear"></div> </div> </div> {block:IfDisqusShortname} <script type="text/javascript"> //<![CDATA[ (function() { var links = document.getElementsByTagName('a'); var query = '?'; for(var i = 0; i < links.length; i++) { if(links[i].href.indexOf('#disqus_thread') >= 0) { query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; } } document.write('<script charset="utf-8" type="text/javascript" src="http://disqus.com/forums/{text:Disqus Shortname}/get_num_replies.js' + query + '"></' + 'script>'); })(); //]]> </script> {/block:IfDisqusShortname} </body> </html> \ No newline at end of file
stucchio/TDPSF-Simplified-Examples
a23b816dc412ab2d1bd258a7f083997c8df51445
Added dependencies to readme.
diff --git a/README.rst b/README.rst index d868784..af9d6d1 100644 --- a/README.rst +++ b/README.rst @@ -1,68 +1,83 @@ ================================== Simple phase space filter examples ================================== Introduction ============ In 2008, I (together with Avy Soffer) wrote a paper on Phase Space Filters, `A stable absorbing boundary layer for anisotropic waves`_. .. _version: .. _A stable absorbing boundary layer for anisotropic waves: http://arxiv.org/abs/0805.2929 This git repo stores the source code for that paper. Hint for possible TDPSF users ----------------------------- I have developed two separate versions of the TDPSF. One version, described in the paper `Open Boundaries for the Nonlinear Schrodinger Equation`_. .. _Open Boundaries for the Nonlinear Schrodinger Equation: http://arxiv.org/abs/math/0609183 is based on the Windowed Fourier Transform. This version has provable error bounds, which is why it was the first paper I published, and why my Ph.D. thesis was based on it. The other version_ (the one this repo is based on) uses a *simpler* and *faster* phase space filter. The accuracy of this filter is not proven, however in practice I have found it to be just as effective as the WFT based filter. Additionally, the running time of the program is *vastly* superior, by a factor of 8-32x. I *strongly* recommend that anyone who wishes to use phase space filters should use the simplified version. + Guide ===== +Dependencies +------------ + +You need python (probably 2.6 or later, but NOT 3.0), numpy, matplotlib and scipy. + +http://python.org/ + +http://numpy.scipy.org/ + +http://www.scipy.org/ + +http://matplotlib.sourceforge.net/ + + schrodinger_test.py ------------------- The file `schrodinger_test.py` is the program I used to generate Figure 1 of Section 3.1. It implements the TDPSF for the one-dimensional Schrodinger equation. This example is 1-dimensional. Euler Solvers ------------- The Euler equations are solved using a standard FFT-based spectral propagator. This example is 2-dimensional. The file `euler_exact.py` solves the problem on a grid of size `npoints * dx = 2048 * 0.125 = 256`, which is large enough that the waves will not reach the boundary before `t=50`. The file `euler_subsonic.py` solves the problem with the phase space filters. The file `error_check_euler.py` measures the error by comparing the TDPSF simulations to the exact simulations. The simulations are stored in the relative directory `euler_subsonic_$K` and `euler_subsonic_exact_$K`, where `$K` is the frequency of the initial condition. The file `euler_subsonic_long.py` solves the problem for a long time to measure the stability. Maxwell Solvers --------------- The naming for the maxwell examples is the same as for the euler examples.
stucchio/TDPSF-Simplified-Examples
279010e7ab4b58caaed37058ce0a92d34cd94032
Didn't have all the readme file in last commit.
diff --git a/README.rst b/README.rst index 170312e..d868784 100644 --- a/README.rst +++ b/README.rst @@ -1,13 +1,68 @@ ================================== Simple phase space filter examples ================================== Introduction ============ In 2008, I (together with Avy Soffer) wrote a paper on Phase Space Filters, -"A stable absorbing boundary layer for anisotropic waves". +`A stable absorbing boundary layer for anisotropic waves`_. -http://arxiv.org/abs/0805.2929 +.. _version: +.. _A stable absorbing boundary layer for anisotropic waves: http://arxiv.org/abs/0805.2929 + + +This git repo stores the source code for that paper. + +Hint for possible TDPSF users +----------------------------- + +I have developed two separate versions of the TDPSF. One version, +described in the paper `Open Boundaries for the Nonlinear Schrodinger Equation`_. + +.. _Open Boundaries for the Nonlinear Schrodinger Equation: http://arxiv.org/abs/math/0609183 + +is based on the Windowed Fourier Transform. This version has provable +error bounds, which is why it was the first paper I published, and why +my Ph.D. thesis was based on it. + +The other version_ (the one this repo is based on) uses a *simpler* and *faster* +phase space filter. The accuracy of this filter is not proven, however in practice +I have found it to be just as effective as the WFT based filter. + +Additionally, the running time of the program is *vastly* superior, by a factor of 8-32x. + +I *strongly* recommend that anyone who wishes to use phase space filters +should use the simplified version. + +Guide +===== + +schrodinger_test.py +------------------- +The file `schrodinger_test.py` is the program I used to generate Figure 1 of Section 3.1. +It implements the TDPSF for the one-dimensional Schrodinger equation. + +This example is 1-dimensional. + +Euler Solvers +------------- +The Euler equations are solved using a standard FFT-based spectral propagator. This +example is 2-dimensional. + +The file `euler_exact.py` solves the problem on a grid of size `npoints * dx = 2048 * 0.125 = 256`, +which is large enough that the waves will not reach the boundary before `t=50`. + +The file `euler_subsonic.py` solves the problem with the phase space filters. + +The file `error_check_euler.py` measures the error by comparing the TDPSF simulations to +the exact simulations. The simulations are stored in the relative directory `euler_subsonic_$K` +and `euler_subsonic_exact_$K`, where `$K` is the frequency of the initial condition. + +The file `euler_subsonic_long.py` solves the problem for a long time to measure the stability. + +Maxwell Solvers +--------------- + +The naming for the maxwell examples is the same as for the euler examples. -This git repo
stucchio/TDPSF-Simplified-Examples
40598b04009e8df30b77ca62587cb8158c955e6f
Added readme file.
diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..170312e --- /dev/null +++ b/README.rst @@ -0,0 +1,13 @@ +================================== +Simple phase space filter examples +================================== + +Introduction +============ + +In 2008, I (together with Avy Soffer) wrote a paper on Phase Space Filters, +"A stable absorbing boundary layer for anisotropic waves". + +http://arxiv.org/abs/0805.2929 + +This git repo
stucchio/TDPSF-Simplified-Examples
556e7d8ff434272d77425bb8be93e7e3045975aa
Added remainder of examples.
diff --git a/error_check_euler.py b/error_check_euler.py new file mode 100644 index 0000000..1d727ef --- /dev/null +++ b/error_check_euler.py @@ -0,0 +1,52 @@ +from pylab import * +from numpy import * + +def sixdig(n): + return str(n).rjust(6,"0") + +file_prefix = "euler_subsonic_" +file_prefix_exact = "euler_subsonic_exact_" + +def error_from_sim(t,chirp): + u0 = fromfile(file_prefix+str(float(chirp))+"_plots/frame000000.dat", dtype=float64) + u = fromfile(file_prefix+str(float(chirp))+"_plots/frame" + sixdig(t)+".dat", dtype=float64) + ue = fromfile(file_prefix_exact+str(float(chirp))+"_plots/frame" + sixdig(t)+".dat", dtype=float64) + nrm = abs(ue*ue).sum() + return (abs((u-ue)).sum() / abs(u0).sum()), abs(u-ue).max()/abs(u0).max(), sqrt(abs((u-ue)**2).sum() / ((abs(u0)**2).sum())) + +ntimes = 24 +nchirps = 20 + +err = zeros((ntimes,nchirps), dtype=float64) +err_energy = zeros((ntimes,nchirps), dtype=float64) +errmax = zeros((ntimes,nchirps), dtype=float64) + +for t in range(ntimes): + for chirp in range(1,nchirps+1): + err[t,chirp-1], errmax[t,chirp-1], err_energy[t,chirp-1] = error_from_sim(t,chirp) + +logerr=log(err_energy+0.0000000000001)/log(10) + +## subplot(211) +## imshow(transpose(logerr[:,::-1]),extent=(0,ntimes*2,1,nchirps+1)) +## xlabel("Time") +## ylabel("Frequency") +## title("$log_{10}(\mid u-u_d \mid_{L^2} \/ \/ / \mid u_0 \mid_{L^2})$") +## colorbar() +## clabel(contour(transpose(logerr),[-1,-2,-3,-4, -5],extent=(0,ntimes*2,1,nchirps+1)),fmt="$10^{%1.0f}$") + +max_errs = [max(err[:,i-1]) for i in range(1,nchirps+1)] +max_errs_linfty = [max(errmax[:,i-1]) for i in range(1,nchirps+1)] +max_errs_energy = [max(err_energy[:,i-1]) for i in range(1,nchirps+1)] +## subplot(212) +## gray() + +title("Errors for the Euler Equations") +semilogy(arange(nchirps)+1,max_errs,label="$sup_t \mid u-u_d \mid_{L^1} \/ / \mid u_0 \mid_{L^1}$") +semilogy(arange(nchirps)+1,max_errs_linfty, label="$sup_t \mid u-u_d \mid_{L^\infty} \/ \/ \/ / \mid u_0 \mid_{L^\infty}$") +semilogy(arange(nchirps)+1,max_errs_energy, label="$sup_t \mid u-u_d \mid_{L^2} \/ \/ \/ / \mid u_0 \mid_{L^2}$") +ylabel("Relative and Absolute errors") +xlabel("Frequency") +legend() + +savefig("euler_errors.eps", dpi=120) diff --git a/error_check_maxwell.py b/error_check_maxwell.py new file mode 100644 index 0000000..7181377 --- /dev/null +++ b/error_check_maxwell.py @@ -0,0 +1,53 @@ +from pylab import * +from numpy import * + +def sixdig(n): + return str(n).rjust(6,"0") + +file_prefix = "maxwell_orthotropic" +file_prefix_exact = "maxwell_orthotropic_exact_" + +def error_from_sim(t,chirp): + u0 = fromfile(file_prefix+str(float(chirp))+"_plots/frame000000.dat", dtype=float64) + u = fromfile(file_prefix+str(float(chirp))+"_plots/frame" + sixdig(t)+".dat", dtype=float64) + ue = fromfile(file_prefix_exact+str(float(chirp))+"_plots/frame" + sixdig(t)+".dat", dtype=float64) + nrm = abs(ue*ue).sum() + return (abs((u-ue)).sum() / abs(u0).sum()), abs(u-ue).max()/abs(u0).max(), sqrt(abs((u-ue)**2).sum() / ((abs(u0)**2).sum())) + +ntimes = 24 +nchirps = 20 + +err = zeros((ntimes,nchirps), dtype=float64) +err_energy = zeros((ntimes,nchirps), dtype=float64) +errmax = zeros((ntimes,nchirps), dtype=float64) + +for t in range(ntimes): + for chirp in range(1,nchirps+1): + err[t,chirp-1], errmax[t,chirp-1], err_energy[t,chirp-1] = error_from_sim(t,chirp) + +logerr=log(err_energy+0.0000000000001)/log(10) + +hot() + +## subplot(211) +## imshow(transpose(logerr[:,::-1]),extent=(0,ntimes*2,1,nchirps+1)) +## xlabel("Time") +## ylabel("Frequency") +## title("$log_{10}(\mid u-u_d \mid_{L^2} \/ \/ / \mid u_0 \mid_{L^2})$") +## colorbar() +## clabel(contour(transpose(logerr),[-1,-2,-3,-4, -5],extent=(0,ntimes*2,1,nchirps+1)),fmt="$10^{%1.0f}$") + +max_errs = [max(err[:,i-1]) for i in range(1,nchirps+1)] +max_errs_linfty = [max(errmax[:,i-1]) for i in range(1,nchirps+1)] +max_errs_energy = [max(err_energy[:,i-1]) for i in range(1,nchirps+1)] +## subplot(212) +title("Errors for Maxwell's Equations") +## gray() +semilogy(arange(nchirps)+1,max_errs,label="$sup_t \mid u-u_d \mid_{L^1} \/ / \mid u_0 \mid_{L^1}$") +semilogy(arange(nchirps)+1,max_errs_linfty, label="$sup_t \mid u-u_d \mid_{L^\infty} \/ \/ \/ / \mid u_0 \mid_{L^\infty}$") +semilogy(arange(nchirps)+1,max_errs_energy, label="$sup_t \mid u-u_d \mid_{L^2} \/ \/ \/ / \mid u_0 \mid_{L^2}$") +ylabel("Relative and Absolute errors") +xlabel("Frequency") +legend() + +savefig("maxwell_errors.eps", dpi=120) diff --git a/euler_exact.py b/euler_exact.py new file mode 100644 index 0000000..c6d3c13 --- /dev/null +++ b/euler_exact.py @@ -0,0 +1,91 @@ +import os +from pylab import * +import numpy.fft as dft +import scipy.signal as signal +from utils import * +from tdpsf import * + +freq = float(sys.argv[1]) + +simname = "euler_subsonic_exact_" + str(freq) +simdir = simname+"_plots" + + +smallwidth = 128 + +N = 3 #Number of components of the wavefield +npoints = 2048 +shape=(npoints, npoints) +dx = 0.125 +arrow_stride = npoints/24 +width=npoints*dx/2 +dt = 2.0 +tmax = 50 +M = 0.5 #Mach number +x = indices(shape)*dx +x[0] -= npoints*dx/2 +x[1] -= npoints*dx/2 + +def diagonalizing_pair(k): #Returns the diagonalizing pair, given a frequency coordinate array + shape = k.shape[1::] + root_k = sqrt(k[0]*k[0]+k[1]*k[1]) + D = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + D[0,0] = -1*root_k / k[1] + D[0,1] = k[0]/k[1] + D[0,2] = 1 + D[1,0] = root_k / k[1] + D[1,1] = k[0]/k[1] + D[1,2] = 1 + D[2,0] = 0 + D[2,1] = -k[1]/k[0] + D[2,2] = 1 + + DI = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + DI[0,0] = -0.5*k[1]/root_k + DI[0,1] = 0.5*k[1]/root_k + DI[0,2] = 0 + DI[1,0] = 0.5*k[1]*k[0]/(root_k*root_k) + DI[1,1] = 0.5*k[1]*k[0]/(root_k*root_k) + DI[1,2] = -1*k[1]*k[0]/(root_k*root_k) + DI[2,0] = 0.5*k[1]*k[1]/(root_k*root_k) + DI[2,1] = 0.5*k[1]*k[1]/(root_k*root_k) + DI[2,2] = 1*k[0]*k[0]/(root_k*root_k) + return D, DI + +print "Running a simulation of the euler equations in a subsonic flow." +print "Mach number: " + str(M) +print "Lattice of " + str(shape) + ", with dx=" + str(dx) + ", dt="+str(dt) + +#root_k[0,0] = 1.0 + +k = kgrid((npoints,npoints), dx) +root_k = sqrt(k[0]*k[0]+k[1]*k[1]) + +u = empty(shape=(N,) + shape, dtype=Complex64) #The wavefield itself +u[:] = 0 +u[0] = exp((-1.0/9.0)*((x[0]+8)**2+x[1]**2))*cos(freq*sqrt((x[0]+8)**2+x[1]**2+1))*((x[0]+8)**2+x[1]**2) + +D, DI = diagonalizing_pair(k) + +H = empty(shape=(N,) + shape, dtype=Complex64) #Hamiltonian +H[0,:] = complex(0,1)*(M*k[0]+root_k) +H[1,:] = complex(0,1)*(M*k[0]-root_k) +H[2,:] = complex(0,1)*M*k[0] +H[:,0,0] = 0.0 + +os.system("rm -rf " + simdir + "; mkdir " + simdir) + +for i in range(int(tmax/dt)): + u[0,npoints/2-smallwidth:npoints/2+smallwidth,npoints/2-smallwidth:npoints/2+smallwidth].real.tofile(os.path.join(simdir, "frame" + str(i).rjust(6,"0")+".dat")) + time = i*dt + print "Time = " + str(time) + for n in range(N): #FFT the wavefield + u[n] = dft.fft2(u[n]) + u[:] = mmul(D,u) + u *= exp(H*dt) + u[:] = mmul(DI,u) + for n in range(N): #Inverse FFT the wavefield + u[n] = dft.ifft2(u[n]) + + + diff --git a/euler_subsonic.py b/euler_subsonic.py new file mode 100644 index 0000000..7cec60b --- /dev/null +++ b/euler_subsonic.py @@ -0,0 +1,162 @@ +import os +from pylab import * +import numpy.fft as dft +import scipy.signal as signal +from utils import * +from tdpsf import * + +freq = float(sys.argv[1]) + +simname = "euler_subsonic_"+str(freq) +simdir = simname+"_plots" + + +N = 3 #Number of components of the wavefield +npoints = 512 +shape=(npoints, npoints) +dx = 0.125 +arrow_stride = npoints/24 +width=npoints*dx/2 +dt = 0.25 +tmax = 50 +M = 0.5 #Mach number +x = indices(shape)*dx +x[0] -= npoints*dx/2 +x[1] -= npoints*dx/2 + +def diagonalizing_pair(k): #Returns the diagonalizing pair, given a frequency coordinate array + shape = k.shape[1::] + root_k = sqrt(k[0]*k[0]+k[1]*k[1]) + D = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + D[0,0] = -1*root_k / k[1] + D[0,1] = k[0]/k[1] + D[0,2] = 1 + D[1,0] = root_k / k[1] + D[1,1] = k[0]/k[1] + D[1,2] = 1 + D[2,0] = 0 + D[2,1] = -k[1]/k[0] + D[2,2] = 1 + + DI = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + DI[0,0] = -0.5*k[1]/root_k + DI[0,1] = 0.5*k[1]/root_k + DI[0,2] = 0 + DI[1,0] = 0.5*k[1]*k[0]/(root_k*root_k) + DI[1,1] = 0.5*k[1]*k[0]/(root_k*root_k) + DI[1,2] = -1*k[1]*k[0]/(root_k*root_k) + DI[2,0] = 0.5*k[1]*k[1]/(root_k*root_k) + DI[2,1] = 0.5*k[1]*k[1]/(root_k*root_k) + DI[2,2] = 1*k[0]*k[0]/(root_k*root_k) + return D, DI + +print "Running a simulation of the euler equations in a subsonic flow." +print "Mach number: " + str(M) +print "Lattice of " + str(shape) + ", with dx=" + str(dx) + ", dt="+str(dt) + +#root_k[0,0] = 1.0 + +k = kgrid((npoints,npoints), dx) +root_k = sqrt(k[0]*k[0]+k[1]*k[1]) + +u = empty(shape=(N,) + shape, dtype=Complex64) #The wavefield itself +u[:] = 0 +u[0] = exp((-1.0/9.0)*((x[0]+8)**2+x[1]**2))*cos(freq*sqrt((x[0]+8)**2+x[1]**2+1))*((x[0]+8)**2+x[1]**2) + +D, DI = diagonalizing_pair(k) + +H = empty(shape=(N,) + shape, dtype=Complex64) #Hamiltonian +H[0,:] = complex(0,1)*(M*k[0]+root_k) +H[1,:] = complex(0,1)*(M*k[0]-root_k) +H[2,:] = complex(0,1)*M*k[0] +H[:,0,0] = 0.0 + +sdev = 1.0 +top = phase_space_filter(dx,sdev,1e-4, npoints, 0, N, diagonalizing_pair) +bottom = phase_space_filter(dx,sdev,1e-4, npoints, 0, N, diagonalizing_pair, 1) +print "Buff width: " + str(top.buffer_width) +left = phase_space_filter(dx,sdev,1e-6, npoints, 1, N, diagonalizing_pair) +right = phase_space_filter(dx,sdev,1e-6, npoints, 1, N, diagonalizing_pair, 1) +kmin = log(1e-6)/sdev + +print "Buffer widths: " + str(top.buffer_width) + "," + str(left.buffer_width) +buffwidth = top.buffer_width + +kf = top.kgrid() +root_kf = sqrt(kf[0]**2+kf[1]**2) +top.P[:] = 0.0 +top.P[0][where( M + kf[0]/root_kf > 0, True, False) ] = 1.0 +top.P[1][where( M - kf[0]/root_kf > 0, True, False) ] = 1.0 +top.P[2] = 1.0 +top.blur_k_filter() + +kf = bottom.kgrid() +root_kf = sqrt(kf[0]**2+kf[1]**2) +bottom.P[:] = 0.0 +bottom.P[0][where( M + kf[0]/root_kf < 0, True, False) ] = 1.0 +bottom.P[1][where( M - kf[0]/root_kf < 0, True, False) ] = 1.0 +bottom.P[2] = 1.0 +bottom.blur_k_filter() + + +kf = left.kgrid() +root_kf = sqrt(kf[0]**2+kf[1]**2) +left.P[:] = 0.0 +left.P[0][where( 1*kf[1]/root_kf > 0, True, False) ] = 1.0 +left.P[1][where( -1*kf[1]/root_kf > 0, True, False) ] = 1.0 +left.P[2] = 0.0 +left.blur_k_filter() + +kf = right.kgrid() +root_kf = sqrt(kf[0]**2+kf[1]**2) +right.P[:] = 0.0 +right.P[0][where( -1*kf[1]/root_kf > 0, True, False) ] = 1.0 +right.P[1][where( 1*kf[1]/root_kf > 0, True, False) ] = 1.0 +right.P[2] = 0.0 +right.blur_k_filter() + + + + +hot() #Choose the color scheme +os.system("rm -rf " + simdir + "; mkdir " + simdir) + +for i in range(int(tmax/dt)): + time = i*dt + + if i % 8 == 0: + print "Saving data file...t="+str(time) + u[0,buffwidth:-buffwidth,buffwidth:-buffwidth].real.tofile(os.path.join(simdir, "frame" + str(int(i/8)).rjust(6,"0")+".dat")) + + print "Time = " + str(time) + for n in range(N): #FFT the wavefield + u[n] = dft.fft2(u[n]) + u[:] = mmul(D,u) + u *= exp(H*dt) + u[:] = mmul(DI,u) + for n in range(N): #Inverse FFT the wavefield + u[n] = dft.ifft2(u[n]) + if i % int(top.width()/(12.0*dt)) == 0: #Apply phase space filters before + top(u) #waves can cross half the buffer + left(u) + right(u) + bottom(u) + print "Applying filter..." + clf()#Now plot things + imshow(u[0].real,extent=(width,-width,width+M*time,-width+M*time),vmin=-1.0,vmax=1.0) + title("$p(x,"+str(time).ljust(5,'0')+")$") + colorbar() + #hold(True) + #quiver(x[1,::arrow_stride,::arrow_stride],x[0,::arrow_stride,::arrow_stride]+M*time,u[2,::arrow_stride,::arrow_stride].real, u[1,::arrow_stride,::arrow_stride].real, scale=5) + savefig(os.path.join(simdir, "frame" + str(i).rjust(6,"0")+".png"), dpi=120) + + +movie_command_line = "mencoder -ovc lavc -lavcopts vcodec=mpeg1video:vbitrate=1500 -mf type=png:fps=15 -nosound -of mpeg -o " + simdir + "/simulation.mpg mf://" + simdir + "/\*.png" +print "Making movie with command line: " +print movie_command_line +os.system(movie_command_line) + +mp4_movie_command_line = "ffmpeg -r 25 -b 1800 -i " + simdir + "/frame%06d.png " + simdir + "/simulation.mp4" +print mp4_movie_command_line +os.system(mp4_movie_command_line) + diff --git a/euler_subsonic_long.py b/euler_subsonic_long.py new file mode 100644 index 0000000..5e36e5f --- /dev/null +++ b/euler_subsonic_long.py @@ -0,0 +1,158 @@ +import os +from pylab import * +import numpy.fft as dft +import scipy.signal as signal +from utils import * +from tdpsf import * + +freq = 10.0 + +simname = "euler_subsonic_"+str(freq) +simdir = simname+"_plots" + + +N = 3 #Number of components of the wavefield +npoints = 512 +shape=(npoints, npoints) +dx = 0.125 +arrow_stride = npoints/24 +width=npoints*dx/2 +dt = 0.25 +tmax = 2000 +M = 0.5 #Mach number +x = indices(shape)*dx +x[0] -= npoints*dx/2 +x[1] -= npoints*dx/2 + +def diagonalizing_pair(k): #Returns the diagonalizing pair, given a frequency coordinate array + shape = k.shape[1::] + root_k = sqrt(k[0]*k[0]+k[1]*k[1]) + D = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + D[0,0] = -1*root_k / k[1] + D[0,1] = k[0]/k[1] + D[0,2] = 1 + D[1,0] = root_k / k[1] + D[1,1] = k[0]/k[1] + D[1,2] = 1 + D[2,0] = 0 + D[2,1] = -k[1]/k[0] + D[2,2] = 1 + + DI = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + DI[0,0] = -0.5*k[1]/root_k + DI[0,1] = 0.5*k[1]/root_k + DI[0,2] = 0 + DI[1,0] = 0.5*k[1]*k[0]/(root_k*root_k) + DI[1,1] = 0.5*k[1]*k[0]/(root_k*root_k) + DI[1,2] = -1*k[1]*k[0]/(root_k*root_k) + DI[2,0] = 0.5*k[1]*k[1]/(root_k*root_k) + DI[2,1] = 0.5*k[1]*k[1]/(root_k*root_k) + DI[2,2] = 1*k[0]*k[0]/(root_k*root_k) + return D, DI + +print "Running a simulation of the euler equations in a subsonic flow." +print "Mach number: " + str(M) +print "Lattice of " + str(shape) + ", with dx=" + str(dx) + ", dt="+str(dt) + +#root_k[0,0] = 1.0 + +k = kgrid((npoints,npoints), dx) +root_k = sqrt(k[0]*k[0]+k[1]*k[1]) + +u = empty(shape=(N,) + shape, dtype=Complex64) #The wavefield itself +u[:] = 0 +u[0] = exp((-1.0/9.0)*((x[0]+8)**2+x[1]**2))*cos(freq*sqrt((x[0]+8)**2+x[1]**2+1))*((x[0]+8)**2+x[1]**2) + +D, DI = diagonalizing_pair(k) + +H = empty(shape=(N,) + shape, dtype=Complex64) #Hamiltonian +H[0,:] = complex(0,1)*(M*k[0]+root_k) +H[1,:] = complex(0,1)*(M*k[0]-root_k) +H[2,:] = complex(0,1)*M*k[0] +H[:,0,0] = 0.0 + +sdev = 1.0 +top = phase_space_filter(dx,sdev,1e-4, npoints, 0, N, diagonalizing_pair) +bottom = phase_space_filter(dx,sdev,1e-4, npoints, 0, N, diagonalizing_pair, 1) +print "Buff width: " + str(top.buffer_width) +left = phase_space_filter(dx,sdev,1e-6, npoints, 1, N, diagonalizing_pair) +right = phase_space_filter(dx,sdev,1e-6, npoints, 1, N, diagonalizing_pair, 1) +kmin = log(1e-6)/sdev + +print "Buffer widths: " + str(top.buffer_width) + "," + str(left.buffer_width) +buffwidth = top.buffer_width + +kf = top.kgrid() +root_kf = sqrt(kf[0]**2+kf[1]**2) +top.P[:] = 0.0 +top.P[0][where( M + kf[0]/root_kf > 0, True, False) ] = 1.0 +top.P[1][where( M - kf[0]/root_kf > 0, True, False) ] = 1.0 +top.P[2] = 1.0 +top.blur_k_filter() + +kf = bottom.kgrid() +root_kf = sqrt(kf[0]**2+kf[1]**2) +bottom.P[:] = 0.0 +bottom.P[0][where( M + kf[0]/root_kf < 0, True, False) ] = 1.0 +bottom.P[1][where( M - kf[0]/root_kf < 0, True, False) ] = 1.0 +bottom.P[2] = 1.0 +bottom.blur_k_filter() + + +kf = left.kgrid() +root_kf = sqrt(kf[0]**2+kf[1]**2) +left.P[:] = 0.0 +left.P[0][where( 1*kf[1]/root_kf > 0, True, False) ] = 1.0 +left.P[1][where( -1*kf[1]/root_kf > 0, True, False) ] = 1.0 +left.P[2] = 0.0 +left.blur_k_filter() + +kf = right.kgrid() +root_kf = sqrt(kf[0]**2+kf[1]**2) +right.P[:] = 0.0 +right.P[0][where( -1*kf[1]/root_kf > 0, True, False) ] = 1.0 +right.P[1][where( 1*kf[1]/root_kf > 0, True, False) ] = 1.0 +right.P[2] = 0.0 +right.blur_k_filter() + + + + +os.system("rm euler_long_time.dat") +outfile = open("euler_long_time.dat",'w') + +nrm0 = abs(u*u).sum() + +for i in range(int(tmax/dt)): + time = i*dt + + for n in range(N): #FFT the wavefield + u[n] = dft.fft2(u[n]) + u[:] = mmul(D,u) + u *= exp(H*dt) + u[:] = mmul(DI,u) + for n in range(N): #Inverse FFT the wavefield + u[n] = dft.ifft2(u[n]) + if i % int(top.width()/(12.0*dt)) == 0: #Apply phase space filters before + top(u) #waves can cross half the buffer + left(u) + right(u) + bottom(u) + + nrm = abs(u*u).sum() / nrm0 + if i % 8 == 0: + outfile.write(str(time) + "; " + str(nrm) + "\n") + outfile.flush() + print str(time) + "; " + str(nrm) + + + +movie_command_line = "mencoder -ovc lavc -lavcopts vcodec=mpeg1video:vbitrate=1500 -mf type=png:fps=15 -nosound -of mpeg -o " + simdir + "/simulation.mpg mf://" + simdir + "/\*.png" +print "Making movie with command line: " +print movie_command_line +os.system(movie_command_line) + +mp4_movie_command_line = "ffmpeg -r 25 -b 1800 -i " + simdir + "/frame%06d.png " + simdir + "/simulation.mp4" +print mp4_movie_command_line +os.system(mp4_movie_command_line) + diff --git a/maxwell_orthotropic.py b/maxwell_orthotropic.py new file mode 100644 index 0000000..3fdcfdb --- /dev/null +++ b/maxwell_orthotropic.py @@ -0,0 +1,164 @@ +import os +from pylab import * +import numpy.fft as dft +import scipy.signal as signal +from utils import * +from tdpsf import * + +freq = float(sys.argv[1]) + +simname = "maxwell_orthotropic"+str(freq) +simdir = simname+"_plots" + +#This simulation solves the u[3,4,5] parts of the wavefield. +N = 3 #Number of components of the wavefield +npoints = 512 +shape=(npoints, npoints) +dx = 0.125 +arrow_stride = npoints/24 +width=npoints*dx/2 +dt = 0.25 +tmax = 100 +x = indices(shape)*dx +x[0] -= npoints*dx/2 +x[1] -= npoints*dx/2 + +b = 0.25 #Anisotropy parameter +f = (sqrt(1.0+b)+sqrt(1.0-b))/2.0 +g = (-1*sqrt(1.0+b)+sqrt(1.0-b))/2.0 + +def diagonalizing_pair(k): #Returns the diagonalizing pair, given a frequency coordinate array + shape = k.shape[1::] + E = sqrt( (f*f+g*g)*(k[0]*k[0]+k[1]*k[1])-4*f*g*k[0]*k[1]) + E[0,0] = 1.0 + Er2 = sqrt(2.0)*E #E root 2 + D = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + D[0,0] = -1.0 / sqrt(2.0)# Er2 + D[0,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + D[0,2] = (f*k[0]-g*k[1]) / Er2 + D[1,0] = 1.0/ sqrt(2.0) # Er2 + D[1,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + D[1,2] = (f*k[0]-g*k[1]) / Er2 + D[2,0] = 0 + D[2,1] = (f*k[0]-g*k[1]) / E + D[2,2] = (f*k[1]-g*k[0]) / E + + DI = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + DI[0,0] = -1.0 / sqrt(2.0) #Er2 + DI[1,0] = -1.0*(f*k[1]-g*k[0]) / Er2 + DI[2,0] = (f*k[0]-g*k[1]) / Er2 + DI[0,1] = 1.0/ sqrt(2.0) #Er2 + DI[1,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + DI[2,1] = (f*k[0]-g*k[1]) / Er2 + DI[0,2] = 0 + DI[1,2] = (f*k[0]-g*k[1]) / E + DI[2,2] = (f*k[1]-g*k[0]) / E + return D, DI + +print "Running a simulation of the maxwell equations in an orthotropic medium." +print "b = " + str(b) +print "f = " + str(f) +print "g = " + str(g) +print "Lattice of " + str(shape) + ", with dx=" + str(dx) + ", dt="+str(dt) + +#root_k[0,0] = 1.0 + +k = kgrid((npoints,npoints), dx) +E = sqrt( (f**2+g**2)*(k[0]*k[0]+k[1]*k[1])-4*f*g*k[0]*k[1]) + + +u = empty(shape=(N,) + shape, dtype=Complex64) #The wavefield itself +u[:] = 0 +u[0] = exp((-1.0/9.0)*((x[0])**2+x[1]**2))*cos(freq*sqrt((x[0])**2+x[1]**2+1))*((x[0])**2+x[1]**2) + +D, DI = diagonalizing_pair(k) + +H = empty(shape=(N,) + shape, dtype=Complex64) #Hamiltonian +H[0,:] = complex(0,1)*E +H[1,:] = complex(0,-1)*E +H[2,:] = 0.0 +#H[:,0,0] = 0.0 + +sdev = 1.0 +top = phase_space_filter(dx,sdev,1e-4, npoints, 0, N, diagonalizing_pair) +bottom = phase_space_filter(dx,sdev,1e-4, npoints, 0, N, diagonalizing_pair, 1) +print "Buff width: " + str(top.buffer_width) +left = phase_space_filter(dx,sdev,1e-4, npoints, 1, N, diagonalizing_pair) +right = phase_space_filter(dx,sdev,1e-4, npoints, 1, N, diagonalizing_pair, 1) +kmin = log(1e-6)/sdev + +print "Buffer widths: " + str(top.buffer_width) + "," + str(left.buffer_width) +buffwidth = top.buffer_width + +kf = top.kgrid() +top.P[:] = 0.0 +top.P[0][where( 2*(f*f+g*g)*kf[0] -4*f*g*kf[1] > 0, True, False) ] = 1.0 +top.P[1][where( 2*(f*f+g*g)*kf[0] -4*f*g*kf[1] < 0, True, False) ] = 1.0 +top.P[2] = 1.0 +top.blur_k_filter() + +kf = left.kgrid() +left.P[:] = 0.0 +left.P[0][where( 2*(f*f+g*g)*kf[1] -4*f*g*kf[0] > 0, True, False) ] = 1.0 +left.P[1][where( 2*(f*f+g*g)*kf[1] -4*f*g*kf[0] < 0, True, False) ] = 1.0 +left.P[2] = 0.0 +left.blur_k_filter() + +kf = right.kgrid() +right.P[:] = 0.0 +right.P[0][where( 2*(f*f+g*g)*kf[1] -4*f*g*kf[0] < 0, True, False) ] = 1.0 +right.P[1][where( 2*(f*f+g*g)*kf[1] -4*f*g*kf[0] > 0, True, False) ] = 1.0 +right.P[2] = 0.0 +right.blur_k_filter() + +kf = bottom.kgrid() +bottom.P[:] = 0.0 +bottom.P[0][where( 2*(f*f+g*g)*kf[0] -4*f*g*kf[1] < 0, True, False) ] = 1.0 +bottom.P[1][where( 2*(f*f+g*g)*kf[0] -4*f*g*kf[1] > 0, True, False) ] = 1.0 +bottom.P[2] = 1.0 +bottom.blur_k_filter() + + + +hsv() #Choose the color scheme +os.system("rm -rf " + simdir + "; mkdir " + simdir) + +for i in range(int(tmax/dt)): + time = i*dt + + if i % 8 == 0: + print "Saving data file...t="+str(time) + u[0,buffwidth:-buffwidth,buffwidth:-buffwidth].real.tofile(os.path.join(simdir, "frame" + str(int(i/8)).rjust(6,"0")+".dat")) + + print "Time = " + str(time) + for n in range(N): #FFT the wavefield + u[n] = dft.fft2(u[n]) + u[:] = mmul(D,u) + u *= exp(H*dt) + u[2,:] = 0.0 + u[:] = mmul(DI,u) + for n in range(N): #Inverse FFT the wavefield + u[n] = dft.ifft2(u[n]) + if i % int(top.width()/(12.0*dt)) == 0: #Apply phase space filters before + top(u) #waves can cross half the buffer + left(u) + right(u) + bottom(u) + print "Applying filter..." + clf()#Now plot things + imshow(u[0].real,extent=(width,-width,width,-width), vmin=-1,vmax=1) + title("$B_z (x,"+str(time).ljust(5,'0')+")$") + colorbar() + #quiver(x[1,::arrow_stride,::arrow_stride],x[0,::arrow_stride,::arrow_stride]+M*time,u[2,::arrow_stride,::arrow_stride].real, u[1,::arrow_stride,::arrow_stride].real, scale=5) + savefig(os.path.join(simdir, "frame" + str(i).rjust(6,"0")+".png"), dpi=120) + + +movie_command_line = "mencoder -ovc lavc -lavcopts vcodec=mpeg1video:vbitrate=1500 -mf type=png:fps=15 -nosound -of mpeg -o " + simdir + "/simulation.mpg mf://" + simdir + "/\*.png" +print "Making movie with command line: " +print movie_command_line +os.system(movie_command_line) + +mp4_movie_command_line = "ffmpeg -qmax 2 -r 25 -b 1800 -i " + simdir + "/frame%06d.png " + simdir + "/simulation.mp4" +print mp4_movie_command_line +os.system(mp4_movie_command_line) + diff --git a/maxwell_orthotropic_exact.py b/maxwell_orthotropic_exact.py new file mode 100644 index 0000000..1cebbb4 --- /dev/null +++ b/maxwell_orthotropic_exact.py @@ -0,0 +1,100 @@ +import os +from pylab import * +import numpy.fft as dft +import scipy.signal as signal +from utils import * +from tdpsf import * + +freq = float(sys.argv[1]) + +simname = "maxwell_orthotropic_exact_" + str(freq) +simdir = simname+"_plots" + + +smallwidth = 128 + +N = 3 #Number of components of the wavefield +npoints = 2048 +shape=(npoints, npoints) +dx = 0.125 +arrow_stride = npoints/24 +width=npoints*dx/2 +dt = 2.0 +tmax = 50 + +b = 0.25 #Anisotropy parameter +f = (sqrt(1.0+b)+sqrt(1.0-b))/2.0 +g = (-1*sqrt(1.0+b)+sqrt(1.0-b))/2.0 + +x = indices(shape)*dx +x[0] -= npoints*dx/2 +x[1] -= npoints*dx/2 + +def diagonalizing_pair(k): #Returns the diagonalizing pair, given a frequency coordinate array + shape = k.shape[1::] + E = sqrt( (f*f+g*g)*(k[0]*k[0]+k[1]*k[1])-4*f*g*k[0]*k[1]) + E[0,0] = 1.0 + Er2 = sqrt(2.0)*E #E root 2 + D = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + D[0,0] = -1.0 / sqrt(2.0)# Er2 + D[0,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + D[0,2] = (f*k[0]-g*k[1]) / Er2 + D[1,0] = 1.0/ sqrt(2.0) # Er2 + D[1,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + D[1,2] = (f*k[0]-g*k[1]) / Er2 + D[2,0] = 0 + D[2,1] = (f*k[0]-g*k[1]) / E + D[2,2] = (f*k[1]-g*k[0]) / E + + DI = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + DI[0,0] = -1.0 / sqrt(2.0) #Er2 + DI[1,0] = -1.0*(f*k[1]-g*k[0]) / Er2 + DI[2,0] = (f*k[0]-g*k[1]) / Er2 + DI[0,1] = 1.0/ sqrt(2.0) #Er2 + DI[1,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + DI[2,1] = (f*k[0]-g*k[1]) / Er2 + DI[0,2] = 0 + DI[1,2] = (f*k[0]-g*k[1]) / E + DI[2,2] = (f*k[1]-g*k[0]) / E + return D, DI + +print "Running a simulation of the maxwell equations in an orthotropic medium." +print "Lattice of " + str(shape) + ", with dx=" + str(dx) + ", dt="+str(dt) + +#root_k[0,0] = 1.0 + +k = kgrid((npoints,npoints), dx) +E = sqrt( (f*f+g*g)*(k[0]*k[0]+k[1]*k[1])-4*f*g*k[0]*k[1]) +E[0,0] = 1.0 + +root_k = sqrt(k[0]*k[0]+k[1]*k[1]) + +u = empty(shape=(N,) + shape, dtype=Complex64) #The wavefield itself +u[:] = 0 +u[0] = exp((-1.0/9.0)*(x[0]**2+x[1]**2))*cos(freq*sqrt(x[0]**2+x[1]**2+1))*(x[0]**2+x[1]**2) + +D, DI = diagonalizing_pair(k) + +H = empty(shape=(N,) + shape, dtype=Complex64) #Hamiltonian +H[0,:] = complex(0,1)*E +H[1,:] = complex(0,-1)*E +H[2,:] = 0.0 +#H[:,0,0] = 0.0 + +os.system("rm -rf " + simdir + "; mkdir " + simdir) + +for i in range(int(tmax/dt)): + u[0,npoints/2-smallwidth:npoints/2+smallwidth,npoints/2-smallwidth:npoints/2+smallwidth].real.tofile(os.path.join(simdir, "frame" + str(i).rjust(6,"0")+".dat")) + time = i*dt + print "Time = " + str(time) + for n in range(N): #FFT the wavefield + u[n] = dft.fft2(u[n]) + u[:] = mmul(D,u) + u *= exp(H*dt) + u[2,:] = 0 + u[:] = mmul(DI,u) + for n in range(N): #Inverse FFT the wavefield + u[n] = dft.ifft2(u[n]) + + + diff --git a/maxwell_orthotropic_long.py b/maxwell_orthotropic_long.py new file mode 100644 index 0000000..a194607 --- /dev/null +++ b/maxwell_orthotropic_long.py @@ -0,0 +1,160 @@ +import os +from pylab import * +import numpy.fft as dft +import scipy.signal as signal +from utils import * +from tdpsf import * + +freq = 10.0 + +simname = "maxwell_orthotropic"+str(freq) +simdir = simname+"_plots" + +#This simulation solves the u[3,4,5] parts of the wavefield. +N = 3 #Number of components of the wavefield +npoints = 512 +shape=(npoints, npoints) +dx = 0.125 +arrow_stride = npoints/24 +width=npoints*dx/2 +dt = 0.25 +tmax = 2000 +x = indices(shape)*dx +x[0] -= npoints*dx/2 +x[1] -= npoints*dx/2 + +b = 0.25 #Anisotropy parameter +f = (sqrt(1.0+b)+sqrt(1.0-b))/2.0 +g = (-1*sqrt(1.0+b)+sqrt(1.0-b))/2.0 + +def diagonalizing_pair(k): #Returns the diagonalizing pair, given a frequency coordinate array + shape = k.shape[1::] + E = sqrt( (f*f+g*g)*(k[0]*k[0]+k[1]*k[1])-4*f*g*k[0]*k[1]) + E[0,0] = 1.0 + Er2 = sqrt(2.0)*E #E root 2 + D = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + D[0,0] = -1.0 / sqrt(2.0)# Er2 + D[0,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + D[0,2] = (f*k[0]-g*k[1]) / Er2 + D[1,0] = 1.0/ sqrt(2.0) # Er2 + D[1,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + D[1,2] = (f*k[0]-g*k[1]) / Er2 + D[2,0] = 0 + D[2,1] = (f*k[0]-g*k[1]) / E + D[2,2] = (f*k[1]-g*k[0]) / E + + DI = empty(shape=(N,N) + shape, dtype=Complex64) #Diagonalizes the Hamiltonian + DI[0,0] = -1.0 / sqrt(2.0) #Er2 + DI[1,0] = -1.0*(f*k[1]-g*k[0]) / Er2 + DI[2,0] = (f*k[0]-g*k[1]) / Er2 + DI[0,1] = 1.0/ sqrt(2.0) #Er2 + DI[1,1] = -1.0*(f*k[1]-g*k[0]) / Er2 + DI[2,1] = (f*k[0]-g*k[1]) / Er2 + DI[0,2] = 0 + DI[1,2] = (f*k[0]-g*k[1]) / E + DI[2,2] = (f*k[1]-g*k[0]) / E + return D, DI + +print "Running a simulation of the maxwell equations in an orthotropic medium." +print "b = " + str(b) +print "f = " + str(f) +print "g = " + str(g) +print "Lattice of " + str(shape) + ", with dx=" + str(dx) + ", dt="+str(dt) + +#root_k[0,0] = 1.0 + +k = kgrid((npoints,npoints), dx) +E = sqrt( (f**2+g**2)*(k[0]*k[0]+k[1]*k[1])-4*f*g*k[0]*k[1]) + + +u = empty(shape=(N,) + shape, dtype=Complex64) #The wavefield itself +u[:] = 0 +u[0] = exp((-1.0/9.0)*((x[0])**2+x[1]**2))*cos(freq*sqrt((x[0])**2+x[1]**2+1))*((x[0])**2+x[1]**2) + +D, DI = diagonalizing_pair(k) + +H = empty(shape=(N,) + shape, dtype=Complex64) #Hamiltonian +H[0,:] = complex(0,1)*E +H[1,:] = complex(0,-1)*E +H[2,:] = 0.0 +#H[:,0,0] = 0.0 + +sdev = 1.0 +top = phase_space_filter(dx,sdev,1e-4, npoints, 0, N, diagonalizing_pair) +bottom = phase_space_filter(dx,sdev,1e-4, npoints, 0, N, diagonalizing_pair, 1) +print "Buff width: " + str(top.buffer_width) +left = phase_space_filter(dx,sdev,1e-4, npoints, 1, N, diagonalizing_pair) +right = phase_space_filter(dx,sdev,1e-4, npoints, 1, N, diagonalizing_pair, 1) +kmin = log(1e-6)/sdev + +print "Buffer widths: " + str(top.buffer_width) + "," + str(left.buffer_width) +buffwidth = top.buffer_width + +kf = top.kgrid() +top.P[:] = 0.0 +top.P[0][where( 2*(f*f+g*g)*kf[0] -4*f*g*kf[1] > 0, True, False) ] = 1.0 +top.P[1][where( 2*(f*f+g*g)*kf[0] -4*f*g*kf[1] < 0, True, False) ] = 1.0 +top.P[2] = 1.0 +top.blur_k_filter() + +kf = left.kgrid() +left.P[:] = 0.0 +left.P[0][where( 2*(f*f+g*g)*kf[1] -4*f*g*kf[0] > 0, True, False) ] = 1.0 +left.P[1][where( 2*(f*f+g*g)*kf[1] -4*f*g*kf[0] < 0, True, False) ] = 1.0 +left.P[2] = 0.0 +left.blur_k_filter() + +kf = right.kgrid() +right.P[:] = 0.0 +right.P[0][where( 2*(f*f+g*g)*kf[1] -4*f*g*kf[0] < 0, True, False) ] = 1.0 +right.P[1][where( 2*(f*f+g*g)*kf[1] -4*f*g*kf[0] > 0, True, False) ] = 1.0 +right.P[2] = 0.0 +right.blur_k_filter() + +kf = bottom.kgrid() +bottom.P[:] = 0.0 +bottom.P[0][where( 2*(f*f+g*g)*kf[0] -4*f*g*kf[1] < 0, True, False) ] = 1.0 +bottom.P[1][where( 2*(f*f+g*g)*kf[0] -4*f*g*kf[1] > 0, True, False) ] = 1.0 +bottom.P[2] = 1.0 +bottom.blur_k_filter() + + + +os.system("rm maxwell_long_time.dat") +outfile = open("maxwell_long_time.dat",'w') + +nrm0 = abs(u*u).sum() + +for i in range(int(tmax/dt)): + time = i*dt + + for n in range(N): #FFT the wavefield + u[n] = dft.fft2(u[n]) + u[:] = mmul(D,u) + u *= exp(H*dt) + u[2,:] = 0.0 + u[:] = mmul(DI,u) + for n in range(N): #Inverse FFT the wavefield + u[n] = dft.ifft2(u[n]) + if i % int(top.width()/(12.0*dt)) == 0: #Apply phase space filters before + top(u) #waves can cross half the buffer + left(u) + right(u) + bottom(u) + nrm = abs(u*u).sum() / nrm0 + if i % 8 == 0: + outfile.write(str(time) + "; " + str(nrm) + "\n") + outfile.flush() + print str(time) + "; " + str(nrm) + + + +movie_command_line = "mencoder -ovc lavc -lavcopts vcodec=mpeg1video:vbitrate=1500 -mf type=png:fps=15 -nosound -of mpeg -o " + simdir + "/simulation.mpg mf://" + simdir + "/\*.png" +print "Making movie with command line: " +print movie_command_line +os.system(movie_command_line) + +mp4_movie_command_line = "ffmpeg -r 25 -b 1800 -i " + simdir + "/frame%06d.png " + simdir + "/simulation.mp4" +print mp4_movie_command_line +os.system(mp4_movie_command_line) + diff --git a/tdpsf.py b/tdpsf.py new file mode 100644 index 0000000..0f19d27 --- /dev/null +++ b/tdpsf.py @@ -0,0 +1,83 @@ +from pylab import * +import numpy.fft as dft +import scipy.signal as signal +from utils import * + + +class phase_space_filter: + def __init__(self,dx,sigma,tol, npoints, side, N, dfunc, top_or_bottom=0): + self.dx = dx + self.dk = 2*math.pi/(dx*npoints) + self.side = side + self.tol = tol + self.top_or_bottom = top_or_bottom + self.trans_width = sigma*sqrt(-1*log(tol)+2.0*abs(log(2.0*sigma/sqrt(math.pi)))) + self.trans_width_lattice = int(self.trans_width/self.dx) + self.sigma = sigma + self.buffer_width = next_pow_2(3*self.trans_width_lattice) + self.kbuff = log(tol)/sigma + if self.side==0: + self.shape = (2*self.buffer_width, npoints) + self.chi = empty(shape=self.shape, dtype=Complex32) + self.chi[:] = 0.0 + self.chi[self.trans_width_lattice:self.buffer_width-1*self.trans_width_lattice, self.trans_width_lattice:-1*self.trans_width_lattice] = 1.0 + if self.side==1: + self.shape = (npoints, 2*self.buffer_width) + self.chi = empty(shape=self.shape, dtype=Complex32) + self.chi[:] = 0.0 + self.chi[self.trans_width_lattice:-1*self.trans_width_lattice, self.trans_width_lattice:self.buffer_width-1*self.trans_width_lattice] = 1.0 + self.chi = blur_image(self.chi, self.sigma, self.dx) #This is the x window + + k = kgrid(self.shape, dx) + self.P = empty(shape=(N,) + self.shape, dtype=Complex32) + self.N = N + self.P[:] = 1.0 + + self.buff = empty(shape=(N,) + self.shape, dtype=Complex32) + self.D, self.DI = dfunc(k) + + def blur_k_filter(self): + dk = [2*math.pi/(self.dx*self.P[0].shape[i]) for i in range(2)] + for i in range(self.N): + self.P[i] = blur_image(self.P[i], 1.0/self.sigma, dk) + + def width(self): + return self.buffer_width*self.dx + + def kgrid(self): + return kgrid(self.shape, self.dx) + + def __get_data(self,pos): + if self.top_or_bottom == 0 and self.side == 0: + return pos[:,0:self.buffer_width, :] + if self.top_or_bottom == 1 and self.side == 0: + return pos[:,-1*self.buffer_width:, :] + if self.top_or_bottom == 0 and self.side == 1: + return pos[:,:, 0:self.buffer_width] + if self.top_or_bottom == 1 and self.side == 1: + return pos[:,:, -1*self.buffer_width:] + + + def __call__(self,pos): + for i in range(self.N): + if self.side == 0: + self.buff[i,:] = 0 + self.buff[i,0:self.buffer_width,:] = self.__get_data(pos)[i] + self.buff[i,:]*self.chi + self.buff[i,:] = dft.fft2(self.buff[i,:]) + if self.side == 1: + self.buff[i,:] = 0 + self.buff[i,:,0:self.buffer_width] = self.__get_data(pos)[i] + self.buff[i,:]*self.chi + self.buff[i,:] = dft.fft2(self.buff[i,:]) + + self.buff = mmul(self.D, self.buff) + self.buff *= self.P + self.buff = mmul(self.DI, self.buff) + for i in range(self.N): + self.buff[i,:] = dft.ifft2(self.buff[i,:]) + self.buff *= self.chi + if self.side == 0: + self.__get_data(pos)[:] -= self.buff[:,0:self.buffer_width,:] + if self.side == 1: + self.__get_data(pos)[:] -= self.buff[:,:,0:self.buffer_width] diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..6f3dd36 --- /dev/null +++ b/utils.py @@ -0,0 +1,42 @@ +from pylab import * +import scipy.signal as signal +import numpy.fft as dft +import math + +def next_pow_2(n): + i = 0 + while pow(2,i) < n: + i += 1 + return pow(2,i) + +def mmul(A,x): + dim = x.shape[0] + result = x.copy() + for i in range(dim): + result[i] = (A[i]*x).sum(axis=0) + return result + +def kgrid(shape, dx): #Returns a kgrid, given a shape and a lattice spacing + if type(dx) is tuple or type(dx) is list: + dk = [ 2*math.pi/(dx[i]*shape[i]) for i in range(2)] + else: + dk = [ 2*math.pi/(dx*shape[i]) for i in range(2)] + k = indices(shape,dtype=Float32) + 0.000001 + for i in range(2): + k[i,:] *= dk[i] + k[i,where(k[i,:] > dk[i]*(shape[i]-1)/2,True,False)] -= shape[i]*dk[i] + return k + +def blur_image(im, sigma, dx): + """Blurs the image in the Fourier domain.""" + kim = dft.fft2(im) + kx, ky = kgrid(kim.shape, dx) + kim *= exp(-1*(kx**2+ky**2)/(sigma*sigma)) + xim = dft.ifft2(kim) + if abs(xim).max() == 0: + xim = 0 + else: + xim /= xim.max() + return xim + + diff --git a/wave.py b/wave.py new file mode 100644 index 0000000..127d3b4 --- /dev/null +++ b/wave.py @@ -0,0 +1,83 @@ +import os +from pylab import * +import numpy.fft as dft +from utils import * + +simname = "wave" +simdir = simname+"_plots" + +npoints = 256 +shape=(npoints, npoints) +dx = 0.125 +dt = 0.25 +tmax = 24 +x = indices(shape)*dx +x[0] -= npoints*dx/2 +x[1] -= npoints*dx/2 + +dk = 2*math.pi/(dx*npoints) +kmax = math.pi/dx +k = kgrid(shape,dx) + +root_k = complex(0,1)*sqrt(k[0]*k[0]+k[1]*k[1]) +root_k[0,0] = complex(0,1) + +N = 2 #Number of components of the wavefield + +u = empty(shape=(N,) + shape, dtype=Complex32) #The wavefield itself +u[:] = 0 +u[0] = exp(-1*(x[0]*x[0]+x[1]*x[1])/3.0)*exp((x[0]+x[1])*complex(0,-0.5)*math.pi/(dx*npoints)) + +D = empty(shape=(N,N) + shape, dtype=Complex32) #Diagonalizes the Hamiltonian +D[0,0] = 1 +D[0,1] = 1/root_k +D[1,0] = 1 +D[1,1] = -1/root_k + +H = empty(shape=(N,) + shape, dtype=Complex32) #Hamiltonian +H[0,:] = root_k +H[1,:] = -1*root_k +H[:,0,0] = 0.0 + +DI = empty(shape=(N,N) + shape, dtype=Complex32) #Diagonalizes the Hamiltonian +DI[0,0] = 0.5 +DI[0,1] = 0.5 +DI[1,0] = 0.5*root_k +DI[1,1] = -0.5*root_k + +def mmul(A,x): + dim = x.shape[0] + result = x.copy() + for i in range(dim): + result[i] = (A[i]*x).sum(axis=0) + return result + +hot() #Choose the color scheme +os.system("rm -rf " + simdir + "; mkdir " + simdir) +for i in range(int(tmax/dt)): + time = i*dt + print "Time = " + str(time) + for n in range(N): #FFT the wavefield + u[n] = dft.fft2(u[n]) + u[:] = mmul(D,u) + u *= exp(H*dt) + u[:] = mmul(DI,u) + for n in range(N): #Inverse FFT the wavefield + u[n] = dft.ifft2(u[n]) + + clf()#Now plot things + subplot(221) + imshow(u[0].real) + title("$u_0(x,"+str(time)+")$") + colorbar() + subplot(222) + imshow(u[1].real) + title("$u_1(x,"+str(time)+")$") + colorbar() + savefig(os.path.join(simdir, "frame" + str(i).rjust(6,"0")+".png")) + +movie_command_line = "mencoder -ovc lavc -lavcopts vcodec=mpeg1video:vbitrate=1500 -mf type=png:fps=12 -nosound -of mpeg -o " + simdir + "/simulation.mpg mf://" + simdir + "/\*.png" +print "Making movie with command line: " +print movie_command_line +os.system(movie_command_line) +
stucchio/TDPSF-Simplified-Examples
f06eecbf68758098662d37e03f53050ad28b1059
Added simple 1-D schrodinger example.
diff --git a/schrodinger_test.py b/schrodinger_test.py new file mode 100644 index 0000000..d16d11b --- /dev/null +++ b/schrodinger_test.py @@ -0,0 +1,114 @@ +from math import * +import os +from pylab import * +from scipy.special import * +import numpy.fft as dft +import scipy.signal as signal + + +npoints = 1024 +npointsl = 1024*8 +dx = 0.1 + +def xg(np,d_x): + return (arange(np,dtype=float)-np/2.0)*d_x + +def kg(np, d_x): + k = arange(np,dtype=float) + k[np/2:] -= np + k *= (2*pi/(d_x*np)) + return k + +x = xg(npoints,dx) +k = kg(npoints,dx) +xl = xg(npointsl,dx) +kl = kg(npointsl,dx) + +kmax = pi/dx +L = npoints*dx/2.0 + +psi = zeros(npoints, dtype=complex) + +psil = zeros(npointsl, dtype=complex) + +print "X domain: [" + str(x[0]) + ", " + str(x[-1]) + "]" +print "K domain: [" + str(-kmax) + ", " + str(kmax) + "]" + +def erfinv(x): + return sqrt(log(1.0/x)+log(pi)/2-log(2)) + +class tdpsf: + def __init__(self,npoints,dx, tol=1e-6): + self.npoints = npoints + self.dx = dx + L = npoints*dx/2.0 + x = xg(npoints/4,dx) + k = kg(npoints/4,dx) + kmax = pi/dx + bx = erfinv(tol)#sqrt(log(1.0/tol)) + if bx > L/8: + print "Error, bx="+str(bx) + " > L="+str(L) + self.chi = 0.5*(erf((x+bx)/sqrt(2.0))-erf((x-bx)/sqrt(2.0))) + bk = kmax/2.0-1.5*erfinv(tol/L) + if bk < kmax/4: + print "Error, bk="+str(bk) + " < kmax/4="+str(kmax/4) + bk = 0 + self.P = 0.5*erfc((bk-k)/2) + + def __call__(self,grid): + tmp = self.chi*grid[3*self.npoints/4:] + tmp[:] = dft.fft(tmp) + tmp *= self.P + tmp = self.chi*dft.ifft(tmp) + grid[3*self.npoints/4:] -= tmp + +def exact(x,v,t,sigma): + i = complex(0,1) + return (exp(i*v*(x-v*t/2.0))/(2.0*sqrt(sigma)*(1.0+i*t/(sigma*sigma))))*exp(-1*((x-v*t)**2)/(2.0*(sigma*sigma)*(1+i*t/(sigma*sigma)))) + +def error_test(vel,epsilon): + sigma = 7.0 + tmax = 4*L/vel + dt = ((L/2)/kmax)/18 + psi[:] = exact(x,vel,0.0,sigma)#exp(-1.0*(x*x/16.0)+complex(0,vel)*x) + psil[:] = exact(xl,vel,0.0,sigma) + m0 = sqrt(abs(psi[npoints/4:-npoints/4]**2).sum()) + + prop = exp(complex(0,-dt/2.0)*k*k) + propl = exp(complex(0,-dt/2.0)*kl*kl) + fil = tdpsf(npoints,dx,epsilon) + + nsteps = int(tmax/dt)+1 + err = 0.0 + for i in range(nsteps): + psi[:] = dft.ifft(prop*dft.fft(psi)) #Calculate TDPSF approximation + fil(psi) + + psil[:] = dft.ifft(propl*dft.fft(psil)) #Calculate large box solution + + rem = abs(psil[npointsl/2-npoints/4:npointsl/2+npoints/4] - psi[npoints/2-npoints/4:npoints/2+npoints/4]) + + local_err = sqrt((rem*rem).sum())/m0 + if local_err > err: + err = local_err + #print str(v) +", " + str(i*dt) + ", " + str(err) + #print "T="+str(i*dt) + ", M = " + str(sqrt(abs(psi*psi).sum()*dx)/m0) + print "k = " + str(vel) + ", epsilon = " + str(epsilon) + ", err = " + str(err) + return err + +if __name__=="__main__": + velocities = arange(25,1,-1) + eps_powers = [2,3,4,5, 6] + err = [[error_test(float(v),pow(10,-eps_pow)) for v in velocities] for eps_pow in eps_powers] + clf() + for e in enumerate(eps_powers): + semilogy(velocities,err[e[0]],label="$\delta=10^{-" + str(e[1]) + "}$") + xlabel("Frequency ($k$)") + ylabel("Relative Error in $L^2$") + title("Errors for the Schrodinger Equation") +## axvline(x=kmax/2.0, label="$k_{max}/2$") +## axvline(x=kmax/4.0, label="$k_{max}/4$") + legend() + savefig("schrodinger_error.eps") + legend() +
djspiewak/scala-collections
c785a40bfddb3c1fdfa0a03245eb9f4dbde5d453
Optimized VectorBuilder by creating trie in one pass (rather than incrementally)
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala index f17dbe5..6d9d887 100644 --- a/src/main/scala/com/codecommit/collection/Vector.scala +++ b/src/main/scala/com/codecommit/collection/Vector.scala @@ -1,654 +1,762 @@ /** Copyright (c) 2007-2008, Rich Hickey All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Clojure nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package com.codecommit.collection import scala.collection.IndexedSeqLike import scala.collection.generic._ import scala.collection.immutable.IndexedSeq -import scala.collection.mutable.Builder +import scala.collection.mutable.{ArrayBuffer, Builder} import VectorCases._ /** * A straight port of Clojure's <code>PersistentVector</code> class (with some * additional optimizations which may eventually land in Clojure's mainline). * For the record, this implementation is about 30% faster than * {@link scala.collection.immutable.Vector} on reads and about 5% slower for * "writes". * * @author Daniel Spiewak * @author Rich Hickey */ -class Vector[+T] private (val length: Int, trie: Case, tail: Array[AnyRef]) +class Vector[+T] private[collection] (val length: Int, trie: Case, tail: Array[AnyRef]) extends IndexedSeq[T] with GenericTraversableTemplate[T, Vector] with IndexedSeqLike[T, Vector[T]] { outer => private val tailOff = length - tail.length override def companion = Vector /* * The design of this data structure inherantly requires heterogenous arrays. * It is *possible* to design around this, but the result is comparatively * quite inefficient. With respect to this fact, I have left the original * (somewhat dynamically-typed) implementation in place. */ private[collection] def this() = this(0, Zero, Vector.EmptyArray) def apply(i: Int): T = { if (i >= 0 && i < length) { if (i >= tailOff) { tail(i & 0x01f).asInstanceOf[T] } else { var arr = trie(i) arr(i & 0x01f).asInstanceOf[T] } } else throw new IndexOutOfBoundsException(i.toString) } def update[A >: T](i: Int, obj: A): Vector[A] = { if (i >= 0 && i < length) { if (i >= tailOff) { val newTail = new Array[AnyRef](tail.length) Array.copy(tail, 0, newTail, 0, tail.length) newTail(i & 0x01f) = obj.asInstanceOf[AnyRef] new Vector[A](length, trie, newTail) } else { new Vector[A](length, trie(i) = obj.asInstanceOf[AnyRef], tail) } } else if (i == length) { this + obj } else throw new IndexOutOfBoundsException(i.toString) } def +[A >: T](obj: A): Vector[A] = { if (tail.length < 32) { val tail2 = new Array[AnyRef](tail.length + 1) Array.copy(tail, 0, tail2, 0, tail.length) tail2(tail.length) = obj.asInstanceOf[AnyRef] new Vector[A](length + 1, trie, tail2) } else { new Vector[A](length + 1, trie + tail, Vector.array(obj.asInstanceOf[AnyRef])) } } /** * Removes the <i>tail</i> element of this vector. */ def pop: Vector[T] = { if (length == 0) { throw new IllegalStateException("Can't pop empty vector") } else if (length == 1) { Vector.empty } else if (tail.length > 1) { val tail2 = new Array[AnyRef](tail.length - 1) Array.copy(tail, 0, tail2, 0, tail2.length) new Vector[T](length - 1, trie, tail2) } else { val (trie2, tail2) = trie.pop new Vector[T](length - 1, trie2, tail2) } } } final class VectorBuilder[A] extends Builder[A, Vector[A]] { // TODO optimize - private var tmp = Vector.empty[A] + private val buffer = new ArrayBuffer[A] + + val ZeroThresh = 0 + val OneThresh = 32 + val TwoThresh = 32 << 5 + val ThreeThresh = 32 << 10 + val FourThresh = 32 << 15 + val FiveThresh = 32 << 20 + val SixThresh = 32 << 25 def +=(elem: A) = { - tmp += elem + buffer += elem this } - def result = tmp + def result = { + import VectorCases._ + + val tailLength = if (buffer.length % 32 == 0) 32 else buffer.length % 32 + val trieBuffer = buffer.view(0, buffer.length - tailLength) + val tailBuffer = buffer.view(buffer.length - tailLength, buffer.length) + + val trie = if (trieBuffer.length <= ZeroThresh) + Zero + else if (trieBuffer.length <= OneThresh) + One(fillArray1(trieBuffer)) + else if (trieBuffer.length <= TwoThresh) + Two(fillArray2(trieBuffer)) + else if (trieBuffer.length <= ThreeThresh) + Three(fillArray3(trieBuffer)) + else if (trieBuffer.length <= FourThresh) + Four(fillArray4(trieBuffer)) + else if (trieBuffer.length <= FiveThresh) + Five(fillArray5(trieBuffer)) + else if (trieBuffer.length <= SixThresh) + Six(fillArray6(trieBuffer)) + else + throw new IllegalStateException("Cannot build vector with length which exceeds MAX_INT") + + new Vector[A](buffer.length, trie, fillArray1(tailBuffer)) + } + + private def fillArray6(seq: Seq[_]) = { + val CellSize = FiveThresh + val length = if (seq.length % CellSize == 0) seq.length / CellSize else (seq.length / CellSize) + 1 + val back = new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](length) + + for (i <- 0 until back.length) { + val buffer = seq.view(i * CellSize, Math.min((i + 1) * CellSize, seq.length)) + back(i) = fillArray5(buffer) + } + + back + } + + private def fillArray5(seq: Seq[_]) = { + val CellSize = FourThresh + val length = if (seq.length % CellSize == 0) seq.length / CellSize else (seq.length / CellSize) + 1 + val back = new Array[Array[Array[Array[Array[AnyRef]]]]](length) + + for (i <- 0 until back.length) { + val buffer = seq.view(i * CellSize, Math.min((i + 1) * CellSize, seq.length)) + back(i) = fillArray4(buffer) + } + + back + } + + private def fillArray4(seq: Seq[_]) = { + val CellSize = ThreeThresh + val length = if (seq.length % CellSize == 0) seq.length / CellSize else (seq.length / CellSize) + 1 + val back = new Array[Array[Array[Array[AnyRef]]]](length) + + for (i <- 0 until back.length) { + val buffer = seq.view(i * CellSize, Math.min((i + 1) * CellSize, seq.length)) + back(i) = fillArray3(buffer) + } + + back + } + + private def fillArray3(seq: Seq[_]) = { + val CellSize = TwoThresh + val length = if (seq.length % CellSize == 0) seq.length / CellSize else (seq.length / CellSize) + 1 + val back = new Array[Array[Array[AnyRef]]](length) + + for (i <- 0 until back.length) { + val buffer = seq.view(i * CellSize, Math.min((i + 1) * CellSize, seq.length)) + back(i) = fillArray2(buffer) + } + + back + } + + private def fillArray2(seq: Seq[_]) = { + val CellSize = OneThresh + val length = if (seq.length % CellSize == 0) seq.length / CellSize else (seq.length / CellSize) + 1 + val back = new Array[Array[AnyRef]](length) + + for (i <- 0 until back.length) { + val buffer = seq.view(i * CellSize, Math.min((i + 1) * CellSize, seq.length)) + back(i) = fillArray1(buffer) + } + + back + } + + private def fillArray1(seq: Seq[_]) = { + val back = new Array[AnyRef](seq.length) + + for ((e, i) <- seq.zipWithIndex) { + back(i) = e.asInstanceOf[AnyRef] + } + + back + } def clear() { - tmp = Vector.empty[A] + buffer.clear() } } object Vector extends SeqFactory[Vector] { @inline implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Vector[A]] = new GenericCanBuildFrom[A] { override def apply = newBuilder[A] } def newBuilder[A] = new VectorBuilder[A] private[collection] val EmptyArray = new Array[AnyRef](0) private[this] val emptyVector = new Vector[Nothing] @inline override def empty[A]: Vector[A] = emptyVector @inline private[collection] def array(elem: AnyRef) = { val back = new Array[AnyRef](1) back(0) = elem back } } private[collection] object VectorCases { @inline private[this] def copy1(array1: Array[AnyRef], array2: Array[AnyRef]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy2(array1: Array[Array[AnyRef]], array2: Array[Array[AnyRef]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy3(array1: Array[Array[Array[AnyRef]]], array2: Array[Array[Array[AnyRef]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy4(array1: Array[Array[Array[Array[AnyRef]]]], array2: Array[Array[Array[Array[AnyRef]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy5(array1: Array[Array[Array[Array[Array[AnyRef]]]]], array2: Array[Array[Array[Array[Array[AnyRef]]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy6(array1: Array[Array[Array[Array[Array[Array[AnyRef]]]]]], array2: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } sealed trait Case { type Self <: Case val shift: Int def apply(i: Int): Array[AnyRef] def update(i: Int, obj: AnyRef): Self def +(node: Array[AnyRef]): Case def pop: (Case, Array[AnyRef]) } case object Zero extends Case { type Self = Nothing val shift = -1 def apply(i: Int) = throw new IndexOutOfBoundsException(i.toString) def update(i: Int, obj: AnyRef) = throw new IndexOutOfBoundsException(i.toString) def +(node: Array[AnyRef]) = One(node) def pop = throw new IndexOutOfBoundsException("Cannot pop an empty Vector") } case class One(trie: Array[AnyRef]) extends Case { type Self = One val shift = 0 def apply(i: Int) = trie def update(i: Int, obj: AnyRef) = { val trie2 = copy1(trie, new Array[AnyRef](trie.length)) trie2(i & 0x01f) = obj One(trie2) } def +(tail: Array[AnyRef]) = { val trie2 = new Array[Array[AnyRef]](2) trie2(0) = trie trie2(1) = tail Two(trie2) } def pop = (Zero, trie) } case class Two(trie: Array[Array[AnyRef]]) extends Case { type Self = Two val shift = 5 def apply(i: Int) = trie((i >>> 5) & 0x01f) def update(i: Int, obj: AnyRef) = { val trie2a = copy2(trie, new Array[Array[AnyRef]](trie.length)) val trie2b = { val target = trie2a((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2a((i >>> 5) & 0x01f) = trie2b trie2b(i & 0x01f) = obj Two(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.length >= 32) { val trie2 = new Array[Array[Array[AnyRef]]](2) trie2(0) = trie trie2(1) = new Array[Array[AnyRef]](1) trie2(1)(0) = tail Three(trie2) } else { val trie2 = copy2(trie, new Array[Array[AnyRef]](trie.length + 1)) trie2(trie.length) = tail Two(trie2) } } def pop = { if (trie.length == 2) { (One(trie(0)), trie.last) } else { val trie2 = copy2(trie, new Array[Array[AnyRef]](trie.length - 1)) (Two(trie2), trie.last) } } } case class Three(trie: Array[Array[Array[AnyRef]]]) extends Case { type Self = Three val shift = 10 def apply(i: Int) = { val a = trie((i >>> 10) & 0x01f) a((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) val trie2b = { val target = trie2a((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2a((i >>> 10) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2b((i >>> 5) & 0x01f) = trie2c trie2c(i & 0x01f) = obj Three(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[AnyRef]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0) = tail Four(trie2) } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length + 1)) trie2(trie.length) = new Array[Array[AnyRef]](1) trie2(trie.length)(0) = tail Three(trie2) } } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) trie2(trie2.length - 1) = copy2(trie2.last, new Array[Array[AnyRef]](trie2.last.length + 1)) trie2.last(trie.last.length) = tail Three(trie2) } } def pop = { if (trie.last.length == 1) { if (trie.length == 2) { (Two(trie(0)), trie.last.last) } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length - 1)) (Three(trie2), trie.last.last) } } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) trie2(trie2.length - 1) = copy2(trie2.last, new Array[Array[AnyRef]](trie2.last.length - 1)) (Three(trie2), trie.last.last) } } } case class Four(trie: Array[Array[Array[Array[AnyRef]]]]) extends Case { type Self = Four val shift = 15 def apply(i: Int) = { val a = trie((i >>> 15) & 0x01f) val b = a((i >>> 10) & 0x01f) b((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2a((i >>> 15) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2b((i >>> 10) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2c((i >>> 5) & 0x01f) = trie2d trie2d(i & 0x01f) = obj Four(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[Array[AnyRef]]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(1)(0) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0)(0) = tail Five(trie2) } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0) = tail Four(trie2) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length + 1)) trie2.last(trie.last.length) = new Array[Array[AnyRef]](1) trie2.last.last(0) = tail Four(trie2) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy2(trie2.last.last, new Array[Array[AnyRef]](trie2.last.last.length + 1)) trie2.last.last(trie.last.last.length) = tail Four(trie2) } } def pop = { if (trie.last.last.length == 1) { if (trie.last.length == 1) { if (trie.length == 2) { (Three(trie(0)), trie.last.last.last) } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length - 1)) (Four(trie2), trie.last.last.last) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length - 1)) (Four(trie2), trie.last.last.last) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy2(trie2.last.last, new Array[Array[AnyRef]](trie2.last.last.length - 1)) (Four(trie2), trie.last.last.last) } } } case class Five(trie: Array[Array[Array[Array[Array[AnyRef]]]]]) extends Case { type Self = Five val shift = 20 def apply(i: Int) = { val a = trie((i >>> 20) & 0x01f) val b = a((i >>> 15) & 0x01f) val c = b((i >>> 10) & 0x01f) c((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 20) & 0x01f) copy4(target, new Array[Array[Array[Array[AnyRef]]]](target.length)) } trie2a((i >>> 20) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2b((i >>> 15) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2c((i >>> 10) & 0x01f) = trie2d val trie2e = { val target = trie2d((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2d((i >>> 5) & 0x01f) = trie2e trie2e(i & 0x01f) = obj Five(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.last.length >= 32) { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[Array[Array[AnyRef]]]]](1) trie2(1)(0) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(1)(0)(0) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0)(0)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0)(0)(0) = tail Six(trie2) } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(trie.length)(0) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0)(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length + 1)) trie2.last(trie.last.length) = new Array[Array[Array[AnyRef]]](1) trie2.last.last(0) = new Array[Array[AnyRef]](1) trie2.last.last.last(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length + 1)) trie2.last.last(trie.last.last.length) = new Array[Array[AnyRef]](1) trie2.last.last.last(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length)) trie2.last.last(trie2.last.last.length - 1) = copy2(trie2.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.length + 1)) trie2.last.last.last(trie.last.last.last.length) = tail Five(trie2) } } def pop = { if (trie.last.last.last.length == 1) { if (trie.last.last.length == 1) { if (trie.last.length == 1) { if (trie.length == 2) { (Four(trie(0)), trie.last.last.last.last) } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length - 1)) trie2.last.last(trie2.last.last.length - 1) = copy2(trie2.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } } case class Six(trie: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) extends Case { type Self = Six val shift = 25 def apply(i: Int) = { val a = trie((i >>> 25) & 0x01f) val b = a((i >>> 20) & 0x01f) val c = b((i >>> 15) & 0x01f) val d = c((i >>> 10) & 0x01f) d((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 25) & 0x01f) copy5(target, new Array[Array[Array[Array[Array[AnyRef]]]]](target.length)) } trie2a((i >>> 25) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 20) & 0x01f) copy4(target, new Array[Array[Array[Array[AnyRef]]]](target.length)) } trie2b((i >>> 20) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2c((i >>> 15) & 0x01f) = trie2d val trie2e = { val target = trie2d((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2d((i >>> 10) & 0x01f) = trie2e val trie2f = { val target = trie2e((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2e((i >>> 5) & 0x01f) = trie2f trie2f(i & 0x01f) = obj Six(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.last.last.length >= 32) { if (trie.last.last.last.length >= 32) { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { throw new IndexOutOfBoundsException("Cannot grow vector beyond integer bounds") } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[Array[Array[AnyRef]]]]](1) trie2(trie.length)(0) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(trie.length)(0)(0) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0)(0)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0)(0)(0) = tail Six(trie2) } } else { diff --git a/src/spec/scala/VectorSpecs.scala b/src/spec/scala/VectorSpecs.scala index d6d8132..14e9038 100644 --- a/src/spec/scala/VectorSpecs.scala +++ b/src/spec/scala/VectorSpecs.scala @@ -1,387 +1,408 @@ import org.specs._ import org.scalacheck._ -import com.codecommit.collection.Vector +import com.codecommit.collection.{Vector, VectorBuilder} object VectorSpecs extends Specification with ScalaCheck { import Prop._ val vector = Vector[Int]() implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = { Arbitrary(for { data <- Arbitrary.arbitrary[List[A]] } yield data.foldLeft(Vector[A]()) { _ + _ }) } "vector" should { "store a single element" in { val prop = forAll { (i: Int, e: Int) => i >= 0 ==> ((vector(0) = e)(0) == e) } prop must pass } "implement length" in { val prop = forAll { (list: List[Int]) => val vec = list.foldLeft(Vector[Int]()) { _ + _ } vec.length == list.length } prop must pass } "replace single element" in { val prop = forAll { (vec: Vector[Int], i: Int) => (!vec.isEmpty && i > Math.MIN_INT) ==> { val idx = Math.abs(i) % vec.length val newVector = (vec(idx) = "test")(idx) = "newTest" newVector(idx) == "newTest" } } prop must pass } "fail on apply out-of-bounds" in { val prop = forAll { (vec: Vector[Int], i: Int) => !((0 until vec.length) contains i) ==> { try { vec(i) false } catch { case _: IndexOutOfBoundsException => true } } } prop must pass } "fail on update out-of-bounds" in { val prop = forAll { (vec: Vector[Int], i: Int) => !((0 to vec.length) contains i) ==> { try { vec(i) = 42 false } catch { case _: IndexOutOfBoundsException => true } } } prop must pass } "pop elements" in { val prop = forAll { vec: Vector[Int] => vec.length > 0 ==> { val popped = vec.pop var back = popped.length == vec.length - 1 for (i <- 0 until popped.length) { back &&= popped(i) == vec(i) } back } } prop must pass(set(maxSize -> 3000, minTestsOk -> 1000)) } "fail on pop empty vector" in { val caughtExcept = try { Vector.empty.pop false } catch { case _: IllegalStateException => true } caughtExcept mustEqual true } "store multiple elements in order" in { val prop = forAll { list: List[Int] => val newVector = list.foldLeft(vector) { _ + _ } val res = for (i <- 0 until list.length) yield newVector(i) == list(i) res forall { _ == true } } prop must pass } "store lots of elements" in { val LENGTH = 100000 val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ } vector.length mustEqual LENGTH for (i <- 0 until LENGTH) { vector(i) mustEqual i } } "maintain both old and new versions after conj" in { val prop = forAll { vec: Vector[Int] => val vec2 = vec + 42 for (i <- 0 until vec.length) { vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin") } vec2.last mustEqual 42 } prop must pass(set(maxSize -> 3000, minTestsOk -> 1000)) } "maintain both old and new versions after update" in { val prop = forAll { (vec: Vector[Int], i: Int) => (!vec.isEmpty && i > Math.MIN_INT) ==> { val idx = Math.abs(i) % vec.length val vec2 = vec(idx) = 42 for (i <- 0 until vec.length if i != idx) { vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin") } vec2(idx) mustEqual 42 } } prop must pass(set(maxSize -> 3000, minTestsOk -> 1000)) } "maintain both old and new versions after pop" in { val prop = forAll { vec: Vector[Int] => !vec.isEmpty ==> { val vec2 = vec.pop for (i <- 0 until vec.length - 1) { vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin") } vec2.length mustEqual vec.length - 1 } } prop must pass(set(maxSize -> 3000, minTestsOk -> 1000)) } "implement filter" in { val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) => val filtered = vec filter f var back = filtered forall f for (e <- vec) { if (f(e)) { back &&= filtered.contains(e) } } back } prop must pass } "implement foldLeft" in { val prop = forAll { list: List[Int] => val vec = list.foldLeft(Vector[Int]()) { _ + _ } vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ } } prop must pass } "implement forall" in { val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) => val bool = vec forall f var back = true for (e <- vec) { back &&= f(e) } (back && bool) || (!back && !bool) } prop must pass } "implement flatMap" in { val prop = forAll { (vec: Vector[Int], f: (Int)=>Vector[Int]) => val mapped = vec flatMap f var back = true var i = 0 var n = 0 while (i < vec.length) { val res = f(vec(i)) var inner = 0 while (inner < res.length) { back &&= mapped(n) == res(inner) inner += 1 n += 1 } i += 1 } back } prop must pass } "implement map" in { val prop = forAll { (vec: Vector[Int], f: (Int)=>Int) => val mapped = vec map f var back = vec.length == mapped.length for (i <- 0 until vec.length) { back &&= mapped(i) == f(vec(i)) } back } prop must pass } "implement reverse" in { val prop = forAll { v: Vector[Int] => val reversed = v.reverse var back = v.length == reversed.length for (i <- 0 until v.length) { back &&= reversed(i) == v(v.length - i - 1) } back } prop must pass } "append to reverse" in { val prop = forAll { (v: Vector[Int], n: Int) => val rev = v.reverse val add = rev + n var back = add.length == rev.length + 1 for (i <- 0 until rev.length) { back &&= add(i) == rev(i) } back && add(rev.length) == n } prop must pass } "map on reverse" in { val prop = forAll { (v: Vector[Int], f: (Int)=>Int) => val rev = v.reverse val mapped = rev map f var back = mapped.length == rev.length for (i <- 0 until rev.length) { back &&= mapped(i) == f(rev(i)) } back } prop must pass } "implement zip" in { val prop = forAll { (first: Vector[Int], second: Vector[Double]) => val zip = first zip second var back = zip.length == Math.min(first.length, second.length) for (i <- 0 until zip.length) { var (left, right) = zip(i) back &&= (left == first(i) && right == second(i)) } back } prop must pass } "implement zipWithIndex" in { val prop = forAll { vec: Vector[Int] => val zip = vec.zipWithIndex var back = zip.length == vec.length for (i <- 0 until zip.length) { val (elem, index) = zip(i) back &&= (index == i && elem == vec(i)) } back } prop must pass } "implement equals" in { { val prop = forAll { list: List[Int] => val vecA = list.foldLeft(Vector[Int]()) { _ + _ } val vecB = list.foldLeft(Vector[Int]()) { _ + _ } vecA == vecB } prop must pass } { val prop = forAll { (vecA: Vector[Int], vecB: Vector[Int]) => vecA.length != vecB.length ==> (vecA != vecB) } prop must pass } { val prop = forAll { (listA: List[Int], listB: List[Int]) => val vecA = listA.foldLeft(Vector[Int]()) { _ + _ } val vecB = listB.foldLeft(Vector[Int]()) { _ + _ } listA != listB ==> (vecA != vecB) } prop must pass } { val prop = forAll { (vec: Vector[Int], data: Int) => vec != data } prop must pass } } "implement hashCode" in { val prop = forAll { list: List[Int] => val vecA = list.foldLeft(Vector[Int]()) { _ + _ } val vecB = list.foldLeft(Vector[Int]()) { _ + _ } vecA.hashCode == vecB.hashCode } prop must pass } "implement extractor" in { val vec1 = Vector(1, 2, 3) vec1 must beLike { case Vector(a, b, c) => (a, b, c) == (1, 2, 3) } val vec2 = Vector("daniel", "chris", "joseph") vec2 must beLike { case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph") } } } + + "vector builder" should { + "build a vector of arbitrary length" in { + val prop = forAll { i: Int => + i > Math.MIN_INT ==> { + val length = Math.abs(i) % (32 << 16) + val builder = new VectorBuilder[Int] + 0 until length foreach (builder +=) + val vector = builder.result + + vector.length mustEqual length + for (i <- 0 until vector.length) { + vector(i) aka ("vector element at index " + i) mustEqual i + } + true + } + } + + prop must pass(set(maxSize -> 25, minTestsOk -> 12)) + } + } }
djspiewak/scala-collections
045f971ec662a7d7f8dc9718051cf0835caa6e37
Removed EmptyVector
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala index d7439d6..f17dbe5 100644 --- a/src/main/scala/com/codecommit/collection/Vector.scala +++ b/src/main/scala/com/codecommit/collection/Vector.scala @@ -1,681 +1,681 @@ /** Copyright (c) 2007-2008, Rich Hickey All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Clojure nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package com.codecommit.collection import scala.collection.IndexedSeqLike import scala.collection.generic._ import scala.collection.immutable.IndexedSeq import scala.collection.mutable.Builder import VectorCases._ /** * A straight port of Clojure's <code>PersistentVector</code> class (with some * additional optimizations which may eventually land in Clojure's mainline). * For the record, this implementation is about 30% faster than * {@link scala.collection.immutable.Vector} on reads and about 5% slower for * "writes". * * @author Daniel Spiewak * @author Rich Hickey */ class Vector[+T] private (val length: Int, trie: Case, tail: Array[AnyRef]) extends IndexedSeq[T] with GenericTraversableTemplate[T, Vector] with IndexedSeqLike[T, Vector[T]] { outer => private val tailOff = length - tail.length override def companion = Vector /* * The design of this data structure inherantly requires heterogenous arrays. * It is *possible* to design around this, but the result is comparatively * quite inefficient. With respect to this fact, I have left the original * (somewhat dynamically-typed) implementation in place. */ private[collection] def this() = this(0, Zero, Vector.EmptyArray) def apply(i: Int): T = { if (i >= 0 && i < length) { if (i >= tailOff) { tail(i & 0x01f).asInstanceOf[T] } else { var arr = trie(i) arr(i & 0x01f).asInstanceOf[T] } } else throw new IndexOutOfBoundsException(i.toString) } def update[A >: T](i: Int, obj: A): Vector[A] = { if (i >= 0 && i < length) { if (i >= tailOff) { val newTail = new Array[AnyRef](tail.length) Array.copy(tail, 0, newTail, 0, tail.length) newTail(i & 0x01f) = obj.asInstanceOf[AnyRef] new Vector[A](length, trie, newTail) } else { new Vector[A](length, trie(i) = obj.asInstanceOf[AnyRef], tail) } } else if (i == length) { this + obj } else throw new IndexOutOfBoundsException(i.toString) } def +[A >: T](obj: A): Vector[A] = { if (tail.length < 32) { val tail2 = new Array[AnyRef](tail.length + 1) Array.copy(tail, 0, tail2, 0, tail.length) tail2(tail.length) = obj.asInstanceOf[AnyRef] new Vector[A](length + 1, trie, tail2) } else { new Vector[A](length + 1, trie + tail, Vector.array(obj.asInstanceOf[AnyRef])) } } /** * Removes the <i>tail</i> element of this vector. */ def pop: Vector[T] = { if (length == 0) { throw new IllegalStateException("Can't pop empty vector") } else if (length == 1) { - EmptyVector + Vector.empty } else if (tail.length > 1) { val tail2 = new Array[AnyRef](tail.length - 1) Array.copy(tail, 0, tail2, 0, tail2.length) new Vector[T](length - 1, trie, tail2) } else { val (trie2, tail2) = trie.pop new Vector[T](length - 1, trie2, tail2) } } } final class VectorBuilder[A] extends Builder[A, Vector[A]] { // TODO optimize private var tmp = Vector.empty[A] def +=(elem: A) = { tmp += elem this } def result = tmp def clear() { tmp = Vector.empty[A] } } object Vector extends SeqFactory[Vector] { @inline implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Vector[A]] = new GenericCanBuildFrom[A] { override def apply = newBuilder[A] } def newBuilder[A] = new VectorBuilder[A] private[collection] val EmptyArray = new Array[AnyRef](0) + private[this] val emptyVector = new Vector[Nothing] + @inline - override def empty[A]: Vector[A] = EmptyVector + override def empty[A]: Vector[A] = emptyVector @inline private[collection] def array(elem: AnyRef) = { val back = new Array[AnyRef](1) back(0) = elem back } } -object EmptyVector extends Vector[Nothing] - private[collection] object VectorCases { @inline private[this] def copy1(array1: Array[AnyRef], array2: Array[AnyRef]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy2(array1: Array[Array[AnyRef]], array2: Array[Array[AnyRef]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy3(array1: Array[Array[Array[AnyRef]]], array2: Array[Array[Array[AnyRef]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy4(array1: Array[Array[Array[Array[AnyRef]]]], array2: Array[Array[Array[Array[AnyRef]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy5(array1: Array[Array[Array[Array[Array[AnyRef]]]]], array2: Array[Array[Array[Array[Array[AnyRef]]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy6(array1: Array[Array[Array[Array[Array[Array[AnyRef]]]]]], array2: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } sealed trait Case { type Self <: Case val shift: Int def apply(i: Int): Array[AnyRef] def update(i: Int, obj: AnyRef): Self def +(node: Array[AnyRef]): Case def pop: (Case, Array[AnyRef]) } case object Zero extends Case { type Self = Nothing val shift = -1 def apply(i: Int) = throw new IndexOutOfBoundsException(i.toString) def update(i: Int, obj: AnyRef) = throw new IndexOutOfBoundsException(i.toString) def +(node: Array[AnyRef]) = One(node) def pop = throw new IndexOutOfBoundsException("Cannot pop an empty Vector") } case class One(trie: Array[AnyRef]) extends Case { type Self = One val shift = 0 def apply(i: Int) = trie def update(i: Int, obj: AnyRef) = { val trie2 = copy1(trie, new Array[AnyRef](trie.length)) trie2(i & 0x01f) = obj One(trie2) } def +(tail: Array[AnyRef]) = { val trie2 = new Array[Array[AnyRef]](2) trie2(0) = trie trie2(1) = tail Two(trie2) } def pop = (Zero, trie) } case class Two(trie: Array[Array[AnyRef]]) extends Case { type Self = Two val shift = 5 def apply(i: Int) = trie((i >>> 5) & 0x01f) def update(i: Int, obj: AnyRef) = { val trie2a = copy2(trie, new Array[Array[AnyRef]](trie.length)) val trie2b = { val target = trie2a((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2a((i >>> 5) & 0x01f) = trie2b trie2b(i & 0x01f) = obj Two(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.length >= 32) { val trie2 = new Array[Array[Array[AnyRef]]](2) trie2(0) = trie trie2(1) = new Array[Array[AnyRef]](1) trie2(1)(0) = tail Three(trie2) } else { val trie2 = copy2(trie, new Array[Array[AnyRef]](trie.length + 1)) trie2(trie.length) = tail Two(trie2) } } def pop = { if (trie.length == 2) { (One(trie(0)), trie.last) } else { val trie2 = copy2(trie, new Array[Array[AnyRef]](trie.length - 1)) (Two(trie2), trie.last) } } } case class Three(trie: Array[Array[Array[AnyRef]]]) extends Case { type Self = Three val shift = 10 def apply(i: Int) = { val a = trie((i >>> 10) & 0x01f) a((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) val trie2b = { val target = trie2a((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2a((i >>> 10) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2b((i >>> 5) & 0x01f) = trie2c trie2c(i & 0x01f) = obj Three(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[AnyRef]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0) = tail Four(trie2) } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length + 1)) trie2(trie.length) = new Array[Array[AnyRef]](1) trie2(trie.length)(0) = tail Three(trie2) } } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) trie2(trie2.length - 1) = copy2(trie2.last, new Array[Array[AnyRef]](trie2.last.length + 1)) trie2.last(trie.last.length) = tail Three(trie2) } } def pop = { if (trie.last.length == 1) { if (trie.length == 2) { (Two(trie(0)), trie.last.last) } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length - 1)) (Three(trie2), trie.last.last) } } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) trie2(trie2.length - 1) = copy2(trie2.last, new Array[Array[AnyRef]](trie2.last.length - 1)) (Three(trie2), trie.last.last) } } } case class Four(trie: Array[Array[Array[Array[AnyRef]]]]) extends Case { type Self = Four val shift = 15 def apply(i: Int) = { val a = trie((i >>> 15) & 0x01f) val b = a((i >>> 10) & 0x01f) b((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2a((i >>> 15) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2b((i >>> 10) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2c((i >>> 5) & 0x01f) = trie2d trie2d(i & 0x01f) = obj Four(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[Array[AnyRef]]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(1)(0) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0)(0) = tail Five(trie2) } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0) = tail Four(trie2) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length + 1)) trie2.last(trie.last.length) = new Array[Array[AnyRef]](1) trie2.last.last(0) = tail Four(trie2) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy2(trie2.last.last, new Array[Array[AnyRef]](trie2.last.last.length + 1)) trie2.last.last(trie.last.last.length) = tail Four(trie2) } } def pop = { if (trie.last.last.length == 1) { if (trie.last.length == 1) { if (trie.length == 2) { (Three(trie(0)), trie.last.last.last) } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length - 1)) (Four(trie2), trie.last.last.last) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length - 1)) (Four(trie2), trie.last.last.last) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy2(trie2.last.last, new Array[Array[AnyRef]](trie2.last.last.length - 1)) (Four(trie2), trie.last.last.last) } } } case class Five(trie: Array[Array[Array[Array[Array[AnyRef]]]]]) extends Case { type Self = Five val shift = 20 def apply(i: Int) = { val a = trie((i >>> 20) & 0x01f) val b = a((i >>> 15) & 0x01f) val c = b((i >>> 10) & 0x01f) c((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 20) & 0x01f) copy4(target, new Array[Array[Array[Array[AnyRef]]]](target.length)) } trie2a((i >>> 20) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2b((i >>> 15) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2c((i >>> 10) & 0x01f) = trie2d val trie2e = { val target = trie2d((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2d((i >>> 5) & 0x01f) = trie2e trie2e(i & 0x01f) = obj Five(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.last.length >= 32) { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[Array[Array[AnyRef]]]]](1) trie2(1)(0) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(1)(0)(0) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0)(0)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0)(0)(0) = tail Six(trie2) } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(trie.length)(0) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0)(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length + 1)) trie2.last(trie.last.length) = new Array[Array[Array[AnyRef]]](1) trie2.last.last(0) = new Array[Array[AnyRef]](1) trie2.last.last.last(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length + 1)) trie2.last.last(trie.last.last.length) = new Array[Array[AnyRef]](1) trie2.last.last.last(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length)) trie2.last.last(trie2.last.last.length - 1) = copy2(trie2.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.length + 1)) trie2.last.last.last(trie.last.last.last.length) = tail Five(trie2) } } def pop = { if (trie.last.last.last.length == 1) { if (trie.last.last.length == 1) { if (trie.last.length == 1) { if (trie.length == 2) { (Four(trie(0)), trie.last.last.last.last) } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length - 1)) trie2.last.last(trie2.last.last.length - 1) = copy2(trie2.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } } case class Six(trie: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) extends Case { type Self = Six val shift = 25 def apply(i: Int) = { val a = trie((i >>> 25) & 0x01f) val b = a((i >>> 20) & 0x01f) val c = b((i >>> 15) & 0x01f) val d = c((i >>> 10) & 0x01f) d((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 25) & 0x01f) copy5(target, new Array[Array[Array[Array[Array[AnyRef]]]]](target.length)) } trie2a((i >>> 25) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 20) & 0x01f) copy4(target, new Array[Array[Array[Array[AnyRef]]]](target.length)) } trie2b((i >>> 20) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2c((i >>> 15) & 0x01f) = trie2d val trie2e = { val target = trie2d((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2d((i >>> 10) & 0x01f) = trie2e val trie2f = { val target = trie2e((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2e((i >>> 5) & 0x01f) = trie2f trie2f(i & 0x01f) = obj Six(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.last.last.length >= 32) { if (trie.last.last.last.length >= 32) { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { throw new IndexOutOfBoundsException("Cannot grow vector beyond integer bounds") } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[Array[Array[AnyRef]]]]](1) trie2(trie.length)(0) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(trie.length)(0)(0) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0)(0)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0)(0)(0) = tail Six(trie2) } } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length + 1)) trie2.last(trie.last.length) = new Array[Array[Array[Array[AnyRef]]]](1) trie2.last.last(0) = new Array[Array[Array[AnyRef]]](1) trie2.last.last.last(0) = new Array[Array[AnyRef]](1) trie2.last.last.last.last(0) = tail Six(trie2) } } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length + 1)) trie2.last.last(trie.last.last.length) = new Array[Array[Array[AnyRef]]](1) trie2.last.last.last(0) = new Array[Array[AnyRef]](1) trie2.last.last.last.last(0) = tail Six(trie2) } } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length)) trie2.last.last(trie2.last.last.length - 1) = copy3(trie2.last.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.last.length + 1)) trie2.last.last.last(trie.last.last.last.length) = new Array[Array[AnyRef]](1) trie2.last.last.last.last(0) = tail Six(trie2) } } else { diff --git a/src/spec/scala/VectorSpecs.scala b/src/spec/scala/VectorSpecs.scala index 59d149e..d6d8132 100644 --- a/src/spec/scala/VectorSpecs.scala +++ b/src/spec/scala/VectorSpecs.scala @@ -1,387 +1,387 @@ import org.specs._ import org.scalacheck._ -import com.codecommit.collection.{EmptyVector, Vector} +import com.codecommit.collection.Vector object VectorSpecs extends Specification with ScalaCheck { import Prop._ val vector = Vector[Int]() implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = { Arbitrary(for { data <- Arbitrary.arbitrary[List[A]] } yield data.foldLeft(Vector[A]()) { _ + _ }) } "vector" should { "store a single element" in { val prop = forAll { (i: Int, e: Int) => i >= 0 ==> ((vector(0) = e)(0) == e) } prop must pass } "implement length" in { val prop = forAll { (list: List[Int]) => val vec = list.foldLeft(Vector[Int]()) { _ + _ } vec.length == list.length } prop must pass } "replace single element" in { val prop = forAll { (vec: Vector[Int], i: Int) => (!vec.isEmpty && i > Math.MIN_INT) ==> { val idx = Math.abs(i) % vec.length val newVector = (vec(idx) = "test")(idx) = "newTest" newVector(idx) == "newTest" } } prop must pass } "fail on apply out-of-bounds" in { val prop = forAll { (vec: Vector[Int], i: Int) => !((0 until vec.length) contains i) ==> { try { vec(i) false } catch { case _: IndexOutOfBoundsException => true } } } prop must pass } "fail on update out-of-bounds" in { val prop = forAll { (vec: Vector[Int], i: Int) => !((0 to vec.length) contains i) ==> { try { vec(i) = 42 false } catch { case _: IndexOutOfBoundsException => true } } } prop must pass } "pop elements" in { val prop = forAll { vec: Vector[Int] => vec.length > 0 ==> { val popped = vec.pop var back = popped.length == vec.length - 1 for (i <- 0 until popped.length) { back &&= popped(i) == vec(i) } back } } prop must pass(set(maxSize -> 3000, minTestsOk -> 1000)) } "fail on pop empty vector" in { val caughtExcept = try { - EmptyVector.pop + Vector.empty.pop false } catch { case _: IllegalStateException => true } caughtExcept mustEqual true } "store multiple elements in order" in { val prop = forAll { list: List[Int] => val newVector = list.foldLeft(vector) { _ + _ } val res = for (i <- 0 until list.length) yield newVector(i) == list(i) res forall { _ == true } } prop must pass } "store lots of elements" in { val LENGTH = 100000 val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ } vector.length mustEqual LENGTH for (i <- 0 until LENGTH) { vector(i) mustEqual i } } "maintain both old and new versions after conj" in { val prop = forAll { vec: Vector[Int] => val vec2 = vec + 42 for (i <- 0 until vec.length) { vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin") } vec2.last mustEqual 42 } prop must pass(set(maxSize -> 3000, minTestsOk -> 1000)) } "maintain both old and new versions after update" in { val prop = forAll { (vec: Vector[Int], i: Int) => (!vec.isEmpty && i > Math.MIN_INT) ==> { val idx = Math.abs(i) % vec.length val vec2 = vec(idx) = 42 for (i <- 0 until vec.length if i != idx) { vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin") } vec2(idx) mustEqual 42 } } prop must pass(set(maxSize -> 3000, minTestsOk -> 1000)) } "maintain both old and new versions after pop" in { val prop = forAll { vec: Vector[Int] => !vec.isEmpty ==> { val vec2 = vec.pop for (i <- 0 until vec.length - 1) { vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin") } vec2.length mustEqual vec.length - 1 } } prop must pass(set(maxSize -> 3000, minTestsOk -> 1000)) } "implement filter" in { val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) => val filtered = vec filter f var back = filtered forall f for (e <- vec) { if (f(e)) { back &&= filtered.contains(e) } } back } prop must pass } "implement foldLeft" in { val prop = forAll { list: List[Int] => val vec = list.foldLeft(Vector[Int]()) { _ + _ } vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ } } prop must pass } "implement forall" in { val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) => val bool = vec forall f var back = true for (e <- vec) { back &&= f(e) } (back && bool) || (!back && !bool) } prop must pass } "implement flatMap" in { val prop = forAll { (vec: Vector[Int], f: (Int)=>Vector[Int]) => val mapped = vec flatMap f var back = true var i = 0 var n = 0 while (i < vec.length) { val res = f(vec(i)) var inner = 0 while (inner < res.length) { back &&= mapped(n) == res(inner) inner += 1 n += 1 } i += 1 } back } prop must pass } "implement map" in { val prop = forAll { (vec: Vector[Int], f: (Int)=>Int) => val mapped = vec map f var back = vec.length == mapped.length for (i <- 0 until vec.length) { back &&= mapped(i) == f(vec(i)) } back } prop must pass } "implement reverse" in { val prop = forAll { v: Vector[Int] => val reversed = v.reverse var back = v.length == reversed.length for (i <- 0 until v.length) { back &&= reversed(i) == v(v.length - i - 1) } back } prop must pass } "append to reverse" in { val prop = forAll { (v: Vector[Int], n: Int) => val rev = v.reverse val add = rev + n var back = add.length == rev.length + 1 for (i <- 0 until rev.length) { back &&= add(i) == rev(i) } back && add(rev.length) == n } prop must pass } "map on reverse" in { val prop = forAll { (v: Vector[Int], f: (Int)=>Int) => val rev = v.reverse val mapped = rev map f var back = mapped.length == rev.length for (i <- 0 until rev.length) { back &&= mapped(i) == f(rev(i)) } back } prop must pass } "implement zip" in { val prop = forAll { (first: Vector[Int], second: Vector[Double]) => val zip = first zip second var back = zip.length == Math.min(first.length, second.length) for (i <- 0 until zip.length) { var (left, right) = zip(i) back &&= (left == first(i) && right == second(i)) } back } prop must pass } "implement zipWithIndex" in { val prop = forAll { vec: Vector[Int] => val zip = vec.zipWithIndex var back = zip.length == vec.length for (i <- 0 until zip.length) { val (elem, index) = zip(i) back &&= (index == i && elem == vec(i)) } back } prop must pass } "implement equals" in { { val prop = forAll { list: List[Int] => val vecA = list.foldLeft(Vector[Int]()) { _ + _ } val vecB = list.foldLeft(Vector[Int]()) { _ + _ } vecA == vecB } prop must pass } { val prop = forAll { (vecA: Vector[Int], vecB: Vector[Int]) => vecA.length != vecB.length ==> (vecA != vecB) } prop must pass } { val prop = forAll { (listA: List[Int], listB: List[Int]) => val vecA = listA.foldLeft(Vector[Int]()) { _ + _ } val vecB = listB.foldLeft(Vector[Int]()) { _ + _ } listA != listB ==> (vecA != vecB) } prop must pass } { val prop = forAll { (vec: Vector[Int], data: Int) => vec != data } prop must pass } } "implement hashCode" in { val prop = forAll { list: List[Int] => val vecA = list.foldLeft(Vector[Int]()) { _ + _ } val vecB = list.foldLeft(Vector[Int]()) { _ + _ } vecA.hashCode == vecB.hashCode } prop must pass } "implement extractor" in { val vec1 = Vector(1, 2, 3) vec1 must beLike { case Vector(a, b, c) => (a, b, c) == (1, 2, 3) } val vec2 = Vector("daniel", "chris", "joseph") vec2 must beLike { case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph") } } } }
djspiewak/scala-collections
3196af396d805c6585b81a93f6c91e481acd4acc
Removed obsolete VectorProjection class
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala index 2050efa..94c1d52 100644 --- a/src/main/scala/com/codecommit/collection/Vector.scala +++ b/src/main/scala/com/codecommit/collection/Vector.scala @@ -1,694 +1,677 @@ /** Copyright (c) 2007-2008, Rich Hickey All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Clojure nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package com.codecommit.collection import scala.collection.IndexedSeqLike import scala.collection.generic._ import scala.collection.immutable.IndexedSeq import scala.collection.mutable.Builder import VectorCases._ /** * A straight port of Clojure's <code>PersistentVector</code> class. * * @author Daniel Spiewak * @author Rich Hickey */ class Vector[+T] private (val length: Int, trie: Case, tail: Array[AnyRef]) extends IndexedSeq[T] with GenericTraversableTemplate[T, Vector] with IndexedSeqLike[T, Vector[T]] { outer => private val tailOff = length - tail.length override def companion = Vector /* * The design of this data structure inherantly requires heterogenous arrays. * It is *possible* to design around this, but the result is comparatively * quite inefficient. With respect to this fact, I have left the original * (somewhat dynamically-typed) implementation in place. */ private[collection] def this() = this(0, Zero, Vector.EmptyArray) def apply(i: Int): T = { if (i >= 0 && i < length) { if (i >= tailOff) { tail(i & 0x01f).asInstanceOf[T] } else { var arr = trie(i) arr(i & 0x01f).asInstanceOf[T] } } else throw new IndexOutOfBoundsException(i.toString) } def update[A >: T](i: Int, obj: A): Vector[A] = { if (i >= 0 && i < length) { if (i >= tailOff) { val newTail = new Array[AnyRef](tail.length) Array.copy(tail, 0, newTail, 0, tail.length) newTail(i & 0x01f) = obj.asInstanceOf[AnyRef] new Vector[A](length, trie, newTail) } else { new Vector[A](length, trie(i) = obj.asInstanceOf[AnyRef], tail) } } else if (i == length) { this + obj } else throw new IndexOutOfBoundsException(i.toString) } def +[A >: T](obj: A): Vector[A] = { if (tail.length < 32) { val tail2 = new Array[AnyRef](tail.length + 1) Array.copy(tail, 0, tail2, 0, tail.length) tail2(tail.length) = obj.asInstanceOf[AnyRef] new Vector[A](length + 1, trie, tail2) } else { new Vector[A](length + 1, trie + tail, Vector.array(obj.asInstanceOf[AnyRef])) } } /** * Removes the <i>tail</i> element of this vector. */ def pop: Vector[T] = { if (length == 0) { throw new IllegalStateException("Can't pop empty vector") } else if (length == 1) { EmptyVector } else if (tail.length > 1) { val tail2 = new Array[AnyRef](tail.length - 1) Array.copy(tail, 0, tail2, 0, tail2.length) new Vector[T](length - 1, trie, tail2) } else { val (trie2, tail2) = trie.pop new Vector[T](length - 1, trie2, tail2) } } } final class VectorBuilder[A] extends Builder[A, Vector[A]] { // TODO optimize private var tmp = Vector.empty[A] def +=(elem: A) = { tmp += elem this } def result = tmp def clear() { tmp = Vector.empty[A] } } object Vector extends SeqFactory[Vector] { @inline implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Vector[A]] = new GenericCanBuildFrom[A] { override def apply = newBuilder[A] } def newBuilder[A] = new VectorBuilder[A] private[collection] val EmptyArray = new Array[AnyRef](0) @inline override def empty[A]: Vector[A] = EmptyVector @inline private[collection] def array(elem: AnyRef) = { val back = new Array[AnyRef](1) back(0) = elem back } } object EmptyVector extends Vector[Nothing] -private[collection] abstract class VectorProjection[+T] extends Vector[T] { - override val length: Int - override def apply(i: Int): T - - override def +[A >: T](e: A) = innerCopy + e - - override def update[A >: T](i: Int, e: A) = { - if (i < 0) { - throw new IndexOutOfBoundsException(i.toString) - } else if (i > length) { - throw new IndexOutOfBoundsException(i.toString) - } else innerCopy(i) = e - } - - private lazy val innerCopy = foldLeft(EmptyVector:Vector[T]) { _ + _ } -} - private[collection] object VectorCases { @inline private[this] def copy1(array1: Array[AnyRef], array2: Array[AnyRef]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy2(array1: Array[Array[AnyRef]], array2: Array[Array[AnyRef]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy3(array1: Array[Array[Array[AnyRef]]], array2: Array[Array[Array[AnyRef]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy4(array1: Array[Array[Array[Array[AnyRef]]]], array2: Array[Array[Array[Array[AnyRef]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy5(array1: Array[Array[Array[Array[Array[AnyRef]]]]], array2: Array[Array[Array[Array[Array[AnyRef]]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } @inline private[this] def copy6(array1: Array[Array[Array[Array[Array[Array[AnyRef]]]]]], array2: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) = { Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length)) array2 } sealed trait Case { type Self <: Case val shift: Int def apply(i: Int): Array[AnyRef] def update(i: Int, obj: AnyRef): Self def +(node: Array[AnyRef]): Case def pop: (Case, Array[AnyRef]) } case object Zero extends Case { type Self = Nothing val shift = -1 def apply(i: Int) = throw new IndexOutOfBoundsException(i.toString) def update(i: Int, obj: AnyRef) = throw new IndexOutOfBoundsException(i.toString) def +(node: Array[AnyRef]) = One(node) def pop = throw new IndexOutOfBoundsException("Cannot pop an empty Vector") } case class One(trie: Array[AnyRef]) extends Case { type Self = One val shift = 0 def apply(i: Int) = trie def update(i: Int, obj: AnyRef) = { val trie2 = copy1(trie, new Array[AnyRef](trie.length)) trie2(i & 0x01f) = obj One(trie2) } def +(tail: Array[AnyRef]) = { val trie2 = new Array[Array[AnyRef]](2) trie2(0) = trie trie2(1) = tail Two(trie2) } def pop = (Zero, trie) } case class Two(trie: Array[Array[AnyRef]]) extends Case { type Self = Two val shift = 5 def apply(i: Int) = trie((i >>> 5) & 0x01f) def update(i: Int, obj: AnyRef) = { val trie2a = copy2(trie, new Array[Array[AnyRef]](trie.length)) val trie2b = { val target = trie2a((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2a((i >>> 5) & 0x01f) = trie2b trie2b(i & 0x01f) = obj Two(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.length >= 32) { val trie2 = new Array[Array[Array[AnyRef]]](2) trie2(0) = trie trie2(1) = new Array[Array[AnyRef]](1) trie2(1)(0) = tail Three(trie2) } else { val trie2 = copy2(trie, new Array[Array[AnyRef]](trie.length + 1)) trie2(trie.length) = tail Two(trie2) } } def pop = { if (trie.length == 2) { (One(trie(0)), trie.last) } else { val trie2 = copy2(trie, new Array[Array[AnyRef]](trie.length - 1)) (Two(trie2), trie.last) } } } case class Three(trie: Array[Array[Array[AnyRef]]]) extends Case { type Self = Three val shift = 10 def apply(i: Int) = { val a = trie((i >>> 10) & 0x01f) a((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) val trie2b = { val target = trie2a((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2a((i >>> 10) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2b((i >>> 5) & 0x01f) = trie2c trie2c(i & 0x01f) = obj Three(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[AnyRef]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0) = tail Four(trie2) } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length + 1)) trie2(trie.length) = new Array[Array[AnyRef]](1) trie2(trie.length)(0) = tail Three(trie2) } } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) trie2(trie2.length - 1) = copy2(trie2.last, new Array[Array[AnyRef]](trie2.last.length + 1)) trie2.last(trie.last.length) = tail Three(trie2) } } def pop = { if (trie.last.length == 1) { if (trie.length == 2) { (Two(trie(0)), trie.last.last) } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length - 1)) (Three(trie2), trie.last.last) } } else { val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length)) trie2(trie2.length - 1) = copy2(trie2.last, new Array[Array[AnyRef]](trie2.last.length - 1)) (Three(trie2), trie.last.last) } } } case class Four(trie: Array[Array[Array[Array[AnyRef]]]]) extends Case { type Self = Four val shift = 15 def apply(i: Int) = { val a = trie((i >>> 15) & 0x01f) val b = a((i >>> 10) & 0x01f) b((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2a((i >>> 15) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2b((i >>> 10) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2c((i >>> 5) & 0x01f) = trie2d trie2d(i & 0x01f) = obj Four(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[Array[AnyRef]]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(1)(0) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0)(0) = tail Five(trie2) } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0) = tail Four(trie2) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length + 1)) trie2.last(trie.last.length) = new Array[Array[AnyRef]](1) trie2.last.last(0) = tail Four(trie2) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy2(trie2.last.last, new Array[Array[AnyRef]](trie2.last.last.length + 1)) trie2.last.last(trie.last.last.length) = tail Four(trie2) } } def pop = { if (trie.last.last.length == 1) { if (trie.last.length == 1) { if (trie.length == 2) { (Three(trie(0)), trie.last.last.last) } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length - 1)) (Four(trie2), trie.last.last.last) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length - 1)) (Four(trie2), trie.last.last.last) } } else { val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length)) trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy2(trie2.last.last, new Array[Array[AnyRef]](trie2.last.last.length - 1)) (Four(trie2), trie.last.last.last) } } } case class Five(trie: Array[Array[Array[Array[Array[AnyRef]]]]]) extends Case { type Self = Five val shift = 20 def apply(i: Int) = { val a = trie((i >>> 20) & 0x01f) val b = a((i >>> 15) & 0x01f) val c = b((i >>> 10) & 0x01f) c((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 20) & 0x01f) copy4(target, new Array[Array[Array[Array[AnyRef]]]](target.length)) } trie2a((i >>> 20) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2b((i >>> 15) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2c((i >>> 10) & 0x01f) = trie2d val trie2e = { val target = trie2d((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2d((i >>> 5) & 0x01f) = trie2e trie2e(i & 0x01f) = obj Five(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.last.length >= 32) { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { val trie2 = new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](2) trie2(0) = trie trie2(1) = new Array[Array[Array[Array[Array[AnyRef]]]]](1) trie2(1)(0) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(1)(0)(0) = new Array[Array[Array[AnyRef]]](1) trie2(1)(0)(0)(0) = new Array[Array[AnyRef]](1) trie2(1)(0)(0)(0)(0) = tail Six(trie2) } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(trie.length)(0) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0)(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length + 1)) trie2.last(trie.last.length) = new Array[Array[Array[AnyRef]]](1) trie2.last.last(0) = new Array[Array[AnyRef]](1) trie2.last.last.last(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length + 1)) trie2.last.last(trie.last.last.length) = new Array[Array[AnyRef]](1) trie2.last.last.last(0) = tail Five(trie2) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length)) trie2.last.last(trie2.last.last.length - 1) = copy2(trie2.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.length + 1)) trie2.last.last.last(trie.last.last.last.length) = tail Five(trie2) } } def pop = { if (trie.last.last.last.length == 1) { if (trie.last.last.length == 1) { if (trie.last.length == 1) { if (trie.length == 2) { (Four(trie(0)), trie.last.last.last.last) } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } else { val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length)) trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1)) trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length - 1)) trie2.last.last(trie2.last.last.length - 1) = copy2(trie2.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.length - 1)) (Five(trie2), trie.last.last.last.last) } } } case class Six(trie: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) extends Case { type Self = Six val shift = 25 def apply(i: Int) = { val a = trie((i >>> 25) & 0x01f) val b = a((i >>> 20) & 0x01f) val c = b((i >>> 15) & 0x01f) val d = c((i >>> 10) & 0x01f) d((i >>> 5) & 0x01f) } def update(i: Int, obj: AnyRef) = { val trie2a = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) val trie2b = { val target = trie2a((i >>> 25) & 0x01f) copy5(target, new Array[Array[Array[Array[Array[AnyRef]]]]](target.length)) } trie2a((i >>> 25) & 0x01f) = trie2b val trie2c = { val target = trie2b((i >>> 20) & 0x01f) copy4(target, new Array[Array[Array[Array[AnyRef]]]](target.length)) } trie2b((i >>> 20) & 0x01f) = trie2c val trie2d = { val target = trie2c((i >>> 15) & 0x01f) copy3(target, new Array[Array[Array[AnyRef]]](target.length)) } trie2c((i >>> 15) & 0x01f) = trie2d val trie2e = { val target = trie2d((i >>> 10) & 0x01f) copy2(target, new Array[Array[AnyRef]](target.length)) } trie2d((i >>> 10) & 0x01f) = trie2e val trie2f = { val target = trie2e((i >>> 5) & 0x01f) copy1(target, new Array[AnyRef](target.length)) } trie2e((i >>> 5) & 0x01f) = trie2f trie2f(i & 0x01f) = obj Six(trie2a) } def +(tail: Array[AnyRef]) = { if (trie.last.last.last.last.length >= 32) { if (trie.last.last.last.length >= 32) { if (trie.last.last.length >= 32) { if (trie.last.length >= 32) { if (trie.length >= 32) { throw new IndexOutOfBoundsException("Cannot grow vector beyond integer bounds") } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length + 1)) trie2(trie.length) = new Array[Array[Array[Array[Array[AnyRef]]]]](1) trie2(trie.length)(0) = new Array[Array[Array[Array[AnyRef]]]](1) trie2(trie.length)(0)(0) = new Array[Array[Array[AnyRef]]](1) trie2(trie.length)(0)(0)(0) = new Array[Array[AnyRef]](1) trie2(trie.length)(0)(0)(0)(0) = tail Six(trie2) } } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length + 1)) trie2.last(trie.last.length) = new Array[Array[Array[Array[AnyRef]]]](1) trie2.last.last(0) = new Array[Array[Array[AnyRef]]](1) trie2.last.last.last(0) = new Array[Array[AnyRef]](1) trie2.last.last.last.last(0) = tail Six(trie2) } } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length + 1)) trie2.last.last(trie.last.last.length) = new Array[Array[Array[AnyRef]]](1) trie2.last.last.last(0) = new Array[Array[AnyRef]](1) trie2.last.last.last.last(0) = tail Six(trie2) } } else { val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length)) trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length)) trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length)) trie2.last.last(trie2.last.last.length - 1) = copy3(trie2.last.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.last.length + 1)) trie2.last.last.last(trie.last.last.last.length) = new Array[Array[AnyRef]](1) trie2.last.last.last.last(0) = tail Six(trie2) } } else {
djspiewak/scala-collections
ed9fb82e7cd2da2ddb914b145b762150042c2379
Added Scala's immutable.Vector to perf test
diff --git a/src/test/scala/VectorPerf.scala b/src/test/scala/VectorPerf.scala index 8bc5303..f5546ca 100644 --- a/src/test/scala/VectorPerf.scala +++ b/src/test/scala/VectorPerf.scala @@ -1,297 +1,366 @@ import com.codecommit.collection.Vector +import scala.collection.immutable.{Vector => DefVector} import scala.collection.mutable.ArrayBuffer import scala.collection.immutable.IntMap object VectorPerf { import PerfLib._ def main(args: Array[String]) { println() //========================================================================== { title("Fill 100000 Sequential Indexes") val vectorOp = "Vector" -> time { var vec = Vector[Int]() var i = 0 while (i < 100000) { vec += i i += 1 } } val arrayOp = "ArrayBuffer" -> time { var arr = new ArrayBuffer[Int] var i = 0 while (i < 100000) { arr += i i += 1 } } vectorOp compare arrayOp + val defVectorOp = "DefVector" -> time { + var vec = DefVector[Int]() + var i = 0 + + while (i < 100000) { + vec :+= i + i += 1 + } + } + + vectorOp compare defVectorOp + val intMapOp = "IntMap" -> time { var map = IntMap[Int]() var i = 0 while (i < 100000) { map = map(i) = i i += 1 } } vectorOp compare intMapOp val oldIntMapOp = "Map[Int, _]" -> time { var map = Map[Int, Int]() var i = 0 while (i < 100000) { map = map(i) = i i += 1 } } vectorOp compare oldIntMapOp div('=') println() } //========================================================================== { title("Read 100000 Sequential Indexes") var vec = Vector[Int]() for (i <- 0 until 100000) { vec += i } var arr = new ArrayBuffer[Int] for (i <- 0 until 100000) { arr += i } + var defVec = DefVector[Int]() + for (i <- 0 until 100000) { + defVec :+= i + } + var map = IntMap[Int]() for (i <- 0 until 100000) { map = map(i) = i } var oldMap = Map[Int, Int]() for (i <- 0 until 100000) { oldMap = oldMap(i) = i } val vectorOp = "Vector" -> time { var i = 0 while (i < vec.length) { vec(i) i += 1 } } val arrayOp = "ArrayBuffer" -> time { var i = 0 while (i < arr.size) { arr(i) i += 1 } } vectorOp compare arrayOp + val defVectorOp = "DefVector" -> time { + var i = 0 + while (i < defVec.length) { + defVec(i) + i += 1 + } + } + + vectorOp compare defVectorOp + val intMapOp = "IntMap" -> time { var i = 0 while (i < vec.length) { // map.size is unsuitable map(i) i += 1 } } vectorOp compare intMapOp val oldIntMapOp = "Map[Int, _]" -> time { var i = 0 while (i < vec.length) { // map.size is unsuitable oldMap(i) i += 1 } } vectorOp compare oldIntMapOp div('=') println() } //========================================================================== { title("Read 100000 Random Indexes") val indexes = new Array[Int](100000) var max = -1 for (i <- 0 until indexes.length) { indexes(i) = Math.round(Math.random * 40000000).toInt max = Math.max(max, indexes(i)) } var vec = Vector[Int]() for (i <- 0 to max) { // unplesant hack vec += 0 } for (i <- 0 until indexes.length) { vec = vec(indexes(i)) = i } val arr = new ArrayBuffer[Int] for (i <- 0 to max) { // unplesant hack arr += 0 } for (i <- 0 until indexes.length) { arr(indexes(i)) = i } + var defVec = DefVector[Int]() + for (i <- 0 to max) { // unplesant hack + defVec :+= 0 + } + + for (i <- 0 until indexes.length) { + defVec = defVec.updated(indexes(i), i) + } + var map = IntMap[Int]() for (i <- 0 until indexes.length) { map = map(indexes(i)) = i } var oldMap = Map[Int, Int]() for (i <- 0 until indexes.length) { oldMap = map(indexes(i)) = i } val vectorOp = "Vector" -> time { var i = 0 while (i < indexes.length) { vec(indexes(i)) i += 1 } } val arrayOp = "ArrayBuffer" -> time { var i = 0 while (i < indexes.length) { arr(indexes(i)) i += 1 } } vectorOp compare arrayOp + val defVectorOp = "DefVector" -> time { + var i = 0 + while (i < indexes.length) { + defVec(indexes(i)) + i += 1 + } + } + + vectorOp compare defVectorOp + val intMapOp = "IntMap" -> time { var i = 0 while (i < indexes.length) { map(indexes(i)) i += 1 } } vectorOp compare intMapOp val oldIntMapOp = "Map[Int, _]" -> time { var i = 0 while (i < indexes.length) { oldMap(indexes(i)) i += 1 } } vectorOp compare oldIntMapOp div('=') println() } //========================================================================== { title("Reverse of Length 100000") var vec = Vector[Int]() for (i <- 0 until 100000) { vec += i } var arr = new ArrayBuffer[Int] for (i <- 0 until 100000) { arr += i } + var defVec = DefVector[Int]() + for (i <- 0 until 100000) { + defVec :+= i + } + var map = IntMap[Int]() for (i <- 0 until 100000) { map = map(i) = i } val vectorOp = "Vector" -> time { vec.reverse } val arrayOp = "ArrayBuffer" -> time { arr.reverse } vectorOp compare arrayOp + val defVectorOp = "DefVector" -> time { + defVec.reverse + } + + vectorOp compare defVectorOp + div('=') println() } //========================================================================== { title("Compute Length (100000)") var vec = Vector[Int]() for (i <- 0 until 100000) { vec += i } var arr = new ArrayBuffer[Int] for (i <- 0 until 100000) { arr += i } + var defVec = DefVector[Int]() + for (i <- 0 until 100000) { + defVec :+= i + } + var map = IntMap[Int]() for (i <- 0 until 100000) { map = map(i) = i } var oldMap = Map[Int, Int]() for (i <- 0 until 100000) { oldMap = oldMap(i) = i } val vectorOp = "Vector" -> time { vec.length } val arrayOp = "ArrayBuffer" -> time { arr.length } vectorOp compare arrayOp + val defVectorOp = "DefVector" -> time { + defVec.length + } + + vectorOp compare defVectorOp + val intMapOp = "IntMap" -> time { map.size } vectorOp compare intMapOp val oldIntMapOp = "Map[Int, _]" -> time { oldMap.size } vectorOp compare oldIntMapOp div('=') println() } } }
djspiewak/scala-collections
99adcedd7c6ffde0fe42436e8944a5f85d849a8b
Ported forward Vector perf test
diff --git a/do_perf b/do_perf index 60473d8..baaa62c 100755 --- a/do_perf +++ b/do_perf @@ -1,8 +1,8 @@ #!/bin/sh buildr test:compile if [ "$?" ]; then echo =============================================================================== - exec java -Xmx2048m -Xms512m -server -cp "${SCALA28_HOME}/lib/scala-library.jar:target/classes:target/test/classes" QueuePerf + exec java -Xmx2048m -Xms512m -server -cp "${SCALA28_HOME}/lib/scala-library.jar:target/classes:target/test/classes" VectorPerf fi diff --git a/src/test/scala/VectorPerf.scala b/src/test/scala/VectorPerf.scala new file mode 100644 index 0000000..8bc5303 --- /dev/null +++ b/src/test/scala/VectorPerf.scala @@ -0,0 +1,297 @@ +import com.codecommit.collection.Vector + +import scala.collection.mutable.ArrayBuffer +import scala.collection.immutable.IntMap + +object VectorPerf { + import PerfLib._ + + def main(args: Array[String]) { + println() + + //========================================================================== + { + title("Fill 100000 Sequential Indexes") + + val vectorOp = "Vector" -> time { + var vec = Vector[Int]() + var i = 0 + + while (i < 100000) { + vec += i + i += 1 + } + } + + val arrayOp = "ArrayBuffer" -> time { + var arr = new ArrayBuffer[Int] + var i = 0 + + while (i < 100000) { + arr += i + i += 1 + } + } + + vectorOp compare arrayOp + + val intMapOp = "IntMap" -> time { + var map = IntMap[Int]() + var i = 0 + + while (i < 100000) { + map = map(i) = i + i += 1 + } + } + + vectorOp compare intMapOp + + val oldIntMapOp = "Map[Int, _]" -> time { + var map = Map[Int, Int]() + var i = 0 + + while (i < 100000) { + map = map(i) = i + i += 1 + } + } + + vectorOp compare oldIntMapOp + + div('=') + println() + } + + //========================================================================== + { + title("Read 100000 Sequential Indexes") + + var vec = Vector[Int]() + for (i <- 0 until 100000) { + vec += i + } + + var arr = new ArrayBuffer[Int] + for (i <- 0 until 100000) { + arr += i + } + + var map = IntMap[Int]() + for (i <- 0 until 100000) { + map = map(i) = i + } + + var oldMap = Map[Int, Int]() + for (i <- 0 until 100000) { + oldMap = oldMap(i) = i + } + + val vectorOp = "Vector" -> time { + var i = 0 + while (i < vec.length) { + vec(i) + i += 1 + } + } + + val arrayOp = "ArrayBuffer" -> time { + var i = 0 + while (i < arr.size) { + arr(i) + i += 1 + } + } + + vectorOp compare arrayOp + + val intMapOp = "IntMap" -> time { + var i = 0 + while (i < vec.length) { // map.size is unsuitable + map(i) + i += 1 + } + } + + vectorOp compare intMapOp + + val oldIntMapOp = "Map[Int, _]" -> time { + var i = 0 + while (i < vec.length) { // map.size is unsuitable + oldMap(i) + i += 1 + } + } + + vectorOp compare oldIntMapOp + + div('=') + println() + } + + //========================================================================== + { + title("Read 100000 Random Indexes") + + val indexes = new Array[Int](100000) + var max = -1 + for (i <- 0 until indexes.length) { + indexes(i) = Math.round(Math.random * 40000000).toInt + max = Math.max(max, indexes(i)) + } + + var vec = Vector[Int]() + for (i <- 0 to max) { // unplesant hack + vec += 0 + } + + for (i <- 0 until indexes.length) { + vec = vec(indexes(i)) = i + } + + val arr = new ArrayBuffer[Int] + for (i <- 0 to max) { // unplesant hack + arr += 0 + } + + for (i <- 0 until indexes.length) { + arr(indexes(i)) = i + } + + var map = IntMap[Int]() + for (i <- 0 until indexes.length) { + map = map(indexes(i)) = i + } + + var oldMap = Map[Int, Int]() + for (i <- 0 until indexes.length) { + oldMap = map(indexes(i)) = i + } + + val vectorOp = "Vector" -> time { + var i = 0 + while (i < indexes.length) { + vec(indexes(i)) + i += 1 + } + } + + val arrayOp = "ArrayBuffer" -> time { + var i = 0 + while (i < indexes.length) { + arr(indexes(i)) + i += 1 + } + } + + vectorOp compare arrayOp + + val intMapOp = "IntMap" -> time { + var i = 0 + while (i < indexes.length) { + map(indexes(i)) + i += 1 + } + } + + vectorOp compare intMapOp + + val oldIntMapOp = "Map[Int, _]" -> time { + var i = 0 + while (i < indexes.length) { + oldMap(indexes(i)) + i += 1 + } + } + + vectorOp compare oldIntMapOp + + div('=') + println() + } + + //========================================================================== + { + title("Reverse of Length 100000") + + var vec = Vector[Int]() + for (i <- 0 until 100000) { + vec += i + } + + var arr = new ArrayBuffer[Int] + for (i <- 0 until 100000) { + arr += i + } + + var map = IntMap[Int]() + for (i <- 0 until 100000) { + map = map(i) = i + } + + val vectorOp = "Vector" -> time { + vec.reverse + } + + val arrayOp = "ArrayBuffer" -> time { + arr.reverse + } + + vectorOp compare arrayOp + + div('=') + println() + } + + //========================================================================== + { + title("Compute Length (100000)") + + var vec = Vector[Int]() + for (i <- 0 until 100000) { + vec += i + } + + var arr = new ArrayBuffer[Int] + for (i <- 0 until 100000) { + arr += i + } + + var map = IntMap[Int]() + for (i <- 0 until 100000) { + map = map(i) = i + } + + var oldMap = Map[Int, Int]() + for (i <- 0 until 100000) { + oldMap = oldMap(i) = i + } + + val vectorOp = "Vector" -> time { + vec.length + } + + val arrayOp = "ArrayBuffer" -> time { + arr.length + } + + vectorOp compare arrayOp + + val intMapOp = "IntMap" -> time { + map.size + } + + vectorOp compare intMapOp + + val oldIntMapOp = "Map[Int, _]" -> time { + oldMap.size + } + + vectorOp compare oldIntMapOp + + div('=') + println() + } + } +} +