2
0
mirror of https://gitlab.com/apparmor/apparmor synced 2025-08-31 22:35:35 +00:00

Compare commits

..

34 Commits

Author SHA1 Message Date
John Johansen
022a988e4e 2.7.1 Release 2012-01-30 07:30:25 -08:00
Christian Boltz
95f9b1d07c Update abstractios for KDE4
(At least) openSUSE uses ~/.kde4 to store KDE4 settings.
This patch changes ~/.kde/ to ~/.kde{,4} in all abstractions.

The patch is mostly from Velery Valery, I only fixed a merge conflict 
and added the kmail{,2} part in private-files-strict.

References: https://bugzilla.novell.com/show_bug.cgi?id=741592

Acked-By: Steve Beattie <sbeattie@ubuntu.com> for both trunk and 2.7.
2012-01-19 15:21:56 +01:00
Jamie Strandboge
4258749515 update p11-kit to allow mmap of libraries in pkcs directories
Acked-by: Jamie Strandboge <jamie@canonical.com>
Acked-By: Steve Beattie <sbeattie@ubuntu.com>
2012-01-18 16:23:12 -06:00
Steve Beattie
62b2a00331 Merge from trunk rev 1930: A bug in Ubuntu reported that the aspell
abstraction does not allow write access to the user customizable
dictionaries, the personal dictionary (~/.aspell.$LANG.pws) and the
personal replacement dictionary (~/.aspell.$LANG.prepl). It also
adjusts the abstraction to add the owner modifier to the personal
dictionaries.

Bug: https://bugs.launchpad.net/bugs/917859

Signed-off-by: Steve Beattie <sbeattie@ubuntu.com>
Acked-by: John Johansen <john.johansen@canonical.com>
2012-01-18 11:06:21 -08:00
Steve Beattie
463415347d Merge from trunk rev 1908: utils/Immunix/AppArmor.pm: fixes the profile
autogeneration code to include read access to the script itself for
interpreted scripts.

Nominated-By: Steve Beattie <sbeattie@ubuntu.com>
Acked-by: Christian Boltz <apparmor@cboltz.de> for the 2.7 branch
2012-01-12 10:39:48 +01:00
Steve Beattie
a52313485f Merge from trunk rev 1907: utils/Immunix/AppArmor.pm: update the
initial profile generation for python and ruby scripts to include
the respective abstractions.

Nominated-By: Steve Beattie <sbeattie@ubuntu.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2012-01-12 10:38:41 +01:00
Christian Boltz
67b440a019 when using smbldap-useradd using this smb.conf entry
add machine script = /usr/sbin/smbldap-useradd -t 5 -w "%u"
smbd obviously needs x permissions for smbldap-useradd.

The commit also adds a new profile for usr.sbin.smbldap-useradd (based on 
the audit.log from Alexis Pellicier).

Additionally, I moved the "/etc/samba/* rwk" rule next to the other 
/etc-related rules in the smbd profile.

References: https://bugzilla.novell.com/show_bug.cgi?id=738041

Acked-By: Steve Beattie <sbeattie@ubuntu.com>
2012-01-10 19:08:48 +01:00
Steve Beattie
da1bb2f219 Trunk revision 1910: Fix from Felix Geyer: block write access to
~/.kde/env because KDE automatically sources scripts in that folder
on startup.

Bug: https://bugs.launchpad.net/bugs/914190

Nominated-By: Steve Beattie <sbeattie@ubuntu.com>
Acked-by: John Johansen <john.johansen@canonical.com>
2012-01-10 12:59:54 +01:00
Steve Beattie
0badfb7816 Trunk revision 1909: Fix from Felix Geyer: in the enchant abstraction,
allow the creation of enchant .config directory.

Bug: https://bugs.launchpad.net/bugs/914184

Nominated-By: Steve Beattie <sbeattie@ubuntu.com>
Acked-By: John Johansen <john.johansen@canonical.com>
2012-01-10 12:58:33 +01:00
Christian Boltz
87bf30b6d0 read-only TFTP access for dnsmasq
This is a backport of r1870 to the 2.7 branch.

Acked-By: Steve Beattie <sbeattie@ubuntu.com> for 2.7


Original commit message for trunk r1870:
  Merge from Simon Deziel for TFTP read-only access for dnsmasq. Fixes
  LP: #905412

  Acked-by: Jamie Strandboge <jamie@canonical.com>
2012-01-09 21:08:19 +01:00
Christian Boltz
51369a0c3e according to Peter Czanik, the openSUSE syslog-ng maintainer, syslog-ng
needs capability dac_read_search.

References: https://bugzilla.novell.com/show_bug.cgi?id=731876

ACKed-by: Steve Beattie <steve@nxnw.org>
2012-01-09 13:29:43 +01:00
Jamie Strandboge
6ae5a71ea2 merge from trunk:
add p11-kit abstraction (LP: #912754, LP: #912752)
  
  From the README in the toplevel source:
  "[P11-KIT] Provides a way to load and enumerate PKCS#11 modules. Provides a
  standard configuration setup for installing PKCS#11 modules in such a way that
  they're discoverable."
  
  File locatations are described in [1]. There is a global configuration file in
  /etc/pkcs11/pkcs11.conf. Per module configuration happens in
  /etc/pkcs11/<module name>. There is also user configuration in ~/.pkcs11, but
  IMO this should not be allowed in the abstraction. Example configuration can b
e
  seen in the upstream documentation[2].
  
  This will likely need to be refined as more applications use p11-kit.
  
  [1]http://p11-glue.freedesktop.org/doc/p11-kit/config-locations.html
  [2]http://p11-glue.freedesktop.org/doc/p11-kit/config-example.html
  
  Acked-by: Jamie Strandboge <jamie@canonical.com>
  Acked-By: Steve Beattie <sbeattie@ubuntu.com>
  
  
  Also add p11-kit to authentication abstraction
  
  Acked-by: Jamie Strandboge <jamie@canonical.com>
  Acked-By: Steve Beattie <sbeattie@ubuntu.com>
2012-01-09 10:51:06 +01:00
Jamie Strandboge
850a565dce merge from trunk:
add audacity to the ubuntu-media-players abstraction (LP: #899963)
2012-01-09 10:49:07 +01:00
Jamie Strandboge
a0cf904972 merge from trunk:
allow software-center in the ubuntu-integration abstraction for
  apt: URLs (LP: #662906)
2012-01-09 10:48:36 +01:00
Jamie Strandboge
8760451216 merge from trunk:
allow fireclam plugin to work in Ubuntu multimedia abstraction
  (LP: #562831)
2012-01-09 10:48:11 +01:00
Jamie Strandboge
d096f8f7a5 merge trunk:
Author: James Troup
  Description: fix typo when adding multiarch lines for gconv
  Bug-Ubuntu: https://launchpad.net/bugs/904548
  
  Acked-by: Jamie Strandboge <jamie@canonical.com>
2012-01-09 10:47:42 +01:00
Jamie Strandboge
beb695f7b0 merge from trunk:
Author: Felix Geyer
  Description: allow avahi to do dbus introspection
  Bug-Ubuntu: https://launchpad.net/bugs/769148
  
  Acked-by: Jamie Strandboge <jamie@canonical.com>
2012-01-09 10:47:12 +01:00
Jamie Strandboge
ac80b7ca03 merge from trunk:
Author: Felix Geyer
  Description: abstractions/fonts should allow access to ~/.fonts.conf.d
  Bug-Ubuntu: https://launchpad.net/bugs/870992
  
  Acked-by: Jamie Strandboge <jamie@canonical.com>
2012-01-09 10:46:27 +01:00
Jamie Strandboge
a729e8fd75 merge from trunk:
Nvidia users need access to /dev/nvidia* files for various plugins
  to work right. Since these are all focused around multimedia, add the
  accesses to ubuntu-browsers.d/multimedia
2012-01-09 10:45:40 +01:00
Jamie Strandboge
f4c661e070 merge from trunk:
allow access to Thunar as well as thunar in ubuntu-integration abstraction
  (LP: #890894)
2012-01-09 10:44:45 +01:00
Jamie Strandboge
15e636a329 merge from trunk:
allow ixr access to exo-open in Ubuntu integration abstraction
  (LP: #890894)
2012-01-09 10:44:11 +01:00
Jamie Strandboge
49b9a83d9e Merge from trunk:
update binaries for for transmission in ubuntu-bittorrent-clients
  (LP: #852062)
2012-01-09 10:43:34 +01:00
Jamie Strandboge
069d98d007 merge from trunk:
add kate to Ubuntu text editors browser abstraction
  fix for LP: #884748
2012-01-09 10:42:54 +01:00
Jamie Strandboge
8c82eec301 Cherrypick from trunk:
Description: allow read of @{HOME}/.cups/client.conf and
   @{HOME}/.cups/lpoptions
  Bug-Ubuntu: https://launchpad.net/bugs/887992

  Added owner match per Steve Beattie and lpoptions per Steve and Christian Bolt
z
2012-01-06 10:53:14 -06:00
Jamie Strandboge
455d8a5140 Cherrypick from trunk:
Description: allow read access of /etc/python{2,3}.[0-7]*/sitecustomize.py
   in python abstraction. This script is used by apport aware python application
s
  Bug-Ubuntu: https://launchpad.net/bugs/860856

  Acked-by: Jamie Strandboge <jamie@canonical.com>
  Acked-by: Kees Cook <kees@ubuntu.com>
2012-01-06 10:52:34 -06:00
Jamie Strandboge
efd20f879c Cherrypick from trunk:
Description: update dovecot deliver profile to access various .conf files for
   dovecot
  Bug-Ubuntu: https://launchpad.net/bugs/458922

  Acked-by: Jamie Strandboge <jamie@canonical.com>
  Acked-by: Kees Cook <kees@ubuntu.com>
2012-01-06 10:51:58 -06:00
Jamie Strandboge
977929f558 Cherrypick from trunk:
Description: updates for usr.bin.sshd example profile to work with zsh4, dash
   and systems where /var/run moved to /run. Also allows read of
   /etc/default/locale.
  Bug-Ubuntu: https://launchpad.net/bugs/817956

  Acked-by: Jamie Strandboge <jamie@canonical.com>
  Acked-by: Kees Cook <kees@ubuntu.com>
2012-01-06 10:51:09 -06:00
Jamie Strandboge
cb60e9b3df Cherrypick from upstream:
Description: Disallow writing and linking to @{HOME}/.pki/nssdb/ .so files
  Bug-Ubuntu: https://launchpad.net/bugs/911847

  Acked-by: Jamie Strandboge <jamie@canonical.com>
  Acked-By: Steve Beattie <sbeattie@ubuntu.com>
2012-01-06 10:50:19 -06:00
Christian Boltz
f57d90d935 lesson of the day: it's not a good idea to edit a file while the
"bzr commit" editor is open because bzr caches the modified file 
and doesn't include last-minute changes in the commit :-/

In other words: the rule for /.htaccess didn't contain the audit
keyword in my last commit.
2012-01-05 23:53:51 +01:00
Christian Boltz
f66a2e2e66 according to Lars Müller (a samba developer) smbd needs access to some
more files in /usr/lib*/samba/ in some cases.

References: https://bugzilla.novell.com/show_bug.cgi?id=725967#c5


Acked-By: Steve Beattie <sbeattie@ubuntu.com>
2012-01-05 23:50:13 +01:00
Christian Boltz
d1281c4988 Split off various permissions from the httpd2-prefork profile to
abstractions/apache2-common. Additionally, add read permissions
for /**/.htaccess and /dev/urandom to apache2-common.

The patch is based on a profile abstraction from darix. I made some 
things more strict (compared to darix' profile), and OTOH added some 
things that are needed on my servers.

*** BACKWARDS-INCOMPATIBLE CHANGES ***

^HANDLING_UNTRUSTED_INPUT
- don't allow *.htaccess files (the old /**.htaccess rule was too generous)


Note: this is slightly different to trunk r1895 regarding /.htaccess:
/.htaccess is still allowed in the 2.7 branch, but logged ("audit") and 
has a comment saying that it will be disallowed in future versions.
2012-01-05 23:38:48 +01:00
Christian Boltz
c93fc7c758 Create /etc/apparmor.d/tunables/multiarch.d directory in profiles/Makefile
(otherwise it's created as a file, which is wrong)

Acked-by: John Johansen <john.johansen@canonical.com>
2012-01-03 23:45:00 +01:00
Christian Boltz
e2c5ecafce Fix a syntax error in abstractions/python introduced in r1854.
According to https://launchpad.net/bugs/840734 pyconfig.h should have r 
permissions.

Acked-by: John Johansen <john.johansen@canonical.com>
2012-01-03 21:23:30 +01:00
Christian Boltz
888ef7b0e2 smbd needs read access to /etc/netgroup.
References: https://bugzilla.novell.com/show_bug.cgi?id=738041

Acked-by: John Johansen <john.johansen@canonical.com>
2011-12-30 21:55:58 +01:00
1293 changed files with 103510 additions and 108025 deletions

View File

@@ -165,4 +165,3 @@ tests/regression/apparmor/unix_fd_server
tests/regression/apparmor/unlink
tests/regression/apparmor/xattrs
tests/regression/apparmor/coredump
./utils/apparmor/__pycache__

View File

@@ -7,14 +7,12 @@ include common/Make.rules
DIRS=parser \
profiles \
utils \
libraries/libapparmor \
changehat/libapparmor \
changehat/mod_apparmor \
changehat/pam_apparmor \
tests
#REPO_URL?=lp:apparmor
# --per-file-timestamps is failing over SSH, https://bugs.launchpad.net/bzr/+bug/1257078
REPO_URL?=https://code.launchpad.net/~apparmor-dev/apparmor/master
REPO_URL?=lp:apparmor
# alternate possibilities to export from
#REPO_URL=.
#REPO_URL="bzr+ssh://bazaar.launchpad.net/~sbeattie/+junk/apparmor-dev/"
@@ -27,16 +25,12 @@ __SETUP_DIR?=.
# embedded in ${VERSION}
TAG_VERSION=$(subst ~,-,${VERSION})
# Add exclusion entries arguments for tar here, of the form:
# --exclude dir_to_exclude --exclude other_dir
TAR_EXCLUSIONS=
.PHONY: tarball
tarball: clean
REPO_VERSION=`$(value REPO_VERSION_CMD)` ; \
make export_dir __EXPORT_DIR=${RELEASE_DIR} __REPO_VERSION=$${REPO_VERSION} ; \
make setup __SETUP_DIR=${RELEASE_DIR} ; \
tar ${TAR_EXCLUSIONS} -cvzf ${RELEASE_DIR}.tar.gz ${RELEASE_DIR}
tar --exclude deprecated -cvzf ${RELEASE_DIR}.tar.gz ${RELEASE_DIR}
.PHONY: snapshot
snapshot: clean
@@ -44,7 +38,7 @@ snapshot: clean
SNAPSHOT_DIR=apparmor-${VERSION}~$${REPO_VERSION} ;\
make export_dir __EXPORT_DIR=$${SNAPSHOT_DIR} __REPO_VERSION=$${REPO_VERSION} ; \
make setup __SETUP_DIR=$${SNAPSHOT_DIR} ; \
tar ${TAR_EXCLUSIONS} -cvzf $${SNAPSHOT_DIR}.tar.gz $${SNAPSHOT_DIR} ;
tar --exclude deprecated -cvzf $${SNAPSHOT_DIR}.tar.gz $${SNAPSHOT_DIR} ;
.PHONY: export_dir

35
README
View File

@@ -81,7 +81,7 @@ $ make install
parser:
$ cd parser
$ make # depends on libapparmor having been built first
$ make
$ make check
$ make install
@@ -146,20 +146,6 @@ For details on structure and adding tests, see libraries/libapparmor/README.
$ cd libraries/libapparmor
$ make check
Utils
-----
There are some simple tests available, including basic perl syntax
checks for the perl modules and executables. There are also minimal
checks on the python utilities and python-based tests in the test/
subdirectory.
$ cd utils
$ make check
The aa-decode utility to be tested can be overridden by
setting up environment variable APPARMOR_DECODE; e.g.:
$ APPARMOR_DECODE=/usr/bin/aa-decode make check
Profile checks
--------------
A basic consistency check to ensure that the parser and aa-logprof parse
@@ -198,22 +184,3 @@ Building and Installing AppArmor Kernel Patches
TODO
-----------------
Required versions
-----------------
The AppArmor userspace utilities are written with some assumptions about
installed and available versions of other tools. This is a (possibly
incomplete) list of known version dependencies:
AppArmor.pm (used by aa-audit, aa-autodep, aa-complain, aa-disable,
aa-enforce, aa-genprof, aa-logprof, aa-unconfined) requires minimum
Perl 5.10.1.
Python scripts require a minimum of Python 2.7. Some utilities as well
as some of the parser test scripts may require Python 3.3. Python 3.0,
3.1, and 3.2 are largely untested.
Most shell scripts are written for POSIX-compatible sh. aa-decode expects
bash, probably version 3.2 and higher.

View File

@@ -41,45 +41,12 @@ APXS:=$(shell if [ -x "/usr/sbin/apxs2" ] ; then \
fi )
APXS_INSTALL_DIR=$(shell ${APXS} -q LIBEXECDIR)
DESTDIR=
ifdef USE_SYSTEM
LIBAPPARMOR = $(shell if pkg-config --exists libapparmor ; then \
pkg-config --silence-errors --libs libapparmor ; \
elif ldconfig -p | grep -q libapparmor\.so$$ ; then \
echo -lapparmor ; \
fi )
ifeq ($(strip $(LIBAPPARMOR)),)
ERROR_MESSAGE = $(error ${nl}\
************************************************************************${nl}\
Unable to find libapparmor installed on this system; either${nl}\
install libapparmor devel packages, set the LIBAPPARMOR variable${nl}\
manually, or build against in-tree libapparmor.${nl}\
************************************************************************${nl})
endif # LIBAPPARMOR not set
LDLIBS += $(LIBAPPARMOR)
else
LIBAPPARMOR_SRC := ../../libraries/libapparmor/
LIBAPPARMOR_INCLUDE = $(LIBAPPARMOR_SRC)/include
LIBAPPARMOR_PATH := $(LIBAPPARMOR_SRC)/src/.libs/
ifeq ($(realpath $(LIBAPPARMOR_PATH)/libapparmor.a),)
ERROR_MESSAGE = $(error ${nl}\
************************************************************************${nl}\
$(LIBAPPARMOR_PATH)/libapparmor.a is missing; either build against${nl}\
the in-tree libapparmor by building it first and then trying again${nl}\
(see the top-level README for help) or build against the system${nl}\
libapparmor by adding USE_SYSTEM=1 to your make command.${nl}\
************************************************************************${nl})
endif
# Need to pass -Wl twice here to get past both apxs2 and libtool, as
# libtool will add the path to the RPATH of the library if passed -L/some/path
LIBAPPARMOR_FLAGS = -I$(LIBAPPARMOR_INCLUDE) -Wl,-Wl,-L$(LIBAPPARMOR_PATH)
LDLIBS = -lapparmor
endif
# Need to pass -Wl twice here to get past both apxs2 and libtool, as
# libtool will add the path to the RPATH of the library if passed -L/some/path
LIBAPPARMOR_FLAGS=-I../../libraries/libapparmor/src -Wl,-Wl,-L../../libraries/libapparmor/src/.libs
LDLIBS=-lapparmor
.PHONY: libapparmor_check
.SILENT: libapparmor_check
libapparmor_check: ; $(ERROR_MESSAGE)
all: libapparmor_check $(TARGET) ${MANPAGES} ${HTMLMANPAGES}
all: $(TARGET) ${MANPAGES} ${HTMLMANPAGES}
%.so: %.c
${APXS} ${LIBAPPARMOR_FLAGS} -c $< ${LDLIBS}
@@ -95,6 +62,3 @@ install: ${TARGET} ${MANPAGES}
clean: _clean
rm -rf .libs
rm -f *.la *.lo *.so *.o *.slo Make.rules
.PHONY: check
check: check_pod_files

View File

@@ -1,13 +1,12 @@
/*
* Copyright (c) 2004, 2005, 2006 NOVELL (All rights reserved)
* Copyright (c) 2014 Canonical, Ltd. (All rights reserved)
*
* The mod_apparmor module is licensed under the terms of the GNU
* Lesser General Public License, version 2.1. Please see the file
* COPYING.LGPL.
*
* mod_apparmor - (apache 2.0.x)
* Author: Steve Beattie <steve@nxnw.org>
* Author: Steve Beattie <sbeattie@suse.de>
*
* This currently only implements change_hat functionality, but could be
* extended for other stuff we decide to do.
@@ -18,240 +17,183 @@
#include "http_config.h"
#include "http_request.h"
#include "http_log.h"
#include "http_main.h"
#include "http_protocol.h"
#include "util_filter.h"
#include "apr.h"
#include "apr_strings.h"
#include "apr_lib.h"
#include <sys/apparmor.h>
#include <apparmor.h>
#include <unistd.h>
/* #define DEBUG */
#ifndef __unused
#define __unused __attribute__((unused))
#endif
/* should the following be configurable? */
#define DEFAULT_HAT "HANDLING_UNTRUSTED_INPUT"
#define DEFAULT_URI_HAT "DEFAULT_URI"
/* Compatibility with apache 2.2 */
#if AP_SERVER_MAJORVERSION_NUMBER == 2 && AP_SERVER_MINORVERSION_NUMBER < 3
#define APLOG_TRACE1 APLOG_DEBUG
server_rec *ap_server_conf = NULL;
#endif
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(apparmor);
#endif
module AP_MODULE_DECLARE_DATA apparmor_module;
static unsigned long magic_token = 0;
static unsigned int magic_token = 0;
static int inside_default_hat = 0;
typedef struct {
const char *hat_name;
char *path;
} apparmor_dir_cfg;
const char * hat_name;
char * path;
} immunix_dir_cfg;
typedef struct {
const char *hat_name;
int is_initialized;
} apparmor_srv_cfg;
const char * hat_name;
int is_initialized;
} immunix_srv_cfg;
/* aa_init() gets invoked in the post_config stage of apache.
/* immunix_init() gets invoked in the post_config stage of apache.
* Unfortunately, apache reads its config once when it starts up, then
* it re-reads it when goes into its restart loop, where it starts it's
* children. This means we cannot call change_hat here, as the modules
* memory will be wiped out, and the magic_token will be lost, so apache
* wouldn't be able to change_hat back out. */
static int
aa_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
static int
immunix_init (apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
{
apr_file_t *file;
apr_size_t size = sizeof(magic_token);
apr_file_t * file;
apr_size_t size = sizeof (magic_token);
int ret;
ret = apr_file_open (&file, "/dev/urandom", APR_READ, APR_OS_DEFAULT, p);
if (!ret) {
apr_file_read(file, (void *) &magic_token, &size);
apr_file_close(file);
apr_file_read (file, (void *) &magic_token, &size);
apr_file_close (file);
} else {
ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
"Failed to open /dev/urandom");
ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, "Failed to open /dev/urandom");
}
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
"Opened /dev/urandom successfully");
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "Opened /dev/urandom successfully");
return OK;
}
/* As each child starts up, we'll change_hat into a default hat, mostly
* to protect ourselves from bugs in parsing network input, but before
* we change_hat to the uri specific hat. */
static void
aa_child_init(apr_pool_t *p, server_rec *s)
static void
immunix_child_init (apr_pool_t *p, server_rec *s)
{
int ret;
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
"init: calling change_hat with '%s'", DEFAULT_HAT);
ret = aa_change_hat(DEFAULT_HAT, magic_token);
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "init: calling change_hat");
ret = change_hat (DEFAULT_HAT, magic_token);
if (ret < 0) {
ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
"Failed to change_hat to '%s'", DEFAULT_HAT);
change_hat (NULL, magic_token);
ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, "Failed to change_hat to '%s'",
DEFAULT_HAT);
} else {
inside_default_hat = 1;
}
}
}
#ifdef DEBUG
static void
debug_dump_uri(request_rec *r)
debug_dump_uri (apr_uri_t * uri)
{
apr_uri_t *uri = &r->parsed_uri;
if (uri)
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Dumping uri info "
"scheme='%s' host='%s' path='%s' query='%s' fragment='%s'",
uri->scheme, uri->hostname, uri->path, uri->query,
uri->fragment);
if (uri)
ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, "Dumping uri info "
"scheme='%s' host='%s' path='%s' query='%s' fragment='%s'",
uri->scheme, uri->hostname, uri->path, uri->query,
uri->fragment);
else
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Asked to dump NULL uri");
ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, "Asked to dump NULL uri");
}
/*
aa_enter_hat will attempt to change_hat in the following order:
#else
static void
debug_dump_uri (apr_uri_t * __unused uri) { }
#endif
/*
immunix_enter_hat will attempt to change_hat in the following order:
(1) to a hatname in a location directive
(2) to the server name or a defined per-server default
(3) to the server name + "-" + uri
(4) to the uri
(5) to DEFAULT_URI
(6) back to the parent profile
(2) to the uri
(3) to a per-server default
(4) to DEFAULT_URI
(5) back to the parent profile
*/
static int
aa_enter_hat(request_rec *r)
static int
immunix_enter_hat (request_rec *r)
{
int aa_ret = -1;
apparmor_dir_cfg *dcfg = (apparmor_dir_cfg *)
ap_get_module_config(r->per_dir_config, &apparmor_module);
apparmor_srv_cfg *scfg = (apparmor_srv_cfg *)
ap_get_module_config(r->server->module_config, &apparmor_module);
const char *aa_hat_array[6] = { NULL, NULL, NULL, NULL, NULL, NULL };
int i = 0;
char *aa_con, *aa_mode, *aa_hat;
const char *vhost_uri;
int sd_ret = -1;
immunix_dir_cfg * dcfg = (immunix_dir_cfg *)
ap_get_module_config (r->per_dir_config, &apparmor_module);
immunix_srv_cfg * scfg = (immunix_srv_cfg *)
ap_get_module_config (r->server->module_config, &apparmor_module);
debug_dump_uri(r);
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "aa_enter_hat (%s) n:0x%lx p:0x%lx main:0x%lx",
dcfg->path, (unsigned long) r->next, (unsigned long) r->prev,
(unsigned long) r->main);
debug_dump_uri (&r->parsed_uri);
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "in immunix_enter_hat (%s) n:0x%lx p:0x%lx main:0x%lx",
dcfg->path, (unsigned long) r->next, (unsigned long) r->prev,
(unsigned long) r->main);
/* We only call change_hat for the main request, not subrequests */
if (r->main)
return OK;
if (r->main)
return OK;
if (inside_default_hat) {
aa_change_hat(NULL, magic_token);
inside_default_hat = 0;
change_hat (NULL, magic_token);
inside_default_hat = 0;
}
if (dcfg != NULL && dcfg->hat_name != NULL) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"[dcfg] adding hat '%s' to aa_change_hat vector", dcfg->hat_name);
aa_hat_array[i++] = dcfg->hat_name;
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "calling change_hat [dcfg] %s", dcfg->hat_name);
sd_ret = change_hat (dcfg->hat_name, magic_token);
if (sd_ret < 0) {
change_hat (NULL, magic_token);
} else {
return OK;
}
}
if (scfg) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Dumping scfg info: "
"scfg='0x%lx' scfg->hat_name='%s'",
(unsigned long) scfg, scfg->hat_name);
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "calling change_hat [uri] %s", r->uri);
sd_ret = change_hat (r->uri, magic_token);
if (sd_ret < 0) {
change_hat (NULL, magic_token);
} else {
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "scfg is null");
}
if (scfg != NULL) {
if (scfg->hat_name != NULL) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"[scfg] adding hat '%s' to aa_change_hat vector", scfg->hat_name);
aa_hat_array[i++] = scfg->hat_name;
} else {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"[scfg] adding server_name '%s' to aa_change_hat vector",
r->server->server_hostname);
aa_hat_array[i++] = r->server->server_hostname;
}
vhost_uri = apr_pstrcat(r->pool, r->server->server_hostname, "-", r->uri, NULL);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"[vhost+uri] adding vhost+uri '%s' to aa_change_hat vector", vhost_uri);
aa_hat_array[i++] = vhost_uri;
return OK;
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"[uri] adding uri '%s' to aa_change_hat vector", r->uri);
aa_hat_array[i++] = r->uri;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"[default] adding '%s' to aa_change_hat vector", DEFAULT_URI_HAT);
aa_hat_array[i++] = DEFAULT_URI_HAT;
aa_ret = aa_change_hatv(aa_hat_array, magic_token);
if (aa_ret < 0) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, errno, r, "aa_change_hatv call failed");
if (scfg != NULL && scfg->hat_name != NULL) {
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "calling change_hat [scfg] %s", scfg->hat_name);
sd_ret = change_hat (scfg->hat_name, magic_token);
if (sd_ret < 0) {
change_hat (NULL, magic_token);
} else {
return OK;
}
}
/* Check to see if a defined AAHatName or AADefaultHatName would
* apply, but wasn't the hat we landed up in; report a warning if
* that's the case. */
aa_ret = aa_getcon(&aa_con, &aa_mode);
if (aa_ret < 0) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, errno, r, "aa_getcon call failed");
} else {
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"AA checks: aa_getcon result is '%s', mode '%s'", aa_con, aa_mode);
/* TODO: use libapparmor get hat_name fn here once it is implemented */
aa_hat = strstr(aa_con, "//");
if (aa_hat != NULL && strcmp(aa_mode, "enforce") == 0) {
aa_hat += 2; /* skip "//" */
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"AA checks: apache is in hat '%s', mode '%s'", aa_hat, aa_mode);
if (dcfg != NULL && dcfg->hat_name != NULL) {
if (strcmp(aa_hat, dcfg->hat_name) != 0)
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"AAHatName '%s' applies, but does not appear to be a hat in the apache apparmor policy",
dcfg->hat_name);
} else if (scfg != NULL && scfg->hat_name != NULL) {
if (strcmp(aa_hat, scfg->hat_name) != 0 &&
strcmp(aa_hat, r->uri) != 0)
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"AADefaultHatName '%s' applies, but does not appear to be a hat in the apache apparmor policy",
scfg->hat_name);
}
}
free(aa_con);
}
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "calling change_hat DEFAULT_URI");
sd_ret = change_hat (DEFAULT_URI_HAT, magic_token);
if (sd_ret < 0) change_hat (NULL, magic_token);
return OK;
}
static int
aa_exit_hat(request_rec *r)
static int
immunix_exit_hat (request_rec *r)
{
int aa_ret;
apparmor_dir_cfg *dcfg = (apparmor_dir_cfg *)
ap_get_module_config(r->per_dir_config, &apparmor_module);
/* apparmor_srv_cfg *scfg = (apparmor_srv_cfg *)
ap_get_module_config(r->server->module_config, &apparmor_module); */
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "exiting change_hat: dir hat %s dir path %s",
dcfg->hat_name, dcfg->path);
int sd_ret;
immunix_dir_cfg * dcfg = (immunix_dir_cfg *)
ap_get_module_config (r->per_dir_config, &apparmor_module);
/* immunix_srv_cfg * scfg = (immunix_srv_cfg *)
ap_get_module_config (r->server->module_config, &apparmor_module); */
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "exiting change_hat - dir hat %s path %s", dcfg->hat_name, dcfg->path);
change_hat (NULL, magic_token);
/* can convert the following back to aa_change_hat() when the
* aa_change_hat() bug addressed in trunk commit 2329 lands in most
* system libapparmors */
aa_change_hatv(NULL, magic_token);
aa_ret = aa_change_hat(DEFAULT_HAT, magic_token);
if (aa_ret < 0) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
"Failed to change_hat to '%s'", DEFAULT_HAT);
sd_ret = change_hat (DEFAULT_HAT, magic_token);
if (sd_ret < 0) {
change_hat (NULL, magic_token);
ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, "Failed to change_hat to '%s'",
DEFAULT_HAT);
} else {
inside_default_hat = 1;
}
@@ -260,15 +202,15 @@ aa_exit_hat(request_rec *r)
}
static const char *
aa_cmd_ch_path(cmd_parms *cmd, void *mconfig, const char *parm1)
aa_cmd_ch_path (cmd_parms * cmd, void * mconfig, const char * parm1)
{
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, "directory config change hat %s",
parm1 ? parm1 : "DEFAULT");
apparmor_dir_cfg *dcfg = mconfig;
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, "config change hat %s",
parm1 ? parm1 : "DEFAULT");
immunix_dir_cfg * dcfg = mconfig;
if (parm1 != NULL) {
dcfg->hat_name = parm1;
dcfg->hat_name = parm1;
} else {
dcfg->hat_name = "DEFAULT";
dcfg->hat_name = "DEFAULT";
}
return NULL;
}
@@ -276,27 +218,26 @@ aa_cmd_ch_path(cmd_parms *cmd, void *mconfig, const char *parm1)
static int path_warn_once;
static const char *
immunix_cmd_ch_path(cmd_parms *cmd, void *mconfig, const char *parm1)
immunix_cmd_ch_path (cmd_parms * cmd, void * mconfig, const char * parm1)
{
if (path_warn_once == 0) {
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, "ImmHatName is "
"deprecated, please use AAHatName instead");
path_warn_once = 1;
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, "ImmHatName is "
"deprecated, please use AAHatName instead");
path_warn_once = 1;
}
return aa_cmd_ch_path(cmd, mconfig, parm1);
}
static const char *
aa_cmd_ch_srv(cmd_parms *cmd, void *mconfig, const char *parm1)
aa_cmd_ch_srv (cmd_parms * cmd, void * mconfig, const char * parm1)
{
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, "server config change hat %s",
parm1 ? parm1 : "DEFAULT");
apparmor_srv_cfg *scfg = (apparmor_srv_cfg *)
ap_get_module_config(cmd->server->module_config, &apparmor_module);
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, "config change hat %s",
parm1 ? parm1 : "DEFAULT");
immunix_srv_cfg * scfg = mconfig;
if (parm1 != NULL) {
scfg->hat_name = parm1;
scfg->hat_name = parm1;
} else {
scfg->hat_name = "DEFAULT";
scfg->hat_name = "DEFAULT";
}
return NULL;
}
@@ -304,29 +245,27 @@ aa_cmd_ch_srv(cmd_parms *cmd, void *mconfig, const char *parm1)
static int srv_warn_once;
static const char *
immunix_cmd_ch_srv(cmd_parms *cmd, void *mconfig, const char *parm1)
immunix_cmd_ch_srv (cmd_parms * cmd, void * mconfig, const char * parm1)
{
if (srv_warn_once == 0) {
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, "ImmDefaultHatName is "
"deprecated, please use AADefaultHatName instead");
srv_warn_once = 1;
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, "ImmDefaultHatName is "
"deprecated, please use AADefaultHatName instead");
srv_warn_once = 1;
}
return aa_cmd_ch_srv(cmd, mconfig, parm1);
}
static void *
aa_create_dir_config(apr_pool_t *p, char *path)
immunix_create_dir_config (apr_pool_t * p, char * path)
{
apparmor_dir_cfg *newcfg = (apparmor_dir_cfg *) apr_pcalloc(p, sizeof(*newcfg));
immunix_dir_cfg * newcfg = (immunix_dir_cfg *) apr_pcalloc(p, sizeof(* newcfg));
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
"aa_create_dir_cfg (%s)", path ? path : ":no path:");
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "in immunix_create_dir (%s)", path ? path : ":no path:");
if (newcfg == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf,
"aa_create_dir_config: couldn't alloc dir config");
return NULL;
ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, "immunix_create_dir: couldn't alloc dir config");
return NULL;
}
newcfg->path = apr_pstrdup(p, path ? path : ":no path:");
newcfg->path = apr_pstrdup (p, path ? path : ":no path:");
return newcfg;
}
@@ -334,93 +273,83 @@ aa_create_dir_config(apr_pool_t *p, char *path)
/* XXX: Should figure out an appropriate action to take here, if any
static void *
aa_merge_dir_config(apr_pool_t *p, void *parent, void *child)
immunix_merge_dir_config (apr_pool_t * p, void * parent, void * child)
{
apparmor_dir_cfg *newcfg = (apparmor_dir_cfg *) apr_pcalloc(p, sizeof(*newcfg));
immunix_dir_cfg * newcfg = (immunix_dir_cfg *) apr_pcalloc(p, sizeof(* newcfg));
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf, "in immunix_merge_dir ()");
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "in immunix_merge_dir ()");
if (newcfg == NULL)
return NULL;
return NULL;
return newcfg;
}
*/
static void *
aa_create_srv_config(apr_pool_t *p, server_rec *srv)
immunix_create_srv_config (apr_pool_t * p, server_rec * srv)
{
apparmor_srv_cfg *newcfg = (apparmor_srv_cfg *) apr_pcalloc(p, sizeof(*newcfg));
immunix_srv_cfg * newcfg = (immunix_srv_cfg *) apr_pcalloc(p, sizeof(* newcfg));
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
"in aa_create_srv_config");
ap_log_error (APLOG_MARK, APLOG_DEBUG, 0, NULL, "in immunix_create_srv");
if (newcfg == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf,
"aa_create_srv_config: couldn't alloc srv config");
return NULL;
ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, "immunix_create_srv: couldn't alloc srv config");
return NULL;
}
return newcfg;
}
static const command_rec mod_apparmor_cmds[] = {
static const command_rec immunix_cmds[] = {
AP_INIT_TAKE1(
AP_INIT_TAKE1 (
"ImmHatName",
immunix_cmd_ch_path,
NULL,
ACCESS_CONF,
""
immunix_cmd_ch_path,
NULL,
ACCESS_CONF,
""
),
AP_INIT_TAKE1(
AP_INIT_TAKE1 (
"ImmDefaultHatName",
immunix_cmd_ch_srv,
NULL,
RSRC_CONF,
""
immunix_cmd_ch_srv,
NULL,
RSRC_CONF,
""
),
AP_INIT_TAKE1(
AP_INIT_TAKE1 (
"AAHatName",
aa_cmd_ch_path,
NULL,
ACCESS_CONF,
""
aa_cmd_ch_path,
NULL,
ACCESS_CONF,
""
),
AP_INIT_TAKE1(
AP_INIT_TAKE1 (
"AADefaultHatName",
aa_cmd_ch_srv,
NULL,
RSRC_CONF,
""
aa_cmd_ch_srv,
NULL,
RSRC_CONF,
""
),
{ NULL }
};
static void
register_hooks(apr_pool_t *p)
static void
register_hooks (apr_pool_t *p)
{
ap_hook_post_config(aa_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_child_init(aa_child_init, NULL, NULL, APR_HOOK_MIDDLE);
#if AP_SERVER_MAJORVERSION_NUMBER == 2 && AP_SERVER_MINORVERSION_NUMBER < 3
/* Compatibility with apache 2.2 */
ap_hook_access_checker(aa_enter_hat, NULL, NULL, APR_HOOK_FIRST);
#else
/* apache 2.4 mod_authz hook */
ap_hook_check_access_ex(aa_enter_hat, NULL, NULL, APR_HOOK_FIRST, AP_AUTH_INTERNAL_PER_CONF);
#endif
/* ap_hook_post_read_request(aa_enter_hat, NULL, NULL, APR_HOOK_FIRST); */
ap_hook_log_transaction(aa_exit_hat, NULL, NULL, APR_HOOK_LAST);
ap_hook_post_config (immunix_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_child_init (immunix_child_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_access_checker(immunix_enter_hat, NULL, NULL, APR_HOOK_FIRST);
/* ap_hook_post_read_request(immunix_enter_hat, NULL, NULL, APR_HOOK_FIRST); */
ap_hook_log_transaction(immunix_exit_hat, NULL, NULL, APR_HOOK_LAST);
}
module AP_MODULE_DECLARE_DATA apparmor_module = {
STANDARD20_MODULE_STUFF,
aa_create_dir_config, /* dir config creater */
NULL, /* dir merger --- default is to override */
/* immunix_merge_dir_config, */ /* dir merger --- default is to override */
aa_create_srv_config, /* server config */
NULL, /* merge server config */
mod_apparmor_cmds, /* command table */
register_hooks /* register hooks */
immunix_create_dir_config, /* dir config creater */
NULL, /* dir merger --- default is to override */
/* immunix_merge_dir_config, */ /* dir merger --- default is to override */
immunix_create_srv_config, /* server config */
NULL, /* merge server config */
immunix_cmds, /* command table */
register_hooks /* register hooks */
};

View File

@@ -40,15 +40,11 @@ apache2(8)/httpd(8) configuration files, and restart Apache. Make sure that
apparmor is also functioning.
Once mod_apparmor is loaded within Apache, all requests to Apache will
cause mod_apparmor to attempt to change into a hat that matches the
ServerName for the server/vhost. If no such hat is found, it will
first fall back by attempting to change into a hat composed of the
ServerName-URI (e.g. "www.example.com-/app/some.cgi"). If that hat
is not found, it will fall back to attempting to use the hat named
by the URI (e.g. "/app/some.cgi"). If that hat is not found, it will
fall back to attempting to use the hat DEFAULT_URI; if that also does
not exist, it will fall back to using the global Apache profile. Most
static web pages can simply make use of the DEFAULT_URI hat.
cause mod_apparmor to attempt to change into a hat named by the URI
(e.g. /app/some.cgi). If no such hat is found, it will fall back to
attempting to use the hat DEFAULT_URI; if that also does not exist,
it will fall back to using the global Apache profile. Most static web
pages can simply make use of the DEFAULT_URI hat.
Additionally, before any requests come in to Apache, mod_apparmor
will attempt to change hat into the HANDLING_UNTRUSTED_INPUT hat.
@@ -64,7 +60,7 @@ provides the AAHatName and AADefaultHatName Apache configuration options.
=item B<AAHatName>
AAHatName allows you to specify a hat to be used for a given Apache
E<lt>DirectoryE<gt>, E<lt>DirectoryMatchE<gt>, E<lt>LocationE<gt> or
E<lt>DirectoryE<gt>, E<lt>DirectoryMatch>, E<lt>LocationE<gt> or
E<lt>LocationMatchE<gt> directive (see the Apache documenation for more
details). Note that mod_apparmor behavior can become confused if
E<lt>Directory*E<gt> and E<lt>Location*E<gt> directives are intermingled
@@ -76,11 +72,11 @@ behavior described above.
AADefaultHatName allows you to specify a default hat to be used for
virtual hosts and other Apache server directives, so that you can have
different defaults for different virtual hosts. This can be overridden
by the AAHatName directive and is checked for only if there isn't
a matching AAHatName. The default value of AADefaultHatName is the
ServerName for the server/vhost configuration. If the AADefaultHatName
hat does not exist, then it falls back to the behavior described above.
different defaults for different virtual hosts. This can be overridden by
the AAHatName directive and is checked for only if there isn't a matching
AAHatName or hat named by the URI. If the AADefaultHatName hat does not
exist, it falls back to the DEFAULT_URI hat if it exists (as described
above).
=back
@@ -95,35 +91,20 @@ On each URI request, mod_apparmor will first aa_change_hat(2) into
Then, after performing the initial parsing of the request, mod_apparmor
will:
=over 4
=over 2
=item 1
try to aa_change_hat(2) into a matching AAHatName hat if it exists and
1. try to aa_change_hat(2) into a matching AAHatName hat if it exists and
applies, otherwise it will
=item 2
2. try to aa_change_hat(2) into the URI itself, otherwise it will
try to aa_change_hat(2) into an AADefaultHatName hat, either the
ServerName (the default) or the configuration value specified by the
AADefaultHatName directive, for the server/vhost, otherwise it will
3. try to aa_change_hat(2) into an AADefaultHatName hat if it has been defined
for the server/vhost, otherwise it will
=item 3
try to aa_change_hat(2) into the ServerName-URI, otherwise it will
=item 4
try to aa_change_hat(2) into the URI itself, otherwise it will
=item 5
try to aa_change_hat(2) into the DEFAULT_URI hat, if it exists, otherwise it
4. try to aa_change_hat(2) into the DEFAULT_URI hat, if it exists, otherwise it
will
=item 6
fall back to the global Apache policy
5. fall back to the global Apache policy
=back
@@ -131,11 +112,10 @@ fall back to the global Apache policy
mod_apparmor() currently only supports apache2, and has only been tested
with the prefork MPM configuration -- threaded configurations of Apache
may not work correctly. For Apache 2.4 users, you should enable the mpm_prefork
module.
may not work correctly.
There are likely other bugs lurking about; if you find any, please report
them at L<https://bugs.launchpad.net/apparmor/+filebug>.
them at L<http://https://bugs.launchpad.net/apparmor/+filebug>.
=head1 SEE ALSO

View File

@@ -26,50 +26,12 @@ common/Make.rules: $(COMMONDIR)/Make.rules
ln -sf $(COMMONDIR) .
endif
ifdef USE_SYSTEM
LIBAPPARMOR = $(shell if pkg-config --exists libapparmor ; then \
pkg-config --silence-errors --libs libapparmor ; \
elif ldconfig -p | grep -q libapparmor\.so$$ ; then \
echo -lapparmor ; \
fi )
ifeq ($(strip $(LIBAPPARMOR)),)
ERROR_MESSAGE = $(error ${nl}\
************************************************************************${nl}\
Unable to find libapparmor installed on this system; either${nl}\
install libapparmor devel packages, set the LIBAPPARMOR variable${nl}\
manually, or build against in-tree libapparmor.${nl}\
************************************************************************${nl})
endif
LIBAPPARMOR_INCLUDE =
AA_LDLIBS = $(LIBAPPARMOR)
AA_LINK_FLAGS =
else
LIBAPPARMOR_SRC := ../../libraries/libapparmor/
LIBAPPARMOR_INCLUDE_PATH = $(LIBAPPARMOR_SRC)/include
LIBAPPARMOR_PATH := $(LIBAPPARMOR_SRC)/src/.libs/
ifeq ($(realpath $(LIBAPPARMOR_PATH)/libapparmor.a),)
ERROR_MESSAGE = $(error ${nl}\
************************************************************************${nl}\
$(LIBAPPARMOR_PATH)/libapparmor.a is missing; either build against${nl}\
the in-tree libapparmor by building it first and then trying again${nl}\
(see the top-level README for help) or build against the system${nl}\
libapparmor by adding USE_SYSTEM=1 to your make command.${nl}\
************************************************************************${nl})
endif
LIBAPPARMOR_INCLUDE = -I$(LIBAPPARMOR_INCLUDE_PATH)
AA_LINK_FLAGS = -L$(LIBAPPARMOR_PATH)
AA_LDLIBS = -lapparmor
endif
EXTRA_CFLAGS=$(CFLAGS) -fPIC -shared -Wall $(LIBAPPARMOR_INCLUDE)
LINK_FLAGS=-Xlinker -x $(AA_LINK_FLAGS)
LIBS=-lpam $(AA_LDLIBS)
EXTRA_CFLAGS=$(CFLAGS) -fPIC -shared -Wall -I../../libraries/libapparmor/src/
LINK_FLAGS=-Xlinker -x -L../../libraries/libapparmor/src/.libs
LIBS=-lpam -lapparmor
OBJECTS=${NAME}.o get_options.o
.PHONY: libapparmor_check
.SILENT: libapparmor_check
libapparmor_check: ; $(ERROR_MESSAGE)
all: libapparmor_check $(NAME).so
all: $(NAME).so
$(NAME).so: ${OBJECTS}
$(CC) $(EXTRA_CFLAGS) $(LINK_FLAGS) -o $@ ${OBJECTS} $(LIBS)

View File

@@ -27,7 +27,7 @@
#include <grp.h>
#include <syslog.h>
#include <errno.h>
#include <sys/apparmor.h>
#include <apparmor.h>
#include <security/pam_ext.h>
#include <security/pam_modutil.h>

View File

@@ -13,7 +13,7 @@
#include "jni.h"
#include <errno.h>
#include <sys/apparmor.h>
#include "sys/apparmor.h"
#include "com_novell_apparmor_JNIChangeHat.h"
/* c intermediate lib call for Java -> JNI -> c library execution of the change_hat call */

View File

@@ -13,7 +13,7 @@
#include "jni.h"
#include <errno.h>
#include <sys/apparmor.h>
#include <apparmor.h>
#include "com_novell_apparmor_JNIChangeHat.h"
/* c intermediate lib call for Java -> JNI -> c library execution of the change_hat call */

View File

@@ -27,20 +27,6 @@
DISTRIBUTION=AppArmor
VERSION=$(shell cat common/Version)
# Convenience functions
pathsearch = $(firstword $(wildcard $(addsuffix /$(1),$(subst :, ,$(PATH)))))
map = $(foreach a,$(2),$(call $(1),$(a)))
AWK:=$(shell which awk)
ifndef AWK
$(error awk utility required for build but not available)
endif
define nl
endef
# OVERRIDABLE variables
# Set these variables before including Make.rules to change its behavior
# SPECFILE - for packages that have a non-standard specfile name
@@ -141,17 +127,6 @@ endif
endif
ifndef PYTHON_VERSIONS
PYTHON_VERSIONS = $(call map, pathsearch, python2 python3)
endif
ifndef PYTHON
PYTHON = $(firstword ${PYTHON_VERSIONS})
endif
#Helper function to be used with $(call pyalldo, run_test_with_all.py)
pyalldo=set -e; $(foreach py, $(PYTHON_VERSIONS), $(py) $(1);)
.PHONY: version
.SILENT: version
version:
@@ -175,40 +150,6 @@ _clean:
-rm -f ${NAME}-${VERSION}-*.tar.gz
-rm -f ${MANPAGES} *.[0-9].gz ${HTMLMANPAGES} pod2htm*.tmp
# =====================
# generate list of capabilities based on
# /usr/include/linux/capabilities.h for use in multiple locations in
# the source tree
# =====================
# emits defined capabilities in a simple list, e.g. "CAP_NAME CAP_NAME2"
CAPABILITIES=$(shell echo "\#include <linux/capability.h>" | cpp -dM | LC_ALL=C sed -n -e '/CAP_EMPTY_SET/d' -e 's/^\#define[ \t]\+CAP_\([A-Z0-9_]\+\)[ \t]\+\([0-9xa-f]\+\)\(.*\)$$/CAP_\1/p' | sort)
.PHONY: list_capabilities
list_capabilities: /usr/include/linux/capability.h
@echo "$(CAPABILITIES)"
# =====================
# generate list of network protocols based on
# sys/socket.h for use in multiple locations in
# the source tree
# =====================
# These are the families that it doesn't make sense for apparmor
# to mediate. We use PF_ here since that is what is required in
# bits/socket.h, but we will rewrite these as AF_.
FILTER_FAMILIES=PF_UNSPEC PF_UNIX
__FILTER=$(shell echo $(strip $(FILTER_FAMILIES)) | sed -e 's/ /\\\|/g')
# emits the AF names in a "AF_NAME NUMBER," pattern
AF_NAMES=$(shell echo "\#include <sys/socket.h>" | cpp -dM | LC_ALL=C sed -n -e '/$(__FILTER)/d' -e 's/PF_LOCAL/PF_UNIX/' -e 's/^\#define[ \t]\+PF_\([A-Z0-9_]\+\)[ \t]\+\([0-9]\+\).*$$/AF_\1 \2,/p' | sort -n -k2)
.PHONY: list_af_names
list_af_names:
@echo "$(AF_NAMES)"
# =====================
# manpages
# =====================
@@ -231,8 +172,29 @@ install_manpages: $(MANPAGES)
MAN_RELEASE="AppArmor ${VERSION}"
%.1 %.2 %.3 %.4 %.5 %.6 %.7 %.8: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --stderr --section=$(subst .,,$(suffix $@)) > $@
%.1: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --section=1 > $@
%.2: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --section=2 > $@
%.3: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --section=3 > $@
%.4: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --section=4 > $@
%.5: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --section=5 > $@
%.6: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --section=6 > $@
%.7: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --section=7 > $@
%.8: %.pod
$(POD2MAN) $< --release=$(MAN_RELEASE) --center=AppArmor --section=8 > $@
%.1.html: %.pod
$(POD2HTML) --header --css apparmor.css --infile=$< --outfile=$@
@@ -266,7 +228,3 @@ ENSCRIPT_ARGS=-C -2jGr -f Courier6 -E
%.pm.ps: %.pm
enscript ${ENSCRIPT_ARGS} -o $@ $<
.PHONY: check_pod_files
check_pod_files:
LANG=C podchecker -warning -warning *.pod

View File

@@ -1 +1 @@
2.8.97
2.7.1

View File

@@ -0,0 +1 @@
Matt Barringer <mbarringer@suse.de>

View File

@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library General
Public License instead of this License.

View File

@@ -0,0 +1,167 @@
Basic Installation
==================
These are generic installation instructions.
The `configure' shell script attempts to guess correct values for
various system-dependent variables used during compilation. It uses
those values to create a `Makefile' in each directory of the package.
It may also create one or more `.h' files containing system-dependent
definitions. Finally, it creates a shell script `config.status' that
you can run in the future to recreate the current configuration, a file
`config.cache' that saves the results of its tests to speed up
reconfiguring, and a file `config.log' containing compiler output
(useful mainly for debugging `configure').
If you need to do unusual things to compile the package, please try
to figure out how `configure' could check whether to do them, and mail
diffs or instructions to the address given in the `README' so they can
be considered for the next release. If at some point `config.cache'
contains results you don't want to keep, you may remove or edit it.
The file `configure.in' is used to create `configure' by a program
called `autoconf'. You only need `configure.in' if you want to change
it or regenerate `configure' using a newer version of `autoconf'.
The simplest way to compile this package is:
1. `cd' to the directory containing the package's source code and type
`./configure' to configure the package for your system. If you're
using `csh' on an old version of System V, you might need to type
`sh ./configure' instead to prevent `csh' from trying to execute
`configure' itself.
Running `configure' takes a while. While running, it prints some
messages telling which features it is checking for.
2. Type `make' to compile the package.
3. Type `make install' to install the programs and any data files and
documentation.
4. You can remove the program binaries and object files from the
source code directory by typing `make clean'.
Compilers and Options
=====================
Some systems require unusual options for compilation or linking that
the `configure' script does not know about. You can give `configure'
initial values for variables by setting them in the environment. Using
a Bourne-compatible shell, you can do that on the command line like
this:
CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure
Or on systems that have the `env' program, you can do it like this:
env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure
Compiling For Multiple Architectures
====================================
You can compile the package for more than one kind of computer at the
same time, by placing the object files for each architecture in their
own directory. To do this, you must use a version of `make' that
supports the `VPATH' variable, such as GNU `make'. `cd' to the
directory where you want the object files and executables to go and run
the `configure' script. `configure' automatically checks for the
source code in the directory that `configure' is in and in `..'.
If you have to use a `make' that does not supports the `VPATH'
variable, you have to compile the package for one architecture at a time
in the source code directory. After you have installed the package for
one architecture, use `make distclean' before reconfiguring for another
architecture.
Installation Names
==================
By default, `make install' will install the package's files in
`/usr/local/bin', `/usr/local/man', etc. You can specify an
installation prefix other than `/usr/local' by giving `configure' the
option `--prefix=PATH'.
You can specify separate installation prefixes for
architecture-specific files and architecture-independent files. If you
give `configure' the option `--exec-prefix=PATH', the package will use
PATH as the prefix for installing programs and libraries.
Documentation and other data files will still use the regular prefix.
If the package supports it, you can cause programs to be installed
with an extra prefix or suffix on their names by giving `configure' the
option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
Optional Features
=================
Some packages pay attention to `--enable-FEATURE' options to
`configure', where FEATURE indicates an optional part of the package.
They may also pay attention to `--with-PACKAGE' options, where PACKAGE
is something like `gnu-as' or `x' (for the X Window System). The
`README' should mention any `--enable-' and `--with-' options that the
package recognizes.
For packages that use the X Window System, `configure' can usually
find the X include and library files automatically, but if it doesn't,
you can use the `configure' options `--x-includes=DIR' and
`--x-libraries=DIR' to specify their locations.
Specifying the System Type
==========================
There may be some features `configure' can not figure out
automatically, but needs to determine by the type of host the package
will run on. Usually `configure' can figure that out, but if it prints
a message saying it can not guess the host type, give it the
`--host=TYPE' option. TYPE can either be a short name for the system
type, such as `sun4', or a canonical name with three fields:
CPU-COMPANY-SYSTEM
See the file `config.sub' for the possible values of each field. If
`config.sub' isn't included in this package, then this package doesn't
need to know the host type.
If you are building compiler tools for cross-compiling, you can also
use the `--target=TYPE' option to select the type of system they will
produce code for and the `--build=TYPE' option to select the type of
system on which you are compiling the package.
Sharing Defaults
================
If you want to set default values for `configure' scripts to share,
you can create a site shell script called `config.site' that gives
default values for variables like `CC', `cache_file', and `prefix'.
`configure' looks for `PREFIX/share/config.site' if it exists, then
`PREFIX/etc/config.site' if it exists. Or, you can set the
`CONFIG_SITE' environment variable to the location of the site script.
A warning: not all `configure' scripts look for a site script.
Operation Controls
==================
`configure' recognizes the following options to control how it
operates.
`--cache-file=FILE'
Use and save the results of the tests in FILE instead of
`./config.cache'. Set FILE to `/dev/null' to disable caching, for
debugging `configure'.
`--help'
Print a summary of the options to `configure', and exit.
`--quiet'
`--silent'
`-q'
Do not print messages saying which checks are being made.
`--srcdir=DIR'
Look for the package's source code in directory DIR. Usually
`configure' can determine that directory automatically.
`--version'
Print the version of Autoconf used to generate the `configure'
script, and exit.
`configure' also accepts some other, not widely useful, options.

View File

@@ -0,0 +1,5 @@
# not a GNU package. You can remove this line, if
# have all needed files, that a GNU package needs
AUTOMAKE_OPTIONS = foreign 1.4
SUBDIRS = src

View File

@@ -0,0 +1,8 @@
In order to actually use aadbus, you need to tell auditd to use it as a dispatcher. It's simple:
* As root, edit /etc/auditd.conf
* Add the following line (using the correct path, of course):
dispatcher=/usr/local/bin/apparmor-dbus
* Restart auditd

View File

@@ -0,0 +1,43 @@
#
# spec file for package apparmor-dbus
#
# norootforbuild
Name: apparmor-dbus
BuildRequires: audit-devel dbus-1-devel pkgconfig libapparmor-devel
Requires: libapparmor
Version: 2.3
Release: 0
License: GPL
Group: System/Management
BuildRoot: %{_tmppath}/%{name}-%{version}-build
Source0: %{name}-%{version}.tar.bz2
Summary: -
%description
-
%prep
%setup -n %{name}-%{version}
%build
autoreconf --force --install
export CFLAGS="$RPM_OPT_FLAGS"
%{?suse_update_config:%{suse_update_config -f}}
./configure --prefix=%{_prefix}
make
%install
rm -rf %{buildroot}
%makeinstall
%clean
rm -rf %{buildroot}
%files
%defattr(-, root, root)
%{_prefix}/bin/apparmor-dbus
%changelog
* Thu Sep 13 2007 - sbeattie@suse.de
- Bump to revision 1.2

View File

@@ -0,0 +1,31 @@
#!/bin/sh
DIE=0
(autoconf --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "You must have autoconf installed to compile $package."
echo "Download the appropriate package for your distribution,"
echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/"
DIE=1
}
(automake --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "You must have automake installed to compile $package."
echo "Download the appropriate package for your system,"
echo "or get the source from one of the GNU ftp sites"
echo "listed in http://www.gnu.org/order/ftp.html"
DIE=1
}
if test "$DIE" -eq 1; then
exit 1
fi
echo "Running aclocal"
aclocal
echo "Running autoconf"
autoconf --force
echo "Running automake -ac"
automake -ac

View File

@@ -0,0 +1,16 @@
AC_INIT(configure.in)
AM_INIT_AUTOMAKE(apparmor-dbus, 2.3)
AC_LANG_C
AC_PROG_CC
AC_CHECK_HEADERS(libaudit.h,,AC_MSG_ERROR([libaudit header file not found!]))
AC_CHECK_LIB(audit, audit_open)
AC_CHECK_HEADERS(aalogparse/aalogparse.h)
AC_CHECK_LIB(apparmor, parse_record)
PKG_CHECK_MODULES(DBUS, dbus-1 >= 0.60)
CFLAGS="${CFLAGS} ${DBUS_CFLAGS}"
AC_CHECK_LIB(dbus-1, exit,,AC_MSG_ERROR([dbus-1 not found!]))
AC_OUTPUT(Makefile src/Makefile)

View File

@@ -0,0 +1,2 @@
bin_PROGRAMS = apparmor-dbus
apparmor_dbus_SOURCES = aadbus.c

View File

@@ -0,0 +1,322 @@
#define DBUS_API_SUBJECT_TO_CHANGE
#include <stdio.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <locale.h>
#include <libaudit.h>
#include <dbus/dbus.h>
#include <aalogparse/aalogparse.h>
#define NULLSPACE(x) (x == NULL) ? &empty_string : &x
#define NULLSTRLEN(x) (x == NULL) ? 1 : (strlen(x) + 1)
// Local data
static volatile int signaled = 0;
static int pipe_fd;
// Local functions
static int event_loop(void);
static int is_reject(char *data);
// SIGTERM handler
static void term_handler( int sig )
{
signaled = 1;
}
/*
* main is started by auditd. See dispatcher in auditd.conf
*/
int main(int argc, char *argv[])
{
struct sigaction sa;
setlocale (LC_ALL, "");
#ifndef DEBUG
/* Make sure we are root */
if (getuid() != 0) {
printf("You must be root to run this program.\n");
return 4;
}
#endif
// register sighandlers
sa.sa_flags = 0 ;
sa.sa_handler = term_handler;
sigemptyset( &sa.sa_mask ) ;
sigaction( SIGTERM, &sa, NULL );
sa.sa_handler = term_handler;
sigemptyset( &sa.sa_mask ) ;
sigaction( SIGCHLD, &sa, NULL );
sa.sa_handler = SIG_IGN;
sigaction( SIGHUP, &sa, NULL );
(void)chdir("/");
// change over to pipe_fd
pipe_fd = dup(0);
close(0);
open("/dev/null", O_RDONLY);
fcntl(pipe_fd, F_SETFD, FD_CLOEXEC);
// Start the program
return event_loop();
}
/* This function is needed for "old" messages which lumped
* everything together under one audit ID.
*/
static int is_reject (char *data)
{
int ret = -1;
/* Look for the first space */
char *start = strchr(data, ' ');
if ((start != NULL) && (strlen(start) > 9))
{
if (strncmp(start + 1, "REJECTING", 9) == 0)
{
ret = 0;
}
}
return ret;
}
static int event_loop(void)
{
void* data;
char *empty_string = " "; /* This is a quick way to indicate a 'null' value in our DBUS message */
struct iovec vec[2];
struct audit_dispatcher_header hdr;
DBusError error; /* Error, if any */
DBusMessage *message; /* Message to send */
static DBusConnection *con = NULL; /* Connection to DBUS server */
DBusMessageIter iter, /* The main message iterator */
profileIter,
nameIter,
name2Iter,
parentIter,
activeIter,
dataIter;
char *line = NULL, *parsable_line = NULL;
int real_data_size;
aa_log_record *record;
int is_rejection = 0;
if (con && !dbus_connection_get_is_connected(con))
{
dbus_connection_unref(con);
con = NULL;
}
if (!con)
{
dbus_error_init(&error);
con = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
if (!con)
{
dbus_error_free(&error);
return 1;
}
}
//message = dbus_message_new_signal("/com/Novell/AppArmor","com.novell.apparmor", "Reject");
/* allocate data structures */
data = malloc(MAX_AUDIT_MESSAGE_LENGTH);
if (data == NULL)
{
printf("Cannot allocate buffer\n");
return 1;
}
memset(data, 0, MAX_AUDIT_MESSAGE_LENGTH);
memset(&hdr, 0, sizeof(hdr));
do
{
int rc;
parsable_line = NULL;
is_rejection = 0;
struct timeval tv;
fd_set fd;
tv.tv_sec = 1;
tv.tv_usec = 0;
FD_ZERO(&fd);
FD_SET(pipe_fd, &fd);
rc = select(pipe_fd+1, &fd, NULL, NULL, &tv);
if (rc == 0)
continue;
else if (rc == -1)
break;
/* Get header first. it is fixed size */
vec[0].iov_base = (void*)&hdr;
vec[0].iov_len = sizeof(hdr);
memset(data, 0, MAX_AUDIT_MESSAGE_LENGTH);
// Next payload
vec[1].iov_base = data;
vec[1].iov_len = MAX_AUDIT_MESSAGE_LENGTH;
rc = readv(pipe_fd, vec, 2);
if (rc == 0 || rc == -1) {
printf("rc == %d(%s)\n", rc, strerror(errno));
break;
}
/* Handle the AppArmor events.
* 1500 is used for "old" style messages.
* 1503 is used for APPARMOR_DENIED messages.
*/
if ((hdr.type == 1500) || (hdr.type == 1503))
{
line = (char *) data;
record = NULL;
if (hdr.type == 1503)
is_rejection = 1;
if ((hdr.type == 1500) && (is_reject(line) == 0))
is_rejection = 1;
/* We only care about REJECTING messages */
if (is_rejection == 1)
{
/* parse_record expects things like they appear in audit.log -
* which means we need to prepend TYPE=APPARMOR (if hdr.type is 1500)
* or type=APPARMOR_DENIED (if hdr.type is 1503). This is not ideal.
*/
real_data_size = strlen(line);
if (hdr.type == 1500)
{
parsable_line = (char *) malloc(real_data_size + 20);
snprintf(parsable_line, real_data_size + 19, "type=APPARMOR msg=%s", line);
}
else
{
parsable_line = (char *) malloc(real_data_size + 27);
snprintf(parsable_line, real_data_size + 26, "type=APPARMOR_DENIED msg=%s", line);
}
record = parse_record(parsable_line);
message = dbus_message_new_signal("/com/Novell/AppArmor","com.novell.apparmor", "REJECT");
dbus_message_iter_init_append(message, &iter);
/*
* The message has a number of fields appended to it,
* all of which map to the aa_log_record struct that we get back from
* parse_record(). If an entry in the struct is NULL or otherwise invalid,
* the field is still appended as a single blank space (in the case of strings), or a
* 0 in case of integers (which are all PIDs and unlikely to ever be 0).
*
* TODO: Pass a bitmask int along for the denied & requested masks
*
* 1 - The full string - BYTE ARRAY
* 2 - The PID (record->pid) - DBUS_TYPE_INT64
* 3 - The task (record->task) - DBUS_TYPE_INT64
* 4 - The audit ID (record->audit_id) - DBUS_TYPE_STRING
* 5 - The operation (record->operation: "Exec" "ptrace" etc) - DBUS_TYPE_STRING
* 6 - The denied mask (record->denied_mask: "rwx" etc) - DBUS_TYPE_STRING
* 7 - The requested mask (record->requested_mask) - DBUS_TYPE_STRING
* 8 - The name of the profile (record->profile) - BYTE ARRAY
* 9 - The first name field (record->name) - BYTE ARRAY
* 10- The second name field (record->name2) - BYTE ARRAY
* 11- The attribute (record->attribute) - DBUS_TYPE_STRING
* 12- The parent task (record->parent) - BYTE ARRAY
* 13- The magic token (record->magic_token) - DBUS_TYPE_INT64
* 14- The info field (record->info) - BYTE ARRAY
* 15- The active hat (record->active_hat) - BYTE ARRAY
*/
if (record != NULL)
{
/* Please note: NULLSPACE is defined at the top of this file, and will expand to
a ternary conditional:
(record->audit_id == NULL) ? &empty_string : &record->audit_id
for example.
The way we handle strings is ugly - some of the characters we allow (0x80, for example) are invalid Unicode,
which will cause our DBus connection to be dropped if we send them as a DBUS_TYPE_STRING.
Instead, we send a bunch of containers, each with a byte array. Perhaps a struct would be better?
*/
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, &dataIter);
dbus_message_iter_append_fixed_array(&dataIter, DBUS_TYPE_BYTE, &data, strlen(data) + 1);
dbus_message_iter_close_container(&iter, &dataIter);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_INT64, &record->pid);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_INT64, &record->task);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, NULLSPACE(record->audit_id));
dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, NULLSPACE(record->operation));
dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, NULLSPACE(record->denied_mask));
dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, NULLSPACE(record->requested_mask));
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, &profileIter);
dbus_message_iter_append_fixed_array(&profileIter,
DBUS_TYPE_BYTE,
NULLSPACE(record->profile),
NULLSTRLEN(record->profile));
dbus_message_iter_close_container(&iter, &profileIter);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, &nameIter);
dbus_message_iter_append_fixed_array(&nameIter,
DBUS_TYPE_BYTE,
NULLSPACE(record->name),
NULLSTRLEN(record->name));
dbus_message_iter_close_container(&iter, &nameIter);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, &name2Iter);
dbus_message_iter_append_fixed_array(&name2Iter,
DBUS_TYPE_BYTE,
NULLSPACE(record->name2),
NULLSTRLEN(record->name2));
dbus_message_iter_close_container(&iter, &name2Iter);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, NULLSPACE(record->attribute));
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, &parentIter);
dbus_message_iter_append_fixed_array(&parentIter,
DBUS_TYPE_BYTE,
NULLSPACE(record->parent),
NULLSTRLEN(record->parent));
dbus_message_iter_close_container(&iter, &parentIter);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_INT64, &record->magic_token);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, NULLSPACE(record->info));
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, &activeIter);
dbus_message_iter_append_fixed_array(&activeIter,
DBUS_TYPE_BYTE,
NULLSPACE(record->active_hat),
NULLSTRLEN(record->active_hat));
dbus_message_iter_close_container(&iter, &activeIter);
}
dbus_connection_send(con, message, NULL);
dbus_connection_flush(con);
dbus_message_unref(message);
free_record(record);
if (parsable_line != NULL)
free(parsable_line);
}
}
} while(!signaled);
if (con)
dbus_connection_unref(con);
free(data);
return 0;
}

View File

@@ -0,0 +1 @@
Matt Barringer <mbarringer@suse.de>

View File

@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library General
Public License instead of this License.

View File

@@ -0,0 +1,167 @@
Basic Installation
==================
These are generic installation instructions.
The `configure' shell script attempts to guess correct values for
various system-dependent variables used during compilation. It uses
those values to create a `Makefile' in each directory of the package.
It may also create one or more `.h' files containing system-dependent
definitions. Finally, it creates a shell script `config.status' that
you can run in the future to recreate the current configuration, a file
`config.cache' that saves the results of its tests to speed up
reconfiguring, and a file `config.log' containing compiler output
(useful mainly for debugging `configure').
If you need to do unusual things to compile the package, please try
to figure out how `configure' could check whether to do them, and mail
diffs or instructions to the address given in the `README' so they can
be considered for the next release. If at some point `config.cache'
contains results you don't want to keep, you may remove or edit it.
The file `configure.in' is used to create `configure' by a program
called `autoconf'. You only need `configure.in' if you want to change
it or regenerate `configure' using a newer version of `autoconf'.
The simplest way to compile this package is:
1. `cd' to the directory containing the package's source code and type
`./configure' to configure the package for your system. If you're
using `csh' on an old version of System V, you might need to type
`sh ./configure' instead to prevent `csh' from trying to execute
`configure' itself.
Running `configure' takes a while. While running, it prints some
messages telling which features it is checking for.
2. Type `make' to compile the package.
3. Type `make install' to install the programs and any data files and
documentation.
4. You can remove the program binaries and object files from the
source code directory by typing `make clean'.
Compilers and Options
=====================
Some systems require unusual options for compilation or linking that
the `configure' script does not know about. You can give `configure'
initial values for variables by setting them in the environment. Using
a Bourne-compatible shell, you can do that on the command line like
this:
CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure
Or on systems that have the `env' program, you can do it like this:
env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure
Compiling For Multiple Architectures
====================================
You can compile the package for more than one kind of computer at the
same time, by placing the object files for each architecture in their
own directory. To do this, you must use a version of `make' that
supports the `VPATH' variable, such as GNU `make'. `cd' to the
directory where you want the object files and executables to go and run
the `configure' script. `configure' automatically checks for the
source code in the directory that `configure' is in and in `..'.
If you have to use a `make' that does not supports the `VPATH'
variable, you have to compile the package for one architecture at a time
in the source code directory. After you have installed the package for
one architecture, use `make distclean' before reconfiguring for another
architecture.
Installation Names
==================
By default, `make install' will install the package's files in
`/usr/local/bin', `/usr/local/man', etc. You can specify an
installation prefix other than `/usr/local' by giving `configure' the
option `--prefix=PATH'.
You can specify separate installation prefixes for
architecture-specific files and architecture-independent files. If you
give `configure' the option `--exec-prefix=PATH', the package will use
PATH as the prefix for installing programs and libraries.
Documentation and other data files will still use the regular prefix.
If the package supports it, you can cause programs to be installed
with an extra prefix or suffix on their names by giving `configure' the
option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
Optional Features
=================
Some packages pay attention to `--enable-FEATURE' options to
`configure', where FEATURE indicates an optional part of the package.
They may also pay attention to `--with-PACKAGE' options, where PACKAGE
is something like `gnu-as' or `x' (for the X Window System). The
`README' should mention any `--enable-' and `--with-' options that the
package recognizes.
For packages that use the X Window System, `configure' can usually
find the X include and library files automatically, but if it doesn't,
you can use the `configure' options `--x-includes=DIR' and
`--x-libraries=DIR' to specify their locations.
Specifying the System Type
==========================
There may be some features `configure' can not figure out
automatically, but needs to determine by the type of host the package
will run on. Usually `configure' can figure that out, but if it prints
a message saying it can not guess the host type, give it the
`--host=TYPE' option. TYPE can either be a short name for the system
type, such as `sun4', or a canonical name with three fields:
CPU-COMPANY-SYSTEM
See the file `config.sub' for the possible values of each field. If
`config.sub' isn't included in this package, then this package doesn't
need to know the host type.
If you are building compiler tools for cross-compiling, you can also
use the `--target=TYPE' option to select the type of system they will
produce code for and the `--build=TYPE' option to select the type of
system on which you are compiling the package.
Sharing Defaults
================
If you want to set default values for `configure' scripts to share,
you can create a site shell script called `config.site' that gives
default values for variables like `CC', `cache_file', and `prefix'.
`configure' looks for `PREFIX/share/config.site' if it exists, then
`PREFIX/etc/config.site' if it exists. Or, you can set the
`CONFIG_SITE' environment variable to the location of the site script.
A warning: not all `configure' scripts look for a site script.
Operation Controls
==================
`configure' recognizes the following options to control how it
operates.
`--cache-file=FILE'
Use and save the results of the tests in FILE instead of
`./config.cache'. Set FILE to `/dev/null' to disable caching, for
debugging `configure'.
`--help'
Print a summary of the options to `configure', and exit.
`--quiet'
`--silent'
`-q'
Do not print messages saying which checks are being made.
`--srcdir=DIR'
Look for the package's source code in directory DIR. Usually
`configure' can determine that directory automatically.
`--version'
Print the version of Autoconf used to generate the `configure'
script, and exit.
`configure' also accepts some other, not widely useful, options.

View File

@@ -0,0 +1,2 @@
SUBDIRS = src doc

View File

@@ -0,0 +1,5 @@
default: all
all:
srcdir=`pwd` sh macros/autogen.sh

View File

@@ -0,0 +1,6 @@
The profile editor requires wxWidgets 2.6 or higher. Your distro probably has a
binary package you could install, or you can install from a source distribution
from http://www.wxwidgets.org
This program is released under the GPL, except for all source files under
the src/wxStyledTextCtrl directory. Check there for license details for those files.

View File

@@ -0,0 +1,55 @@
AC_INIT(src/profileeditor.cpp)
AM_INIT_AUTOMAKE(profileeditor, 0.9)
AC_PROG_CXX
AC_PROG_INSTALL
AC_LIBTOOL_DLOPEN
AC_PROG_LIBTOOL
CPPFLAGS="$CPPFLAGS -Wall -g -fexceptions"
CXXFLAGS="$CPPFLAGS -Wall -g -fexceptions"
WXCONFIG=wx-config
AC_ARG_WITH(wx-config,
[[ --with-wx-config=FILE Use the given path to wx-config when determining
wxWidgets configuration; defaults to "wx-config"]],
[
if test "$withval" != "yes" -a "$withval" != ""; then
WXCONFIG=$withval
fi
])
wxversion=0
AC_DEFUN([WXTEST],
[
AC_REQUIRE([AC_PROG_AWK])
AC_MSG_CHECKING([wxWidgets version])
if wxversion=`$WXCONFIG --version`; then
AC_MSG_RESULT([$wxversion])
else
AC_MSG_RESULT([not found])
AC_MSG_ERROR([wxWidgets is required. Try --with-wx-config.])
fi])
# Call WXTEST func
WXTEST
# Verify minimus requires
vers=`echo $wxversion | $AWK 'BEGIN { FS = "."; } { printf "% d", ($1 * 1000 + $2) * 1000 + $3;}'`
if test -n "$vers" && test "$vers" -ge 2006000; then
WX_CPPFLAGS="`$WXCONFIG --cppflags`"
WX_CXXFLAGS="`$WXCONFIG --cxxflags | sed -e 's/-fno-exceptions//'`"
WX_LIBS="`$WXCONFIG --libs`"
else
AC_MSG_ERROR([wxWidgets 2.6.0 or newer is required])
fi
CPPFLAGS="$CPPFLAGS $WX_CPPFLAGS"
CXXFLAGS="$CXXFLAGS $WX_CPPFLAGS"
AC_SUBST(WX_LIBS)
AC_OUTPUT(Makefile src/Makefile src/wxStyledTextCtrl/Makefile doc/Makefile)

View File

@@ -0,0 +1,4 @@
docdir = $(datadir)/doc/@PACKAGE@
doc_DATA = \
en/AppArmorProfileEditor.htb

View File

@@ -0,0 +1,342 @@
# Makefile.in generated by automake 1.9.6 from Makefile.am.
# @configure_input@
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
@SET_MAKE@
srcdir = @srcdir@
top_srcdir = @top_srcdir@
VPATH = @srcdir@
pkgdatadir = $(datadir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
pkgincludedir = $(includedir)/@PACKAGE@
top_builddir = ..
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
INSTALL = @INSTALL@
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = @build@
host_triplet = @host@
subdir = doc
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/configure.in
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_CLEAN_FILES =
SOURCES =
DIST_SOURCES =
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = `echo $$p | sed -e 's|^.*/||'`;
am__installdirs = "$(DESTDIR)$(docdir)"
docDATA_INSTALL = $(INSTALL_DATA)
DATA = $(doc_DATA)
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = @ACLOCAL@
AMDEP_FALSE = @AMDEP_FALSE@
AMDEP_TRUE = @AMDEP_TRUE@
AMTAR = @AMTAR@
AR = @AR@
AUTOCONF = @AUTOCONF@
AUTOHEADER = @AUTOHEADER@
AUTOMAKE = @AUTOMAKE@
AWK = @AWK@
CC = @CC@
CCDEPMODE = @CCDEPMODE@
CFLAGS = @CFLAGS@
CPP = @CPP@
CPPFLAGS = @CPPFLAGS@
CXX = @CXX@
CXXCPP = @CXXCPP@
CXXDEPMODE = @CXXDEPMODE@
CXXFLAGS = @CXXFLAGS@
CYGPATH_W = @CYGPATH_W@
DEFS = @DEFS@
DEPDIR = @DEPDIR@
ECHO = @ECHO@
ECHO_C = @ECHO_C@
ECHO_N = @ECHO_N@
ECHO_T = @ECHO_T@
EGREP = @EGREP@
EXEEXT = @EXEEXT@
F77 = @F77@
FFLAGS = @FFLAGS@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
LDFLAGS = @LDFLAGS@
LIBOBJS = @LIBOBJS@
LIBS = @LIBS@
LIBTOOL = @LIBTOOL@
LN_S = @LN_S@
LTLIBOBJS = @LTLIBOBJS@
MAKEINFO = @MAKEINFO@
OBJEXT = @OBJEXT@
PACKAGE = @PACKAGE@
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
PACKAGE_NAME = @PACKAGE_NAME@
PACKAGE_STRING = @PACKAGE_STRING@
PACKAGE_TARNAME = @PACKAGE_TARNAME@
PACKAGE_VERSION = @PACKAGE_VERSION@
PATH_SEPARATOR = @PATH_SEPARATOR@
RANLIB = @RANLIB@
SET_MAKE = @SET_MAKE@
SHELL = @SHELL@
STRIP = @STRIP@
VERSION = @VERSION@
WX_LIBS = @WX_LIBS@
ac_ct_AR = @ac_ct_AR@
ac_ct_CC = @ac_ct_CC@
ac_ct_CXX = @ac_ct_CXX@
ac_ct_F77 = @ac_ct_F77@
ac_ct_RANLIB = @ac_ct_RANLIB@
ac_ct_STRIP = @ac_ct_STRIP@
am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
am__include = @am__include@
am__leading_dot = @am__leading_dot@
am__quote = @am__quote@
am__tar = @am__tar@
am__untar = @am__untar@
bindir = @bindir@
build = @build@
build_alias = @build_alias@
build_cpu = @build_cpu@
build_os = @build_os@
build_vendor = @build_vendor@
datadir = @datadir@
exec_prefix = @exec_prefix@
host = @host@
host_alias = @host_alias@
host_cpu = @host_cpu@
host_os = @host_os@
host_vendor = @host_vendor@
includedir = @includedir@
infodir = @infodir@
install_sh = @install_sh@
libdir = @libdir@
libexecdir = @libexecdir@
localstatedir = @localstatedir@
mandir = @mandir@
mkdir_p = @mkdir_p@
oldincludedir = @oldincludedir@
prefix = @prefix@
program_transform_name = @program_transform_name@
sbindir = @sbindir@
sharedstatedir = @sharedstatedir@
sysconfdir = @sysconfdir@
target_alias = @target_alias@
docdir = $(datadir)/doc/@PACKAGE@
doc_DATA = \
en/AppArmorProfileEditor.htb
all: all-am
.SUFFIXES:
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
&& exit 0; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/Makefile'; \
cd $(top_srcdir) && \
$(AUTOMAKE) --gnu doc/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
distclean-libtool:
-rm -f libtool
uninstall-info-am:
install-docDATA: $(doc_DATA)
@$(NORMAL_INSTALL)
test -z "$(docdir)" || $(mkdir_p) "$(DESTDIR)$(docdir)"
@list='$(doc_DATA)'; for p in $$list; do \
if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
f=$(am__strip_dir) \
echo " $(docDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(docdir)/$$f'"; \
$(docDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(docdir)/$$f"; \
done
uninstall-docDATA:
@$(NORMAL_UNINSTALL)
@list='$(doc_DATA)'; for p in $$list; do \
f=$(am__strip_dir) \
echo " rm -f '$(DESTDIR)$(docdir)/$$f'"; \
rm -f "$(DESTDIR)$(docdir)/$$f"; \
done
tags: TAGS
TAGS:
ctags: CTAGS
CTAGS:
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
list='$(DISTFILES)'; for file in $$list; do \
case $$file in \
$(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
$(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
esac; \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
if test "$$dir" != "$$file" && test "$$dir" != "."; then \
dir="/$$dir"; \
$(mkdir_p) "$(distdir)$$dir"; \
else \
dir=''; \
fi; \
if test -d $$d/$$file; then \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
fi; \
cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
else \
test -f $(distdir)/$$file \
|| cp -p $$d/$$file $(distdir)/$$file \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(DATA)
installdirs:
for dir in "$(DESTDIR)$(docdir)"; do \
test -z "$$dir" || $(mkdir_p) "$$dir"; \
done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-libtool
dvi: dvi-am
dvi-am:
html: html-am
info: info-am
info-am:
install-data-am: install-docDATA
install-exec-am:
install-info: install-info-am
install-man:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-docDATA uninstall-info-am
.PHONY: all all-am check check-am clean clean-generic clean-libtool \
distclean distclean-generic distclean-libtool distdir dvi \
dvi-am html html-am info info-am install install-am \
install-data install-data-am install-docDATA install-exec \
install-exec-am install-info install-info-am install-man \
install-strip installcheck installcheck-am installdirs \
maintainer-clean maintainer-clean-generic mostlyclean \
mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
uninstall uninstall-am uninstall-docDATA uninstall-info-am
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:

View File

@@ -0,0 +1,2 @@
KDE_DOCS = profileeditor
KDE_LANG = en

View File

@@ -0,0 +1,6 @@
#!/bin/sh
aclocal
libtoolize --automake --force --copy
automake -a -c
autoconf

View File

@@ -0,0 +1,44 @@
# norootforbuild
Name: apparmor-profile-editor
BuildRequires: wxGTK-devel gcc-c++
Version: 0.9
Release: 1
Vendor: Novell
Copyright: GPL
Summary: AppArmor profile editor
Group: Application/Editors
Packager: mbarringer@suse.de
BuildRoot: %{_tmppath}/%{name}-root
Source: apparmor-profile-editor-0.9.tar.gz
%description
AppArmor profile editor
%prep
%setup -q -n %{name}-%{version}
%build
autoreconf --force --install
export CFLAGS="$RPM_OPT_FLAGS -DSCI_LEXER -DLINK_LEXERS -fPIC -DPIC -DWX_PRECOMP -DNO_GCC_PRAGMA -D__WX"
export CXXFLAGS="$RPM_OPT_FLAGS -DSCI_LEXER -DLINK_LEXERS -fPIC -DPIC -DWX_PRECOMP -DNO_GCC_PRAGMA -D__WX"
%{?suse_update_config:%{suse_update_config -f}}
./configure --prefix=%{_prefix} --disable-debug --enable-debug=no
make
%install
strip $RPM_BUILD_ROOT%{_prefix}/bin/* || :
rm -rf %{buildroot}
%makeinstall
%clean
rm -rf %{buildroot}
%post -p /sbin/ldconfig
%postun -p /sbin/ldconfig
%files
%defattr(-, root, root)
%{_prefix}/bin/profileeditor
%{_prefix}/share/doc/profileeditor/AppArmorProfileEditor.htb
%dir %{_prefix}/share/doc/profileeditor
%doc AUTHORS COPYING ChangeLog NEWS README TODO
%changelog

View File

@@ -0,0 +1,114 @@
/* AppArmor Profile Editor (C) 2006 Novell, Inc.
*
* 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.
*
*/
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/wfstream.h>
#include "AboutDialog.h"
#include "opensuse_logo.xpm"
IMPLEMENT_DYNAMIC_CLASS(AboutDialog, wxDialog)
BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
END_EVENT_TABLE()
AboutDialog::AboutDialog()
{
}
AboutDialog::AboutDialog(wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style)
{
Create(parent, id, caption, pos, size, style);
}
bool AboutDialog::Create(wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style)
{
mpLogoBitmap = NULL;
mpVersionStaticText = NULL;
mpCopyrightStaticText = NULL;
mpOkButtonSizer = NULL;
mpOkButton = NULL;
SetExtraStyle(GetExtraStyle() | wxWS_EX_BLOCK_EVENTS);
wxDialog::Create(parent, id, caption, pos, size, style);
CreateControls();
GetSizer()->Fit(this);
GetSizer()->SetSizeHints(this);
Centre();
return true;
}
void AboutDialog::CreateControls()
{
SetBackgroundColour(wxColour(255, 255, 255));
wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
SetSizer(mainSizer);
wxBitmap mpLogoBitmapBitmap(opensuse_logo_xpm);
mpLogoBitmap = new wxStaticBitmap(this,
wxID_ANY,
mpLogoBitmapBitmap,
wxDefaultPosition,
wxSize(223, 137),
0);
mainSizer->Add(mpLogoBitmap, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
mpVersionStaticText = new wxStaticText(this,
wxID_ANY,
VERSION_STRING,
wxDefaultPosition,
wxDefaultSize,
0);
mainSizer->Add(mpVersionStaticText, 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxADJUST_MINSIZE, 5);
mpCopyrightStaticText = new wxStaticText(this,
wxID_ANY,
_("(C) 2006 Novell, Inc\n"),
wxDefaultPosition,
wxDefaultSize,
0);
mainSizer->Add(mpCopyrightStaticText, 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxADJUST_MINSIZE, 5);
mpLicenseTextCtrl = new wxTextCtrl(this,
wxID_ANY,
_T(""),
wxDefaultPosition,
wxSize(400, -1),
wxTE_MULTILINE|wxTE_READONLY);
mpLicenseTextCtrl->SetValue(GPL_STRING);
mainSizer->Add(mpLicenseTextCtrl, 0, wxGROW|wxALL, 5);
mpOkButtonSizer = new wxStdDialogButtonSizer;
mainSizer->Add(mpOkButtonSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
mpOkButton = new wxButton(this,
wxID_OK,
_("&OK"),
wxDefaultPosition,
wxDefaultSize,
0);
mpOkButtonSizer->AddButton(mpOkButton);
mpOkButtonSizer->Realize();
}

View File

@@ -0,0 +1,56 @@
#ifndef _ABOUTDIALOG_H_
#define _ABOUTDIALOG_H_
#define VERSION_STRING _("AppArmor Profile Editor version 0.9")
#define GPL_STRING _(" \
Portions of this software (C) 1998-2003 by Neil Hodgson <neilh@scintilla.org>\n\n \
This rest of 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. \
\n\n \
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. \
\n\n \
You should have received a copy of the GNU General Public License \
along with this program; if not, write to the Free Software \
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \
")
/**
* The "About" dialog
*/
class AboutDialog: public wxDialog
{
DECLARE_DYNAMIC_CLASS(AboutDialog)
DECLARE_EVENT_TABLE()
public:
AboutDialog();
AboutDialog(wxWindow* parent,
wxWindowID id = wxID_ANY,
const wxString& caption = _T("About"),
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400, 300),
long style = wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX);
bool Create(wxWindow* parent,
wxWindowID id = wxID_ANY,
const wxString& caption = _T("About"),
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400, 300),
long style = wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX);
void CreateControls();
private:
wxStaticBitmap* mpLogoBitmap;
wxStaticText* mpVersionStaticText;
wxStaticText* mpCopyrightStaticText;
wxStdDialogButtonSizer* mpOkButtonSizer;
wxTextCtrl* mpLicenseTextCtrl;
wxButton* mpOkButton;
};
#endif
// _ABOUTDIALOG_H_

View File

@@ -0,0 +1,185 @@
/* AppArmor Profile Editor (C) 2006 Novell, Inc.
*
* 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.
*
*/
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/config.h>
#include "Configuration.h"
// Initialize all of the static variables
wxString Configuration::mProfileDirectory = wxEmptyString;
wxString Configuration::mProfileEditorExecutable = wxEmptyString;
wxString Configuration::mParserCommand = wxEmptyString;
wxString Configuration::mTemplateText = wxEmptyString;
wxColour Configuration::mCommentColour = wxColour(DEFAULT_COMMENT_COLOUR);
wxColour Configuration::mIncludeColour = wxColour(DEFAULT_INCLUDE_COLOUR);
wxColour Configuration::mCapColour = wxColour(DEFAULT_CAP_COLOUR);
wxColour Configuration::mPathColour = wxColour(DEFAULT_PATH_COLOUR);
wxColour Configuration::mPermColour = wxColour(DEFAULT_PERM_COLOUR);
wxFont Configuration::mCapabilityFont(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
wxFont Configuration::mCommentFont(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_ITALIC, wxFONTWEIGHT_NORMAL);
wxFont Configuration::mIncludeFont(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
wxFont Configuration::mPathFont(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD);
wxFont Configuration::mPermsFont(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL);
int Configuration::mWindowX;
int Configuration::mWindowY;
int Configuration::mWindowHeight;
int Configuration::mWindowWidth;
/**
* Reads in the initial variables
*/
void Configuration::Initialize()
{
// Read in all of the values
mProfileEditorExecutable = wxTheApp->argv[0];
mWindowX = wxConfig::Get()->Read(_("WindowX"), 50);
mWindowY = wxConfig::Get()->Read(_("WindowY"), 50);
mWindowWidth = wxConfig::Get()->Read(_("WindowWidth"), 800);
mWindowHeight = wxConfig::Get()->Read(_("WindowHeight"), 600);
mProfileDirectory = wxConfig::Get()->Read(_("ProfileDirectory"), Configuration::BestGuessProfileDirectory());
mParserCommand = wxConfig::Get()->Read(_("Parser"), BestGuessParserCommand());
mTemplateText = wxConfig::Get()->Read(_("ProfileTemplate"), wxEmptyString);
mCommentColour = _ReadColour(_("CommentColour"), mCommentColour);
mIncludeColour = _ReadColour(_("IncludeColour"), mIncludeColour);
mCapColour = _ReadColour(_("CapabilityColour"), mCapColour);
mPathColour = _ReadColour(_("PathColour"), mPathColour);
mPermColour = _ReadColour(_("PermissionColour"), mPermColour);
_ReadFont(_("CommentFont"), mCommentFont);
_ReadFont(_("IncludeFont"), mIncludeFont);
_ReadFont(_("CapabilityFont"), mCapabilityFont);
_ReadFont(_("PathFont"), mPathFont);
_ReadFont(_("PermsFont"), mPermsFont);
}
/**
* Profiles are most likely stored in either /etc/subdomain.d or
* /etc/apparmor.d. Stat each to see which.
* @param void
* @return profile directory
*/
wxString Configuration::BestGuessProfileDirectory(void)
{
if (wxDirExists(_("/etc/apparmor.d")))
return (_("/etc/apparmor.d"));
else if (wxDirExists(_("/etc/subdomain.d")))
return (_("/etc/subdomain.d"));
else
return (_("/"));
}
/**
* The parser is probably apparmor_parser or
* subdomain_parser. If it's neither, the user
* will need to set it manually, so return /bin/false
* @return the path to the parser
*/
wxString Configuration::BestGuessParserCommand()
{
if (wxFileExists(_("/sbin/apparmor_parser")))
return _("/sbin/apparmor_parser");
else if (wxFileExists(_("/sbin/subdomain_parser")))
return _("/sbin/subdomain_parser");
else
return _("/bin/false");
}
/**
* Writes all of the values to disk
* @return only true for now
*/
bool Configuration::CommitChanges()
{
wxConfig::Get()->Write(_("ProfileDirectory"), mProfileDirectory);
wxConfig::Get()->Write(_("Parser"), mParserCommand);
wxConfig::Get()->Write(_("ProfileTemplate"), mTemplateText);
_WriteColour(_("CommentColour"), mCommentColour);
_WriteColour(_("IncludeColour"), mIncludeColour);
_WriteColour(_("CapabilityColour"), mCapColour);
_WriteColour(_("PathColour"), mPathColour);
_WriteColour(_("PermissionColour"), mPermColour);
wxConfig::Get()->Write(_("CommentFont"), mCommentFont.GetNativeFontInfoDesc());
wxConfig::Get()->Write(_("IncludeFont"), mIncludeFont.GetNativeFontInfoDesc());
wxConfig::Get()->Write(_("CapabilityFont"), mCapabilityFont.GetNativeFontInfoDesc());
wxConfig::Get()->Write(_("PathFont"), mPathFont.GetNativeFontInfoDesc());
wxConfig::Get()->Write(_("PermsFont"), mPermsFont.GetNativeFontInfoDesc());
wxConfig::Get()->Flush();
return true;
}
/**
* Writes the given window settings to the configuration file.
* This is kept separately from CommitChanges() because:
* a) There's no reason to re-write all configuration changes on exit and
* b) There's no reason to update the window position and size on every OnSize() event
*/
void Configuration::WriteWindowSettings(const wxPoint &pos, const wxSize& size)
{
wxConfig::Get()->Write(_("WindowX"), pos.x);
wxConfig::Get()->Write(_("WindowY"), pos.y);
wxConfig::Get()->Write(_("WindowWidth"), size.GetWidth());
wxConfig::Get()->Write(_("WindowHeight"), size.GetHeight());
wxConfig::Get()->Flush();
}
/**
* Reads a colour setting from the config file and translates it into
* a wxColour. If it can't convert the stored value, or the stored value
* does not exist, it will return whatever is passed as defaultColour.
* @param key the configuration key
* @param defaultColour a colour to return
* @return a colour
*/
wxColour Configuration::_ReadColour(const wxString& key, const wxColour& defaultColour)
{
wxColour ret;
wxString tmpStr = wxConfig::Get()->Read(key, wxEmptyString);
if (tmpStr.Length() == 6)
{
ret.Set(wxHexToDec(tmpStr.Mid(0,2)), // Red
wxHexToDec(tmpStr.Mid(2,2)), // Green
wxHexToDec(tmpStr.Mid(4,2)) // Blue
);
}
if (ret.Ok())
return ret;
else
return defaultColour;
}
/**
* Reads a font from the configuration file, and sets it as the 'font'
* @param key configuration key
* @param font the font to set
*/
void Configuration::_ReadFont(const wxString& key, wxFont& font)
{
wxString tmpStr;
if (wxConfig::Get()->Read(key, &tmpStr))
font.SetNativeFontInfo(tmpStr);
}
/**
* Takes a wxColour and converts it to a hex string for writing to disk.
* @param key configuration key
* @param colour the colour to convert
*/
void Configuration::_WriteColour(const wxString& key, const wxColour& colour)
{
wxConfig::Get()->Write(key, wxString::Format(_T("%02x%02x%02x"),
colour.Red(),
colour.Green(),
colour.Blue()));
}

View File

@@ -0,0 +1,84 @@
#ifndef CONFIGURATION_H
#define CONFIGURATION_H
#define DEFAULT_COMMENT_COLOUR 31, 31, 210
#define DEFAULT_INCLUDE_COLOUR 56, 136, 31
#define DEFAULT_CAP_COLOUR 229, 33, 204
#define DEFAULT_PATH_COLOUR 1, 1, 1
#define DEFAULT_PERM_COLOUR 160, 32, 240
class wxConfig;
/**
* The configuration details class
*/
class Configuration
{
public:
static void Initialize();
static wxString BestGuessProfileDirectory();
static wxString BestGuessParserCommand();
static bool CommitChanges();
static wxString GetProfileDirectory() { return mProfileDirectory; }
static wxString GetEditorExecutable() { return mProfileEditorExecutable; }
static wxString GetTemplateText() { return mTemplateText; }
static wxString GetParserCommand() { return mParserCommand; }
static wxColour GetCommentColour() { return mCommentColour; }
static wxColour GetIncludeColour() { return mIncludeColour; }
static wxColour GetCapColour() { return mCapColour; }
static wxColour GetPathColour() { return mPathColour; }
static wxColour GetPermColour() { return mPermColour; }
static wxFont GetCapabilityFont() { return mCapabilityFont; }
static wxFont GetCommentFont() { return mCommentFont; }
static wxFont GetIncludeFont() { return mIncludeFont; }
static wxFont GetPathFont() { return mPathFont; }
static wxFont GetPermFont() { return mPermsFont; }
static wxSize GetWindowSize() { return wxSize(mWindowWidth, mWindowHeight); }
static wxPoint GetWindowPos() { return wxPoint(mWindowX, mWindowY); }
static void WriteWindowSettings(const wxPoint &pos, const wxSize& size);
static void SetProfileDirectory(const wxString& profileDirectory)
{ mProfileDirectory = profileDirectory; }
static void SetEditorExecutable(const wxString& executable) { mProfileEditorExecutable = executable; }
static void SetParserCommand(const wxString& parserCommand) { mParserCommand = parserCommand; }
static void SetTemplateText(const wxString& templateText) { mTemplateText = templateText; }
static void SetCommentColour(const wxColour& commentColour) { mCommentColour = commentColour; }
static void SetIncludeColour(const wxColour& includeColour) { mIncludeColour = includeColour; }
static void SetCapColour(const wxColour& capColour) { mCapColour = capColour; }
static void SetPathColour(const wxColour& pathColour) { mPathColour = pathColour; }
static void SetPermColour(const wxColour& permColour) { mPermColour = permColour; }
static void SetCapabilityFont(const wxFont& capabilityFont) { mCapabilityFont = capabilityFont; }
static void SetCommentFont(const wxFont& commentFont) { mCommentFont = commentFont; }
static void SetIncludeFont(const wxFont& includeFont) { mIncludeFont = includeFont; }
static void SetPathFont(const wxFont& pathFont) { mPathFont = pathFont; }
static void SetPermFont(const wxFont& permsFont) { mPermsFont = permsFont; }
private:
static void _WriteColour(const wxString& key, const wxColour& colour);
static wxColour _ReadColour(const wxString& key, const wxColour& defaultColour);
static void _ReadFont(const wxString& key, wxFont& font);
static wxString mProfileDirectory;
static wxString mProfileEditorExecutable;
static wxString mParserCommand;
static wxString mTemplateText;
static wxColour mCommentColour;
static wxColour mIncludeColour;
static wxColour mCapColour;
static wxColour mPathColour;
static wxColour mPermColour;
static wxFont mCapabilityFont;
static wxFont mCommentFont;
static wxFont mIncludeFont;
static wxFont mPathFont;
static wxFont mPermsFont;
static int mWindowX; // These are just the settings from the
static int mWindowY; // config file, they are *NOT* updated
static int mWindowWidth; // in any size events
static int mWindowHeight;
};
#endif

View File

@@ -0,0 +1,24 @@
# these are the headers for your project
noinst_HEADERS = ProfileDirectoryTraverser.h ProfileTextCtrl.h Preferences.h \
AboutDialog.h opensuse_logo.xpm SearchAllProfiles.h Configuration.h
#########################################################################
# APPLICATION SECTION
#########################################################################
# this is the program that gets installed. it's name is used for all
# of the other Makefile.am variables
bin_PROGRAMS = profileeditor
# the application source, library search path, and link libraries
profileeditor_SOURCES = ProfileTextCtrl.cpp Preferences.cpp AboutDialog.cpp \
SearchAllProfiles.cpp Configuration.cpp profileeditor.cpp
profileeditor_LDFLAGS = $(WX_LIBS)
SUBDIRS = wxStyledTextCtrl
profileeditor_LDADD =\
$(top_builddir)/src/wxStyledTextCtrl/libAppArmorStyledTextCtrl.a
AM_CXXFLAGS = \
-DHELP_FILE_LOCATION=\"$(datadir)/doc/@PACKAGE@/AppArmorProfileEditor.htb\"

View File

@@ -0,0 +1,322 @@
/* AppArmor Profile Editor (C) 2006 Novell, Inc.
*
* 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.
*
*/
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/propdlg.h>
#include <wx/config.h>
#include <wx/colordlg.h>
#include <wx/fontdlg.h>
#include "Configuration.h"
#include "ProfileTextCtrl.h"
#include "Preferences.h"
IMPLEMENT_DYNAMIC_CLASS(PreferencesDialog, wxDialog)
BEGIN_EVENT_TABLE(PreferencesDialog, wxDialog)
EVT_BUTTON(ID_COMMENT_COLOUR_BUTTON, PreferencesDialog::OnColourButton)
EVT_BUTTON(ID_INCLUDES_COLOUR_BUTTON, PreferencesDialog::OnColourButton)
EVT_BUTTON(ID_PERMS_COLOUR_BUTTON, PreferencesDialog::OnColourButton)
EVT_BUTTON(ID_CAPABILITIES_COLOUR_BUTTON, PreferencesDialog::OnColourButton)
EVT_BUTTON(ID_PATHS_COLOUR_BUTTON, PreferencesDialog::OnColourButton)
EVT_BUTTON(ID_COMMENT_FONT_BUTTON, PreferencesDialog::OnFontButton)
EVT_BUTTON(ID_INCLUDES_FONT_BUTTON, PreferencesDialog::OnFontButton)
EVT_BUTTON(ID_CAPABILITIES_FONT_BUTTON, PreferencesDialog::OnFontButton)
EVT_BUTTON(ID_PATHS_FONT_BUTTON, PreferencesDialog::OnFontButton)
EVT_BUTTON(ID_PERMS_FONT_BUTTON, PreferencesDialog::OnFontButton)
END_EVENT_TABLE()
PreferencesDialog::PreferencesDialog( )
{
}
PreferencesDialog::PreferencesDialog(wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style)
{
Create(parent, id, caption, pos, size, style);
}
bool PreferencesDialog::Create(wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style)
{
mpPrefsNotebook = NULL;
mpProfileDir = NULL;
mpParserCommand = NULL;
mpTemplateTextCtrl = NULL;
mpCommentsButton = NULL;
mpIncludesButton = NULL;
mpPermsButton = NULL;
mpCapabilitiesButton = NULL;
mpPathsButton = NULL;
mpCommentsFontButton = NULL;
mpIncludesFontButton = NULL;
mpCapabilitiesFontButton = NULL;
mpPathsFontButton = NULL;
SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS);
wxDialog::Create( parent, id, caption, pos, size, style );
CreateControls();
GetSizer()->Fit(this);
GetSizer()->SetSizeHints(this);
Centre();
return true;
}
void PreferencesDialog::CreateControls()
{
wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
SetSizer(mainSizer);
mpPrefsNotebook = new wxNotebook(this, ID_PREFERENCES_NOTEBOOK, wxDefaultPosition, wxDefaultSize, wxNB_TOP );
// The paths pane
wxPanel* pathsPanel = new wxPanel( mpPrefsNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL );
wxGridSizer* prefsGridSizer = new wxGridSizer(2, 2, 0, 0);
pathsPanel->SetSizer(prefsGridSizer);
wxStaticText* profileDirectoryText = new wxStaticText( pathsPanel, wxID_ANY, _("Profile Directory:"), wxDefaultPosition, wxDefaultSize, 0 );
prefsGridSizer->Add(profileDirectoryText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpProfileDir = new wxTextCtrl( pathsPanel, wxID_ANY, Configuration::GetProfileDirectory(), wxDefaultPosition, wxSize(200, -1), 0 );
prefsGridSizer->Add(mpProfileDir, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* parserCommandText = new wxStaticText( pathsPanel, wxID_ANY, _("Path to apparmor_parser:"), wxDefaultPosition, wxDefaultSize, 0 );
prefsGridSizer->Add(parserCommandText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpParserCommand = new wxTextCtrl( pathsPanel, wxID_ANY, Configuration::GetParserCommand(), wxDefaultPosition, wxSize(200, -1), 0 );
prefsGridSizer->Add(mpParserCommand, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
mpPrefsNotebook->AddPage(pathsPanel, _("Paths"));
// The colours pane //
wxPanel* coloursPanel = new wxPanel( mpPrefsNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL );
wxBoxSizer* colorFontBoxSizer = new wxBoxSizer(wxHORIZONTAL);
coloursPanel->SetSizer(colorFontBoxSizer);
wxStaticBox* colourBoxSizer = new wxStaticBox(coloursPanel, wxID_ANY, _("Colours"));
wxStaticBoxSizer* colourStaticBoxSizer = new wxStaticBoxSizer(colourBoxSizer, wxVERTICAL);
colorFontBoxSizer->Add(colourStaticBoxSizer, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxGridSizer* colourSubSizer = new wxGridSizer(4, 2, 0, 0);
colourStaticBoxSizer->Add(colourSubSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxStaticText* commentsText = new wxStaticText( coloursPanel, wxID_STATIC, _("Comments"), wxDefaultPosition, wxDefaultSize, 0 );
colourSubSizer->Add(commentsText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpCommentsButton = new wxButton( coloursPanel, ID_COMMENT_COLOUR_BUTTON, _T(""), wxDefaultPosition, wxDefaultSize, 0 );
mpCommentsButton->SetBackgroundColour(Configuration::GetCommentColour());
colourSubSizer->Add(mpCommentsButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* includesText = new wxStaticText( coloursPanel, wxID_STATIC, _("Includes"), wxDefaultPosition, wxDefaultSize, 0 );
colourSubSizer->Add(includesText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpIncludesButton = new wxButton( coloursPanel, ID_INCLUDES_COLOUR_BUTTON, _T(""), wxDefaultPosition, wxDefaultSize, 0 );
colourSubSizer->Add(mpIncludesButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
mpIncludesButton->SetBackgroundColour(Configuration::GetIncludeColour());
wxStaticText* capabilitiesText = new wxStaticText( coloursPanel, wxID_STATIC, _("Capabilities"), wxDefaultPosition, wxDefaultSize, 0 );
colourSubSizer->Add(capabilitiesText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpCapabilitiesButton = new wxButton( coloursPanel, ID_CAPABILITIES_COLOUR_BUTTON, _T(""), wxDefaultPosition, wxDefaultSize, 0 );
colourSubSizer->Add(mpCapabilitiesButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
mpCapabilitiesButton->SetBackgroundColour(Configuration::GetCapColour());
wxStaticText* pathsText = new wxStaticText( coloursPanel, wxID_STATIC, _("Paths"), wxDefaultPosition, wxDefaultSize, 0 );
colourSubSizer->Add(pathsText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpPathsButton = new wxButton( coloursPanel, ID_PATHS_COLOUR_BUTTON, _T(""), wxDefaultPosition, wxDefaultSize, 0 );
mpPathsButton->SetBackgroundColour(Configuration::GetPathColour());
colourSubSizer->Add(mpPathsButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* permsText = new wxStaticText( coloursPanel, wxID_STATIC, _("Permissions"), wxDefaultPosition, wxDefaultSize, 0 );
colourSubSizer->Add(permsText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpPermsButton = new wxButton( coloursPanel, ID_PERMS_COLOUR_BUTTON, _T(""), wxDefaultPosition, wxDefaultSize, 0 );
mpPermsButton->SetBackgroundColour(Configuration::GetPermColour());
colourSubSizer->Add(mpPermsButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
// Fonts pane //
wxStaticBox* fontSubSizer = new wxStaticBox(coloursPanel, wxID_ANY, _("Fonts"));
wxStaticBoxSizer* fontBoxSizer = new wxStaticBoxSizer(fontSubSizer, wxVERTICAL);
colorFontBoxSizer->Add(fontBoxSizer, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxGridSizer* fontsGridSizer = new wxGridSizer(4, 2, 0, 0);
fontBoxSizer->Add(fontsGridSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxStaticText* commentFontText = new wxStaticText( coloursPanel, wxID_STATIC, _("Comments"), wxDefaultPosition, wxDefaultSize, 0 );
fontsGridSizer->Add(commentFontText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpCommentsFontButton = new wxButton( coloursPanel, ID_COMMENT_FONT_BUTTON, _("ABCdef"), wxDefaultPosition, wxDefaultSize, 0 );
mpCommentsFontButton->SetFont(Configuration::GetCommentFont());
fontsGridSizer->Add(mpCommentsFontButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* includesFontText = new wxStaticText( coloursPanel, wxID_STATIC, _("Includes"), wxDefaultPosition, wxDefaultSize, 0 );
fontsGridSizer->Add(includesFontText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpIncludesFontButton = new wxButton( coloursPanel, ID_INCLUDES_FONT_BUTTON, _("ABCdef"), wxDefaultPosition, wxDefaultSize, 0 );
mpIncludesFontButton->SetFont(Configuration::GetIncludeFont());
fontsGridSizer->Add(mpIncludesFontButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* capabilitiesFontText = new wxStaticText( coloursPanel, wxID_STATIC, _("Capabilities"), wxDefaultPosition, wxDefaultSize, 0 );
fontsGridSizer->Add(capabilitiesFontText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpCapabilitiesFontButton = new wxButton( coloursPanel, ID_CAPABILITIES_FONT_BUTTON, _("ABCdef"), wxDefaultPosition, wxDefaultSize, 0 );
mpCapabilitiesFontButton->SetFont(Configuration::GetCapabilityFont());
fontsGridSizer->Add(mpCapabilitiesFontButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* pathsFontText = new wxStaticText( coloursPanel, wxID_STATIC, _("Paths"), wxDefaultPosition, wxDefaultSize, 0 );
fontsGridSizer->Add(pathsFontText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpPathsFontButton = new wxButton( coloursPanel, ID_PATHS_FONT_BUTTON, _("ABCdef"), wxDefaultPosition, wxDefaultSize, 0 );
mpPathsFontButton->SetFont(Configuration::GetPathFont());
fontsGridSizer->Add(mpPathsFontButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* permsFontText = new wxStaticText( coloursPanel, wxID_STATIC, _("Permissions"), wxDefaultPosition, wxDefaultSize, 0 );
fontsGridSizer->Add(permsFontText, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpPermsFontButton = new wxButton( coloursPanel, ID_PERMS_FONT_BUTTON, _("ABCdef"), wxDefaultPosition, wxDefaultSize, 0 );
mpPermsFontButton->SetFont(Configuration::GetPermFont());
fontsGridSizer->Add(mpPermsFontButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
mpPrefsNotebook->AddPage(coloursPanel, _("Colours & Fonts"));
// Templates pane //
mpTemplateTextCtrl = new ProfileTextCtrl (mpPrefsNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize);
mpTemplateTextCtrl->SetText(Configuration::GetTemplateText());
mpPrefsNotebook->AddPage(mpTemplateTextCtrl, _("New Profile Template"));
mainSizer->Add(mpPrefsNotebook, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxBoxSizer* buttonBoxSizer = new wxBoxSizer(wxHORIZONTAL);
mainSizer->Add(buttonBoxSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxStdDialogButtonSizer* buttonSizer = new wxStdDialogButtonSizer;
buttonBoxSizer->Add(buttonSizer, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxButton* okButton = new wxButton( this, wxID_OK, _("&OK"), wxDefaultPosition, wxDefaultSize, 0 );
buttonSizer->AddButton(okButton);
wxButton* cancelButton = new wxButton( this, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
buttonSizer->AddButton(cancelButton);
buttonSizer->Realize();
}
void PreferencesDialog::OnColourButton(wxCommandEvent &event)
{
wxColourData currentData;
switch (event.GetId())
{
case ID_COMMENT_COLOUR_BUTTON:
currentData.SetColour(mpCommentsButton->GetBackgroundColour());
break;
case ID_INCLUDES_COLOUR_BUTTON:
currentData.SetColour(mpIncludesButton->GetBackgroundColour());
break;
case ID_CAPABILITIES_COLOUR_BUTTON:
currentData.SetColour(mpCapabilitiesButton->GetBackgroundColour());
break;
case ID_PATHS_COLOUR_BUTTON:
currentData.SetColour(mpPathsButton->GetBackgroundColour());
break;
case ID_PERMS_COLOUR_BUTTON:
currentData.SetColour(mpPermsButton->GetBackgroundColour());
break;
default:
currentData.SetColour(*wxWHITE);
break;
}
wxColourDialog *colourPicker = new wxColourDialog(this, &currentData);
if (colourPicker->ShowModal() == wxID_OK)
{
currentData = colourPicker->GetColourData();
wxColour currentColour = currentData.GetColour();
switch (event.GetId())
{
case ID_COMMENT_COLOUR_BUTTON:
mpCommentsButton->SetBackgroundColour(currentColour);
break;
case ID_INCLUDES_COLOUR_BUTTON:
mpIncludesButton->SetBackgroundColour(currentColour);
break;
case ID_CAPABILITIES_COLOUR_BUTTON:
mpCapabilitiesButton->SetBackgroundColour(currentColour);
break;
case ID_PATHS_COLOUR_BUTTON:
mpPathsButton->SetBackgroundColour(currentColour);
break;
case ID_PERMS_COLOUR_BUTTON:
mpPermsButton->SetBackgroundColour(currentColour);
break;
default:
break;
}
}
colourPicker->Destroy();
}
void PreferencesDialog::OnFontButton(wxCommandEvent &event)
{
wxFontData fontData;
switch (event.GetId())
{
case ID_COMMENT_FONT_BUTTON:
fontData.SetInitialFont(mpCommentsFontButton->GetFont());
break;
case ID_INCLUDES_FONT_BUTTON:
fontData.SetInitialFont(mpIncludesFontButton->GetFont());
break;
case ID_CAPABILITIES_FONT_BUTTON:
fontData.SetInitialFont(mpCapabilitiesFontButton->GetFont());
break;
case ID_PATHS_FONT_BUTTON:
fontData.SetInitialFont(mpPathsFontButton->GetFont());
break;
case ID_PERMS_FONT_BUTTON:
fontData.SetInitialFont(mpPermsFontButton->GetFont());
break;
default:
break;
}
wxFontDialog *fontDialog = new wxFontDialog(this, fontData);
if (fontDialog->ShowModal() == wxID_OK)
{
fontData = fontDialog->GetFontData();
wxFont newFont = fontData.GetChosenFont();
// Write it back to disk
switch (event.GetId())
{
case ID_COMMENT_FONT_BUTTON:
mpCommentsFontButton->SetFont(newFont);
break;
case ID_INCLUDES_FONT_BUTTON:
mpIncludesFontButton->SetFont(newFont);
break;
case ID_CAPABILITIES_FONT_BUTTON:
mpCapabilitiesFontButton->SetFont(newFont);
break;
case ID_PATHS_FONT_BUTTON:
mpPathsFontButton->SetFont(newFont);
break;
case ID_PERMS_FONT_BUTTON:
mpPermsFontButton->SetFont(newFont);
break;
default:
break;
}
}
fontDialog->Destroy();
}

View File

@@ -0,0 +1,102 @@
#ifndef PREFERENCES_H
#define PREFERENCES_H
#include <wx/notebook.h>
#define CONFIG_NAME "AppArmorProfileEditor"
#define DEFAULT_COMMENT_COLOUR_R 31
#define DEFAULT_COMMENT_COLOUR_G 31
#define DEFAULT_COMMENT_COLOUR_B 210
#define DEFAULT_INCLUDE_COLOUR_R 56
#define DEFAULT_INCLUDE_COLOUR_G 136
#define DEFAULT_INCLUDE_COLOUR_B 31
#define DEFAULT_CAP_COLOUR_R 229
#define DEFAULT_CAP_COLOUR_G 33
#define DEFAULT_CAP_COLOUR_B 204
#define DEFAULT_PATH_COLOUR_R 1
#define DEFAULT_PATH_COLOUR_G 1
#define DEFAULT_PATH_COLOUR_B 1
#define DEFAULT_PERM_COLOUR_R 160
#define DEFAULT_PERM_COLOUR_G 32
#define DEFAULT_PERM_COLOUR_B 240
enum
{
ID_COMMENT_COLOUR_BUTTON,
ID_PERMS_COLOUR_BUTTON,
ID_INCLUDES_COLOUR_BUTTON,
ID_CAPABILITIES_COLOUR_BUTTON,
ID_PATHS_COLOUR_BUTTON,
ID_COMMENT_FONT_BUTTON,
ID_PERMS_FONT_BUTTON,
ID_INCLUDES_FONT_BUTTON,
ID_CAPABILITIES_FONT_BUTTON,
ID_PATHS_FONT_BUTTON,
ID_PREFERENCES_NOTEBOOK,
};
/**
* The preferences dialog
*/
class PreferencesDialog: public wxDialog
{
DECLARE_DYNAMIC_CLASS( PreferencesDialog )
DECLARE_EVENT_TABLE()
public:
PreferencesDialog();
PreferencesDialog(wxWindow* parent,
wxWindowID id,
const wxString& caption = _("Preferences"),
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400, 300),
long style = wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX);
bool Create(wxWindow* parent,
wxWindowID,
const wxString& caption = _("Preferences"),
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400, 300),
long style = wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX );
void CreateControls();
wxString BestGuessProfileDirectory ();
wxString BestGuessParserCommand ();
// Event handlers
void OnColourButton(wxCommandEvent &event);
void OnFontButton (wxCommandEvent &event);
// Various accessor functions so we can save the data
wxColour GetCommentButtonColour(void) { return mpCommentsButton->GetBackgroundColour(); }
wxColour GetIncludeButtonColour(void) { return mpIncludesButton->GetBackgroundColour(); }
wxColour GetCapabilityButtonColour(void) { return mpCapabilitiesButton->GetBackgroundColour(); }
wxColour GetPathButtonColour(void) { return mpPathsButton->GetBackgroundColour(); }
wxColour GetPermButtonColour(void) { return mpPermsButton->GetBackgroundColour(); }
wxFont GetCommentButtonFont(void) { return mpCommentsFontButton->GetFont(); }
wxFont GetIncludeButtonFont(void) { return mpIncludesFontButton->GetFont(); }
wxFont GetPathButtonFont(void) { return mpPathsFontButton->GetFont(); }
wxFont GetCapabilityButtonFont(void) { return mpCapabilitiesFontButton->GetFont(); }
wxFont GetPermButtonFont(void) { return mpPermsFontButton->GetFont(); }
wxString GetProfileDir(void) { return mpProfileDir->GetValue(); }
wxString GetParser(void) { return mpParserCommand->GetValue(); }
wxString GetTemplateText(void) { return mpTemplateTextCtrl->GetText(); }
private:
wxNotebook* mpPrefsNotebook;
wxTextCtrl* mpProfileDir;
wxTextCtrl* mpParserCommand;
ProfileTextCtrl* mpTemplateTextCtrl;
wxButton* mpCommentsButton;
wxButton* mpIncludesButton;
wxButton* mpPermsButton;
wxButton* mpCapabilitiesButton;
wxButton* mpPathsButton;
wxButton* mpCommentsFontButton;
wxButton* mpIncludesFontButton;
wxButton* mpCapabilitiesFontButton;
wxButton* mpPathsFontButton;
wxButton* mpPermsFontButton;
};
#endif

View File

@@ -0,0 +1,43 @@
#ifndef PROFILE_DIRECTORY_TRAVERSER
#define PROFILE_DIRECTORY_TRAVERSER
/**
* The wxDirTraverser that searches through the profile directory
*/
class ProfileDirectoryTraverser : public wxDirTraverser
{
public:
ProfileDirectoryTraverser(wxTreeCtrl* profileTree,
const wxTreeItemId& startNode,
const wxString& profileDirectory)
: mpProfileTree(profileTree),
mCurNode(startNode),
mOriginalNode(startNode),
mProfileDirectory(profileDirectory) {}
virtual wxDirTraverseResult OnFile(const wxString& filename)
{
ProfileTreeData* data = new ProfileTreeData(filename);
// OnDir isn't called when the traverser starts
// going through the files in the top level directory,
// so we do this to keep the profiles in the right place
if (wxFileName(filename).GetPath() == mProfileDirectory)
mCurNode = mOriginalNode;
mpProfileTree->AppendItem(mCurNode, wxFileName(filename).GetFullName(), -1, -1, data);
return wxDIR_CONTINUE;
}
virtual wxDirTraverseResult OnDir(const wxString& dirname)
{
mCurNode = mpProfileTree->AppendItem(mOriginalNode, wxFileName(dirname).GetName());
return wxDIR_CONTINUE;
}
private:
wxTreeCtrl* mpProfileTree;
wxTreeItemId mCurNode, mOriginalNode;
wxString mProfileDirectory;
};
#endif

View File

@@ -0,0 +1,115 @@
/* AppArmor Profile Editor (C) 2006 Novell, Inc.
*
* 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.
*
*/
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/textctrl.h>
#include <wx/textfile.h>
#include <wx/config.h>
#include "ProfileTextCtrl.h"
#include "Preferences.h"
#include "Configuration.h"
BEGIN_EVENT_TABLE(ProfileTextCtrl, wxStyledTextCtrl)
EVT_STC_CHANGE(ID_STYLED_PROFILE_WINDOW, ProfileTextCtrl::OnModified)
END_EVENT_TABLE()
ProfileTextCtrl::ProfileTextCtrl(wxWindow *parent, wxWindowID id,
const wxPoint &pos,
const wxSize &size,
long style)
: wxStyledTextCtrl (parent, id, pos, size, style|wxTE_WORDWRAP|wxTE_MULTILINE|wxTE_PROCESS_ENTER)
{
mpParentWindow = parent;
SetLexer(wxSTC_LEX_APPARMOR);
StyleClearAll();
RefreshColoursAndFonts();
mNeedSaving = false;
mIsNew = false;
}
/**
* Loads a file from disk
* @param filename The file to load
* @return true on success, false on failure
*/
bool ProfileTextCtrl::LoadFile(const wxString& filename)
{
wxTextFile file;
wxString currentLine;
if (!file.Open(filename))
return false;
mIgnoreChanges = true; // Have OnModified ignore the events from loading the file
Clear();
mFilename = filename;
wxStyledTextCtrl::LoadFile(filename);
mIgnoreChanges = false;
mNeedSaving = false;
mIsNew = false;
return true;
}
/**
* Event handler triggered by any change in the window
* @param event
*/
void ProfileTextCtrl::OnModified(wxStyledTextEvent &event)
{
if (!mIgnoreChanges)
{
mNeedSaving = true;
wxPostEvent(mpParentWindow, event);
}
}
/**
* Reloads the syntax colouring and fonts
* @param
*/
void ProfileTextCtrl::RefreshColoursAndFonts(void)
{
wxColour yellowColour(252,253,127);
wxFont defaultFont (10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
wxFont commentFont = Configuration::GetCommentFont();
wxFont includeFont = Configuration::GetIncludeFont();
wxFont capabilityFont = Configuration::GetCapabilityFont();
wxFont permFont = Configuration::GetPermFont();
wxFont pathFont = Configuration::GetPathFont();
StyleSetFont (wxSTC_STYLE_DEFAULT, defaultFont);
StyleSetForeground (wxSTC_STYLE_DEFAULT, *wxBLACK);
StyleSetBackground (wxSTC_STYLE_DEFAULT, *wxWHITE);
StyleSetFont (wxSTC_APPARMOR_COMMENT, commentFont);
StyleSetForeground (wxSTC_APPARMOR_COMMENT, Configuration::GetCommentColour());
StyleSetBackground (wxSTC_APPARMOR_COMMENT, *wxWHITE);
StyleSetFont (wxSTC_APPARMOR_INCLUDE, includeFont);
StyleSetForeground (wxSTC_APPARMOR_INCLUDE, Configuration::GetIncludeColour());
StyleSetBackground (wxSTC_APPARMOR_INCLUDE, *wxWHITE);
StyleSetFont (wxSTC_APPARMOR_CAPABILITY, capabilityFont);
StyleSetForeground (wxSTC_APPARMOR_CAPABILITY, Configuration::GetCapColour());
StyleSetBackground (wxSTC_APPARMOR_CAPABILITY, *wxWHITE);
StyleSetFont (wxSTC_APPARMOR_PATH, pathFont);
StyleSetForeground (wxSTC_APPARMOR_PATH, Configuration::GetPathColour());
StyleSetBackground (wxSTC_APPARMOR_PATH, *wxWHITE);
StyleSetFont (wxSTC_APPARMOR_PERMS, permFont);
StyleSetForeground (wxSTC_APPARMOR_PERMS, Configuration::GetPermColour());
StyleSetBackground (wxSTC_APPARMOR_PERMS, *wxWHITE);
StyleSetForeground (wxSTC_STYLE_BRACELIGHT, *wxBLACK);
StyleSetBackground (wxSTC_STYLE_BRACELIGHT, yellowColour);
StyleSetForeground (wxSTC_STYLE_BRACEBAD, *wxBLACK);
StyleSetBackground (wxSTC_STYLE_BRACEBAD, *wxRED);
SetCaretWidth(2);
}

View File

@@ -0,0 +1,44 @@
#ifndef PROFILE_TEXT_CTRL_H
#define PROFILE_TEXT_CTRL_H
#include "wxStyledTextCtrl/stc.h"
#define ID_STYLED_PROFILE_WINDOW 13082
/**
* The syntax highlighting text control
*/
class ProfileTextCtrl : public wxStyledTextCtrl
{
public:
ProfileTextCtrl (wxWindow *parent,
wxWindowID id = wxID_ANY,
const wxPoint &pos = wxDefaultPosition,
const wxSize &size = wxDefaultSize,
long style = wxSUNKEN_BORDER | wxVSCROLL);
bool LoadFile(const wxString &filename);
void ProcessLine(const wxString &currentLine);
void RefreshColoursAndFonts();
void OnModified(wxStyledTextEvent &event);
void OnReturnKey(wxCommandEvent& event);
bool GetNeedSaving() { return mNeedSaving; }
void SetNeedSaving(bool status) { mNeedSaving = status; }
wxString GetFileName() { return mFilename; }
void SetFileName(wxString fileName) { mFilename = fileName; }
void SetIsNew(bool status) { mIsNew = status; }
bool GetIsNew() { return mIsNew; }
void SetIgnoreChanges(bool value) { mIgnoreChanges = value; }
private:
wxWindow *mpParentWindow;
wxString mFilename;
bool mNeedSaving;
bool mIsNew;
bool mIgnoreChanges;
DECLARE_EVENT_TABLE()
};
#endif

View File

@@ -0,0 +1,179 @@
/* AppArmor Profile Editor (C) 2006 Novell, Inc.
*
* 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.
*
*/
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/dir.h>
#include <wx/ffile.h>
#include <wx/busyinfo.h>
#include <wx/process.h>
#include "SearchAllProfiles.h"
IMPLEMENT_DYNAMIC_CLASS(SearchAllProfilesDialog, wxDialog)
BEGIN_EVENT_TABLE(SearchAllProfilesDialog, wxDialog)
EVT_BUTTON(ID_SEARCH_ALL_PROFILES_BUTTON, SearchAllProfilesDialog::OnSearch)
EVT_LISTBOX_DCLICK(ID_SEARCH_ALL_PROFILES_LIST_BOX, SearchAllProfilesDialog::OnListBoxDClick)
END_EVENT_TABLE()
SearchAllProfilesDialog::SearchAllProfilesDialog( )
{
}
SearchAllProfilesDialog::SearchAllProfilesDialog(wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style)
{
Create(parent, id, caption, pos, size, style);
}
bool SearchAllProfilesDialog::Create(wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style )
{
mpSearchPhraseSizer = NULL;
mpSearchStaticText = NULL;
mpSearchPhraseTextCtrl = NULL;
mpSearchButton = NULL;
mpSearchResultsListBox = NULL;
mpOKButtonSizer = NULL;
mProfileDirectory = wxEmptyString;
mEditorExecutable = wxEmptyString;
mSearchedPhrase = wxEmptyString;
SetExtraStyle(GetExtraStyle() | wxWS_EX_BLOCK_EVENTS);
wxDialog::Create(parent, id, caption, pos, size, style);
CreateControls();
GetSizer()->Fit(this);
GetSizer()->SetSizeHints(this);
Centre();
return true;
}
void SearchAllProfilesDialog::CreateControls()
{
wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
SetSizer(mainSizer);
mpSearchPhraseSizer = new wxFlexGridSizer(1, 3, 0, 0);
mainSizer->Add(mpSearchPhraseSizer, 0, wxGROW|wxALL, 5);
mpSearchStaticText = new wxStaticText(this,
wxID_ANY,
_T("Search phrase:"),
wxDefaultPosition,
wxDefaultSize,
0);
mpSearchPhraseSizer->Add(mpSearchStaticText, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5);
mpSearchPhraseTextCtrl = new wxTextCtrl(this,
wxID_ANY,
_T(""),
wxDefaultPosition,
wxSize(300, -1),
0);
mpSearchPhraseSizer->Add(mpSearchPhraseTextCtrl, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5);
mpSearchButton = new wxButton(this,
ID_SEARCH_ALL_PROFILES_BUTTON,
_("Search"),
wxDefaultPosition,
wxDefaultSize,
0);
mpSearchPhraseSizer->Add(mpSearchButton, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
mpSearchResultsListBox = new wxListBox(this,
ID_SEARCH_ALL_PROFILES_LIST_BOX,
wxDefaultPosition,
wxSize(-1, 200),
0,
NULL,
wxLB_SINGLE);
mainSizer->Add(mpSearchResultsListBox, 0, wxGROW|wxALL, 5);
mpOKButtonSizer = new wxStdDialogButtonSizer;
mainSizer->Add(mpOKButtonSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxButton* okButton = new wxButton(this,
wxID_CANCEL,
_("&Cancel"),
wxDefaultPosition,
wxDefaultSize, 0);
mpOKButtonSizer->AddButton(okButton);
mpOKButtonSizer->Realize();
}
/**
* Event handler triggered by the Search button
* @param WXUNUSED( event )
*/
void SearchAllProfilesDialog::OnSearch(wxCommandEvent& WXUNUSED(event))
{
mpSearchButton->Disable();
mpSearchResultsListBox->Clear();
mSearchedPhrase = mpSearchPhraseTextCtrl->GetValue();
DoSearch(mSearchedPhrase);
mpSearchButton->Enable();
}
/**
* Calls the directory traverser
* @param searchString
*/
void SearchAllProfilesDialog::DoSearch(const wxString& searchString)
{
if (mProfileDirectory != wxEmptyString)
{
wxBusyInfo wait(_("Searching..."));
wxTheApp->Yield(); // Needed to repaint the busy window
SearchAllProfilesTraverser traverser(searchString, mpSearchResultsListBox);
wxDir dir (mProfileDirectory);
dir.Traverse(traverser,wxEmptyString);
}
}
/**
* A user has double clicked on a search result
* @param event
*/
void SearchAllProfilesDialog::OnListBoxDClick (wxCommandEvent& event)
{
wxString execString = mEditorExecutable;
execString.Append(_T(" "));
execString.Append(event.GetString());
execString.Append(_T(" \""));
execString.Append(mSearchedPhrase);
execString.Append(_T("\""));
wxProcess *proc = wxProcess::Open(execString);
if (proc == NULL)
{
wxMessageDialog *dlg = new wxMessageDialog(this, _("Could not exec!"), _("Error"),
wxOK|wxICON_ERROR);
dlg->ShowModal();
dlg->Destroy();
}
else
{
proc->Detach();
}
}

View File

@@ -0,0 +1,95 @@
#ifndef _SEARCHALLPROFILESDIALOG_H_
#define _SEARCHALLPROFILESDIALOG_H_
class wxFlexGridSizer;
class wxStdDialogButtonSizer;
/**
* A "Search All Profiles" dialog
*/
class SearchAllProfilesDialog: public wxDialog
{
DECLARE_DYNAMIC_CLASS(SearchAllProfilesDialog)
DECLARE_EVENT_TABLE()
public:
SearchAllProfilesDialog();
SearchAllProfilesDialog(wxWindow* parent,
wxWindowID id = wxID_ANY,
const wxString& caption = _("Search All Profiles"),
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400, 300),
long style = wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX);
/// Creation
bool Create(wxWindow* parent,
wxWindowID id = wxID_ANY,
const wxString& caption = _("Search All Profiles"),
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400, 300),
long style = wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX );
void CreateControls();
void OnSearch(wxCommandEvent& event);
void OnListBoxDClick (wxCommandEvent& event);
void DoSearch(const wxString& searchString);
void SetProfileDirectory (const wxString& dir) { mProfileDirectory = dir; }
void SetEditorExecutable (const wxString& exec) { mEditorExecutable = exec; }
void SetSearchText (const wxString& searchString) { mpSearchPhraseTextCtrl->SetValue(searchString); }
private:
wxFlexGridSizer* mpSearchPhraseSizer;
wxStaticText* mpSearchStaticText;
wxTextCtrl* mpSearchPhraseTextCtrl;
wxButton* mpSearchButton;
wxListBox* mpSearchResultsListBox;
wxStdDialogButtonSizer* mpOKButtonSizer;
wxString mProfileDirectory;
wxString mEditorExecutable;
wxString mSearchedPhrase;
};
/**
* The "Search All" traverser
*/
class SearchAllProfilesTraverser : public wxDirTraverser
{
public:
SearchAllProfilesTraverser (const wxString& search, wxListBox *rBox)
: searchString(search),
resultsBox(rBox) {}
virtual wxDirTraverseResult OnFile(const wxString& filename)
{
if (!tmpFile.Open(filename))
return wxDIR_CONTINUE;
if (!tmpFile.ReadAll(&tmpString))
return wxDIR_CONTINUE;
if (tmpString.Find(searchString) != -1)
resultsBox->Append(filename);
tmpFile.Close();
return wxDIR_CONTINUE;
}
virtual wxDirTraverseResult OnDir(const wxString& dirname)
{
return wxDIR_CONTINUE;
}
private:
wxString searchString;
wxListBox *resultsBox;
wxString tmpString;
wxFFile tmpFile;
};
enum
{
ID_SEARCH_ALL_PROFILES_BUTTON = 15599,
ID_SEARCH_ALL_PROFILES_LIST_BOX
};
#endif

View File

@@ -0,0 +1,173 @@
/* XPM */
static char * opensuse_logo_xpm[] = {
"223 137 33 1",
" c #FFFFFF",
". c #EBF4E6",
"+ c #E4F0DD",
"@ c #CDE5C1",
"# c #C5E1B7",
"$ c #B5D9A1",
"% c #A3D088",
"& c #7ABF48",
"* c #8FC86C",
"= c #F8FBF7",
"- c #BDDDAC",
"; c #85C35B",
"> c #F2F8EF",
", c #D5E9CB",
"' c #99CC7B",
") c #ACD495",
"! c #DCECD4",
"~ c #EDF1F0",
"{ c #D9E2E1",
"] c #E3EAE9",
"^ c #F6F8F8",
"/ c #A1BAB6",
"( c #357D74",
"_ c #007167",
": c #4F8881",
"< c #759E98",
"[ c #C4D3D1",
"} c #85A7A3",
"| c #93B1AD",
"1 c #64938D",
"2 c #B9CBC8",
"3 c #ADC2BF",
"4 c #CFDBD9",
" ",
" ",
" ",
" ",
" ",
" ",
" .+@#$%%%&&&&&&&&&&&&&&&&&&*%%%%%$##@++= ",
" +@-%;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*%-#+. >+= ",
" .,$'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')#+= #&&;%$#+> ",
" >,$;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*)#+= #&&&&&&&&;%-,+ ",
" .-'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'$,> #&&&&&&&&&&&&&&'$@. ",
" .-*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*$,> #&&&&&&&&&&&&&&&&&&&%#!= ",
" >-*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*$!= #&&&&&&&&&&&&&&&&&&&&&&&'-!= ",
" =,'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%@$&&&&&&&&&&&&&&&&&&&&&&&&&&&'#. ",
" >$;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*$! ",
" +%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;-. ",
" ,'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&', ",
" ,*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;#= ",
" ,*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*%&&&&&&&&&;! ",
" ,*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*@. =!$&&&&&&&, ",
" +%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*! =$&&&&&&, ",
" >)&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&$= .+= +;&&&&&! ",
" =#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&$ ,%&&&&;$> .;&&&&;= ",
" !*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&% >'&&&&&&&&&# +&&&&&# ",
" =)&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&> .;&&&&&&&&&&&$ -&&&&&> ",
" @;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&$ '&&&&&&&&&&&&&@ =&&&&&- ",
" =)&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&. ,&&&&&&$> .)&&;= $&&&&;= ",
" +;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&* %&&&&&$ %&&, ,&&&&&@ ",
" -&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&% &&&&&&- %&&# +&&&&&* ",
" ='&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&% &&&&&&&@ =#&&&) &&&&&&+ ",
" .;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&% &&&&&&&&&%'&&&&&# >&&&&&&$ ",
" ,;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&' '&&&&&&&&&&&&&&&@ +&&&&&&&= ",
" @&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&= @&&&&&&&&&&&&&&&> #&&&&&&&, ",
" $&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&, =;&&&&&&&&&&&&&- *&&&&&&&) ",
" $&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&$&&&&&&&&&&&&&* +&&&&&&&&&&&&'= ,&&&&&&&&&= ",
" $&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#.%&&&&&&&&&&&&# !;&&&&&&&&&'= =*&&&&&&&&&, ",
" $&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;= ,*&&&&&&&&&&&+ =$;&&&&&*, )&&&&&&&&&&) ",
" $&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&, #;&&&&&&&&&;! +@#!. $&&&&&&&&&&&; ",
" #&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&* =#;&&&&&&&&&# .'&&&&&&&&&&&&&+ ",
" ,&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&, =$;&&&&&&&&*,= .$&&&&&&&&&&&&&&;. ",
" .&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&% =#;&&&&&&&&&%####$*&&&&&&&&&&&&&&&)= ",
" =;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&$+ =@*&&&&&&&&&&&&&&&&&&&&&&&&&&&*+ ",
" '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%! !)&&&&&&&&&&&&&&&&&&&&&&&*, ",
" #&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*@= =,)&&&&&&&&&&&&&&&&&&', ",
" +&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;$. =!$'&&&&&&&&&&&'-. .> ",
" =*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&',= +,#####@+= +%&# ",
" #&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&$! =,'&&&, ",
" >&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;$!= !$;&&&&&= ",
" %&&&&&&&&&&&&&&&&&&&&&&&&;%##!++++##$%;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%#+ +@)&&&&&&&&) ",
" +&&&&&&&&&&&&&&&&&&&&&&),> >,)&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*%%-%%*&&&&&&&&&&&&+ ",
" %&&&&&&&&&&&&&&&&&&&;#> =,'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&$ ",
" !&&&&&&&&&&&&&&&&&&&#= +%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&- ",
" %&&&&&&&&&&&&&&&&&'. +%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%. ",
" +&&&&&&&&&&&&&&&&&$ !*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&$. ",
" $&&&&&&&&&&&&&&&&# =-&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*#= ",
" =&&&&&&&&&&&&&&&&- >,-%%&&;%%-,> !;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;$! ",
" ,&&&&&&&&&&&&&&&$ =@'&&&&&&&&&&&&&'@> >'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'-! ",
" $&&&&&&&&&&&&&&'= #;&&&&&&&&&&&&&&&&&&$> =$&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*%#!= ",
" *&&&&&&&&&&&&&&. >'&&&&&&&&&&&&&&&&&&&&&&#= $&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%,> .+!##%%'&&&&&&&&&&&'%%##!+ ",
" >&&&&&&&&&&&&&&# .;&&&&&&&&&&&&&&&&&&&&&&&&*. $&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;! ",
" !&&&&&&&&&&&&&;= .;&&&&&&&&&&&&&&&&&&&&&&&&&&&, $&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'$@+. ++#);&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&+ ",
" #&&&&&&&&&&&&&# =;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&, $&&&&&&&&&&&&&&&&&&&&&&&&&&$> !$&&&&&&&&&&&&&&&&&&&&&&&&&&&&$ ",
" )&&&&&&&&&&&&&> )&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&, '&&&&&&&&&&&&&&&&&&&&&&&%> =#;&&&&&&&&&&&&&&&&&&&&&&&&&. ",
" %&&&&&&&&&&&&' +&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&! =;&&&&&&&&&&&&&&&&&&&&&@ =-&&&&&&&&&&&&&&&&&&&&&&&; ",
" '&&&&&&&&&&&&- )&&&&&&&&&&&*$@++@-'&&&&&&&&&&&&&&;= +&&&&&&&&&&&&&&&&&&&&, +*&&&&&&&&&&&&&&&&&&&&&% ",
" &&&&&&&&&&&&&@ =&&&&&&&&&&;, >#;&&&&&&&&&&&&) -&&&&&&&&&&&&&&&&&&- =$&&&&&&&&&&&&&&&&&&&&- ",
" &&&&&&&&&&&&&+ !&&&&&&&&&;. >'&&&&&&&&&&&&+ =*&&&&&&&&&&&&&&&&;= @&&&&&&&&&&&&&&&&&&&# ",
" &&&&&&&&&&&&&+ #&&&&&&&&&# $&&&&&&&&&&&% ,&&&&&&&&&&&&&&&&- ,&&&&&&&&&&&&&&&&&&$ ",
" &&&&&&&&&&&&&+ #&&&&&&&&&> )&&&&&&&&&&&+ %&&&&&&&&&&&&&&&. ,&&&&&&&&&&&&&&&&&% ",
" ;&&&&&&&&&&&&+ #&&&&&&&&& =*&&&&&&&&&&$ !&&&&&&&&&&&&&&* ,&&&&&&&&&&&&&&&&; ",
" %&&&&&&&&&&&&@ #&&&&&&&&&! !&&&&&&&&&&; *&&&&&&&&&&&&&) ,&&&&&&&&&&&&&&&&> ",
" %&&&&&&&&&&&&- ,&&&&&&&&&'= %&&&&&&&&&&. #&&&&&&&&&&&&&# ,&&&&&&&&&&&&&&&, ",
" #&&&&&&&&&&&&' .&&&&&&&&&&'+ =,##@> ,&&&&&&&&&&@ >&&&&&&&&&&&&&@ @&&&&&&&&&&&&&&) ",
" ,&&&&&&&&&&&&&> *&&&&&&&&&&&&&&&&&&;, =&&&&&&&&&&$ *&&&&&&&&&&&&+ $&&&&&&&&&&&&&&= ",
" >&&&&&&&&&&&&&@ ,&&&&&&&&&&&&&&&&&&&&> '&&&&&&&&&% -&&&&&&&&&&&&+ $&&&&&&&&&&&&&# ",
" *&&&&&&&&&&&&* *&&&&&&&&&&&&&&&&&&&# %&&&&&&&&&% !&&&&&&&&&&&&+ $&&&&&&&&&&&&* ",
" -&&&&&&&&&&&&&, .&&&&&&&&&&&&&&&&&&&% %&&&&&&&&&% =;&&&&&&&&&&&+ $&&&&&&&&&&&&, ",
" >&&&&&&&&&&&&&* ,&&&&&&&&&&&&&&&&&&$ %&&&&&&&&&% =@*&&&&&&&&&, $&&&&&&&&&&&* ",
" %&&&&&&&&&&&&&# ,&&&&&&&&&&&&&&&&&+ &&&&&&&&&&% ,*&&&&&&&# @;&&&&&&&&&&@ ",
" ,&&&&&&&&&&&&&&. .'&&&&&&&&&&&&&&$ !&&&&&&&&&&) +%&&&&&# ,'&&&&&&&&;= ",
" *&&&&&&&&&&&&&;= ,*&&&&&&&&&&%+ $&&&&&&&&&&# .$&&&% +$&&&&&&&) ",
" +&&&&&&&&&&&&&&'= .#%*&;%$@> >&&&&&&&&&&&+ >-;* >-;&&&&&+ ",
" %&&&&&&&&&&&&&&'. %&&&&&&&&&&; =@ =,*&&&;= ",
" >;&&&&&&&&&&&&&&;! $&&&&&&&&&&&$ +)&&) ",
" @&&&&&&&&&&&&&&&&$= $&&&&&&&&&&&&. >-;, ",
" )&&&&&&&&&&&&&&&&;#= >%&&&&&&&&&&&&% => ",
" ='&&&&&&&&&&&&&&&&&&$!= !$&&&&&&&&&&&&&&+ ",
" >;&&&&&&&&&&&&&&&&&&&&'$#!++++,#%;&&&&&&&&&&&&&&&- ",
" .;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*= ",
" .'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;. ",
" ='&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&, ",
" -&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&, ",
" +*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;! ~{{{{{{{{{{{{{{{{ ]{{^ ~{{^ {{{{{{{{{{{{{{{{~ {{{{{{{{{{{{{{{{{{{{{] ",
" =#;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'> ~/(_________________:] <___(] /___([ {}__________________| ](______________________1^ 2333{^[ ",
" >$&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&;# [(____________________} 2_____: 4_____(^ ^|_____________________[ :________________________3 3:|<(1< ",
" >#*&&&&&&&&&&&&&&&&&&&&&&&&&;#= [______________________< 3______ 3______{ <______________________3 _________________________< <{31<< ",
" !$;&&&&&&&&&&&&&&&&&&&&',= ~(______________________< 3______ 3______{ 3_______________________2 _________________________| <{33{< ",
" .@)'&&&&&&&&&&&&'$,> |_______________________[ 3______ 3______{ ^(______________________(~ _________________________] ~ ^^ ~ ",
" >++++++++> (______(|33333333333333{ 3______ 3______{ [_______1/33333333333333~ ______:33333333333333333~ ",
" ______:^ 3______ 3______{ 3______/ ______< ",
" ______3 3______ 3______{ 3______{ ______< ",
" ______3 3______ 3______{ 3______{ ______< ",
" ______3 3______ 3______{ 3______{ ______< ",
" ______< 3______ 3______{ 3______2 ______< ",
" >#########,= =#, =,$%%%#> ,#########+ .#+ >@)%%)@= _______}4{{{{{{{{{{{{{^ 3______ 3______{ 2_______3{{{{{{{{{{{{{] ______1{{{{{{{{{{{{{^ ",
" -&&&&&&&&&&&;. )&&-!$;&&&&&&&- .'&&&&&&&&&&&)= >;&&+,%&&&&&&&;! 1______________________<{ 3______ 3______{ ]______________________(|^ ____________________(] ",
" @&&&&&&&&&&&&&;> %&&&&&&&&&&&&&&, =*&&&&&&&&&&&&&) +&&&&&&&&&&&&&&;> [________________________[ 3______ 3______{ <_______________________(] _____________________: ",
" ;&&&%#####-;&&&# %&&&;-#####*&&&' ,&&&;-#####$&&&&> +&&&&%#####-;&&&# 1________________________{ 3______ 3______{ ](_______________________:^ ______________________ ",
" &&&% .&&&% %&&;= =*&&& #&&&+ #&&&+ +&&&% .&&&% ^<_______________________1 3______ 3______{ ](_______________________[ _____________________( ",
" &&&# &&&% %&&% -&&& #&&& +&&&+ +&&&# &&&% [:______________________ 3______ 3______{ ^|(_____________________} _____________________3 ",
" &&&# &&&% %&&% #&&& #&&& +&&&+ +&&&# &&&% ~{{{{{{{{{{{{{[(______{ 3______ 3______{ {{{{{{{{{{{{{{}______< ______:3333333333333{ ",
" &&&# &&&% %&&% #&&& #&&&++++++++@&&&+ +&&&# &&&% /______{ 3______ 3______{ (_____< ______< ",
" &&&# &&&% %&&% #&&& #&&&&&&&&&&&&&&&+ +&&&# &&&% 3______{ 3______ 3______{ <_____< ______< ",
" &&&# &&&% %&&% #&&& #&&&&&&&&&&&&&&&> +&&&# &&&% 3______{ 3______ 3______{ <_____< ______< ",
" &&&# &&&% %&&% #&&& #&&&%%%%%%%%%%%! +&&&# &&&% 3______{ 3______~ /______{ :_____< ______< ",
" &&&# &&&% %&&% #&&& #&&& +&&&# &&&% 1______{ 3______} ](______] ~______< ______< ",
" &&&# &&&% %&&% #&&& #&&& +&&&# &&&% {33333333333333333}_______ [_______:3333333333/(_______ ^[33333333333333333:______} ______:33333333333333333[^ ",
" &&&# &&&% %&&% $&&& #&&& +&&&# &&&% |_________________________1 ~__________________________} ~(_________________________2 _________________________:^ ",
" &&&*= ,&&&) %&&&+ .;&&& #&&&@ +&&&# &&&% ~__________________________2 |_________________________{ 3__________________________~ __________________________2 ",
" '&&&;%%%%%%&&&&@ %&&&&'%%%%%&&&&) +&&&&*%%%%%%. +&&&# &&&% {_________________________1^ ^1_______________________3 3_________________________3 __________________________3 ",
" +&&&&&&&&&&&&&'= %&&&&&&&&&&&&&&+ %&&&&&&&&&&;> +&&&# &&&% ~________________________:] ^1_____________________3 2________________________| :_________________________2 ",
" !;&&&&&&&&&&%= %&&'>,'&&&&&&;! =$&&&&&&&&&)= $&'. ,&;+ 3_____________________(/^ [:_________________}] ^1_____________________:[ [________________________1^ ",
" +@######,. %&&% >,###+ >!######@ @= !. ]{{{{{{{{{{{{{{{{{{{{ ][33333333333334^ {{{{{{{{{{{{{{{{{{{{~ ~{{{{{{{{{{{{{{{{{{{{{{{ ",
" %&&% ",
" %&&% ",
" %&&% ",
" %&&% ",
" %&&% ",
" %&&% ",
" ,&&, ",
" !! ",
" ",
" ",
" ",
" ",
" ",
" "};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,136 @@
#ifndef _PROFILETOOL_H_
#define _PROFILETOOL_H_
#ifndef HELP_FILE_LOCATION
#define HELP_FILE_LOCATION ""
#endif
/**
* @short AppArmor Profile Tool
* @author Matt Barringer <mbarringer@suse.de>
* @version 1.0
*/
class ProfileToolFrame;
class ProfileTreeData;
/**
* The wxApp class
**/
class AppArmorProfileTool : public wxApp
{
public:
virtual bool OnInit();
virtual int OnExit();
private:
ProfileToolFrame *frame;
};
/**
* The main frame
**/
class ProfileToolFrame : public wxFrame
{
public:
ProfileToolFrame(const wxString& title,
const wxPoint& pos,
const wxSize& size,
const wxString& startingProfile,
const wxString& startingHighlight);
~ProfileToolFrame();
void CreateControls(const wxString &startingProfile,
const wxString &startingHighlight);
void ClearProfile();
bool DeleteProfile(wxString& profile);
void EnableSaveMenu(bool toggle);
int FindTreeNodeAndHighlight(wxTreeItemId startingNode, wxString path);
void LoadProfile(const wxString& profile, const wxString& highlight);
void PopulateControls();
void ProfileHasBeenModified();
int ProfileNeedSaving();
void ReloadProfile(const wxString &filePath);
void ReplaceAll(const wxString searchText,
const wxString replaceText,
int matchCase,
int wholeWord);
void RepopulateControl();
int SaveCurrentProfile();
// Event handlers
void OnQuit(wxCommandEvent& event);
void OnClose(wxCloseEvent &event);
void OnAbout(wxCommandEvent& event);
void OnSave(wxCommandEvent& event);
void OnFind(wxCommandEvent& event);
void OnSearchAllProfiles(wxCommandEvent& event);
void OnReplace(wxCommandEvent& event);
void OnSaveAs(wxCommandEvent& event);
void OnHelp(wxCommandEvent& event );
void OnDeleteProfile(wxCommandEvent &event);
void OnReloadProfile(wxCommandEvent &event);
void OnCheckSyntax(wxCommandEvent &event);
void OnEditMenu(wxCommandEvent& event);
void OnPreferences(wxCommandEvent& event);
void OnNewProfile(wxCommandEvent& event);
void OnProfileModified(wxStyledTextEvent &event);
void OnTreeSelection(wxTreeEvent& event);
void OnTreeContextMenu(wxTreeEvent& event);
void OnOpenInclude(wxCommandEvent &event);
void OnInsertInclude(wxCommandEvent &event);
void OnUpdateUI(wxStyledTextEvent &event);
void OnSize(wxSizeEvent& event);
void OnFindButton(wxFindDialogEvent& event);
void OnEndOfProfileReload(wxProcessEvent &event);
private:
wxTreeCtrl *mpProfileTree;
wxFindReplaceDialog *mpFindDialog, *mpReplaceDialog;
wxHtmlHelpController *mpHelpController;
ProfileTextCtrl *mpProfileView;
wxMenuBar *mpMenuBar;
wxFindReplaceData mFindData, mReplaceData;
wxTreeItemId mRootNode;
wxTreeItemId mCurrentNode;
wxSplitterWindow *mpSplitterWindow;
DECLARE_EVENT_TABLE()
};
/**
* This class is used to keep track of what path goes with
* what profile entry in the tree.
*/
class ProfileTreeData : public wxTreeItemData
{
public:
ProfileTreeData(const wxString& path) : mPath(path) {}
wxString GetPath(void) { return mPath; }
private:
wxString mPath;
};
enum
{
ID_MENU_FILE_NEW=1048,
ID_MENU_FILE_PREFERENCES,
ID_MENU_FILE_SAVE,
ID_MENU_FILE_SAVE_AS,
ID_MENU_HELP_ABOUT,
ID_MENU_HELP_PROFILES,
ID_MENU_EDIT_COPY,
ID_MENU_EDIT_CUT,
ID_MENU_EDIT_PASTE,
ID_MENU_EDIT_UNDO,
ID_MENU_EDIT_REDO,
ID_MENU_EDIT_FIND,
ID_MENU_EDIT_REPLACE,
ID_MENU_EDIT_FIND_NEXT,
ID_MENU_EDIT_SEARCH_ALL_PROFILES,
ID_PREFERENCES_DIALOG,
ID_TREE_CONTEXT_DELETE,
ID_TREE_CONTEXT_RELOAD,
ID_RELOAD_PROFILE_PROCESS,
ID_PROFILE_TREE
};
#endif // _PROFILETOOL_H_

View File

@@ -0,0 +1,78 @@
// Scintilla source code edit control
/** @file Accessor.h
** Rapid easy access to contents of a Scintilla.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
enum { wsSpace = 1, wsTab = 2, wsSpaceTab = 4, wsInconsistent=8};
class Accessor;
typedef bool (*PFNIsCommentLeader)(Accessor &styler, int pos, int len);
/**
* Interface to data in a Scintilla.
*/
class Accessor {
protected:
enum {extremePosition=0x7FFFFFFF};
/** @a bufferSize is a trade off between time taken to copy the characters
* and retrieval overhead.
* @a slopSize positions the buffer before the desired position
* in case there is some backtracking. */
enum {bufferSize=4000, slopSize=bufferSize/8};
char buf[bufferSize+1];
int startPos;
int endPos;
int codePage;
virtual bool InternalIsLeadByte(char ch)=0;
virtual void Fill(int position)=0;
public:
Accessor() : startPos(extremePosition), endPos(0), codePage(0) {}
virtual ~Accessor() {}
char operator[](int position) {
if (position < startPos || position >= endPos) {
Fill(position);
}
return buf[position - startPos];
}
/** Safe version of operator[], returning a defined value for invalid position. */
char SafeGetCharAt(int position, char chDefault=' ') {
if (position < startPos || position >= endPos) {
Fill(position);
if (position < startPos || position >= endPos) {
// Position is outside range of document
return chDefault;
}
}
return buf[position - startPos];
}
bool IsLeadByte(char ch) {
return codePage && InternalIsLeadByte(ch);
}
void SetCodePage(int codePage_) { codePage = codePage_; }
virtual bool Match(int pos, const char *s)=0;
virtual char StyleAt(int position)=0;
virtual int GetLine(int position)=0;
virtual int LineStart(int line)=0;
virtual int LevelAt(int line)=0;
virtual int Length()=0;
virtual void Flush()=0;
virtual int GetLineState(int line)=0;
virtual int SetLineState(int line, int state)=0;
virtual int GetPropertyInt(const char *key, int defaultValue=0)=0;
virtual char *GetProperties()=0;
// Style setting
virtual void StartAt(unsigned int start, char chMask=31)=0;
virtual void SetFlags(char chFlags_, char chWhile_)=0;
virtual unsigned int GetStartSegment()=0;
virtual void StartSegment(unsigned int pos)=0;
virtual void ColourTo(unsigned int pos, int chAttr)=0;
virtual void SetLevel(int line, int level)=0;
virtual int IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader = 0)=0;
};

View File

@@ -0,0 +1,174 @@
// Scintilla source code edit control
/** @file AutoComplete.cxx
** Defines the auto completion list box.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "AutoComplete.h"
AutoComplete::AutoComplete() :
active(false),
separator(' '),
typesep('?'),
ignoreCase(false),
chooseSingle(false),
lb(0),
posStart(0),
startLen(0),
cancelAtStartPos(true),
autoHide(true),
dropRestOfWord(false) {
lb = ListBox::Allocate();
stopChars[0] = '\0';
fillUpChars[0] = '\0';
}
AutoComplete::~AutoComplete() {
if (lb) {
lb->Destroy();
delete lb;
lb = 0;
}
}
bool AutoComplete::Active() {
return active;
}
void AutoComplete::Start(Window &parent, int ctrlID,
int position, Point location, int startLen_,
int lineHeight, bool unicodeMode) {
if (active) {
Cancel();
}
lb->Create(parent, ctrlID, location, lineHeight, unicodeMode);
lb->Clear();
active = true;
startLen = startLen_;
posStart = position;
}
void AutoComplete::SetStopChars(const char *stopChars_) {
strncpy(stopChars, stopChars_, sizeof(stopChars));
stopChars[sizeof(stopChars) - 1] = '\0';
}
bool AutoComplete::IsStopChar(char ch) {
return ch && strchr(stopChars, ch);
}
void AutoComplete::SetFillUpChars(const char *fillUpChars_) {
strncpy(fillUpChars, fillUpChars_, sizeof(fillUpChars));
fillUpChars[sizeof(fillUpChars) - 1] = '\0';
}
bool AutoComplete::IsFillUpChar(char ch) {
return ch && strchr(fillUpChars, ch);
}
void AutoComplete::SetSeparator(char separator_) {
separator = separator_;
}
char AutoComplete::GetSeparator() {
return separator;
}
void AutoComplete::SetTypesep(char separator_) {
typesep = separator_;
}
char AutoComplete::GetTypesep() {
return typesep;
}
void AutoComplete::SetList(const char *list) {
lb->SetList(list, separator, typesep);
}
void AutoComplete::Show(bool show) {
lb->Show(show);
if (show)
lb->Select(0);
}
void AutoComplete::Cancel() {
if (lb->Created()) {
lb->Clear();
lb->Destroy();
active = false;
}
}
void AutoComplete::Move(int delta) {
int count = lb->Length();
int current = lb->GetSelection();
current += delta;
if (current >= count)
current = count - 1;
if (current < 0)
current = 0;
lb->Select(current);
}
void AutoComplete::Select(const char *word) {
size_t lenWord = strlen(word);
int location = -1;
const int maxItemLen=1000;
char item[maxItemLen];
int start = 0; // lower bound of the api array block to search
int end = lb->Length() - 1; // upper bound of the api array block to search
while ((start <= end) && (location == -1)) { // Binary searching loop
int pivot = (start + end) / 2;
lb->GetValue(pivot, item, maxItemLen);
int cond;
if (ignoreCase)
cond = CompareNCaseInsensitive(word, item, lenWord);
else
cond = strncmp(word, item, lenWord);
if (!cond) {
// Find first match
while (pivot > start) {
lb->GetValue(pivot-1, item, maxItemLen);
if (ignoreCase)
cond = CompareNCaseInsensitive(word, item, lenWord);
else
cond = strncmp(word, item, lenWord);
if (0 != cond)
break;
--pivot;
}
location = pivot;
if (ignoreCase) {
// Check for exact-case match
for (; pivot <= end; pivot++) {
lb->GetValue(pivot, item, maxItemLen);
if (!strncmp(word, item, lenWord)) {
location = pivot;
break;
}
if (CompareNCaseInsensitive(word, item, lenWord))
break;
}
}
} else if (cond < 0) {
end = pivot - 1;
} else if (cond > 0) {
start = pivot + 1;
}
}
if (location == -1 && autoHide)
Cancel();
else
lb->Select(location);
}

View File

@@ -0,0 +1,70 @@
// Scintilla source code edit control
/** @file AutoComplete.h
** Defines the auto completion list box.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef AUTOCOMPLETE_H
#define AUTOCOMPLETE_H
/**
*/
class AutoComplete {
bool active;
char stopChars[256];
char fillUpChars[256];
char separator;
char typesep; // Type seperator
public:
bool ignoreCase;
bool chooseSingle;
ListBox *lb;
int posStart;
int startLen;
/// Should autocompletion be canceled if editor's currentPos <= startPos?
bool cancelAtStartPos;
bool autoHide;
bool dropRestOfWord;
AutoComplete();
~AutoComplete();
/// Is the auto completion list displayed?
bool Active();
/// Display the auto completion list positioned to be near a character position
void Start(Window &parent, int ctrlID, int position, Point location,
int startLen_, int lineHeight, bool unicodeMode);
/// The stop chars are characters which, when typed, cause the auto completion list to disappear
void SetStopChars(const char *stopChars_);
bool IsStopChar(char ch);
/// The fillup chars are characters which, when typed, fill up the selected word
void SetFillUpChars(const char *fillUpChars_);
bool IsFillUpChar(char ch);
/// The separator character is used when interpreting the list in SetList
void SetSeparator(char separator_);
char GetSeparator();
/// The typesep character is used for seperating the word from the type
void SetTypesep(char separator_);
char GetTypesep();
/// The list string contains a sequence of words separated by the separator character
void SetList(const char *list);
void Show(bool show);
void Cancel();
/// Move the current list element by delta, scrolling appropriately
void Move(int delta);
/// Select a list element that starts with word as the current element
void Select(const char *word);
};
#endif

View File

@@ -0,0 +1,270 @@
// Scintilla source code edit control
/** @file CallTip.cxx
** Code for displaying call tips.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include "Platform.h"
#include "Scintilla.h"
#include "CallTip.h"
CallTip::CallTip() {
wCallTip = 0;
inCallTipMode = false;
posStartCallTip = 0;
val = 0;
rectUp = PRectangle(0,0,0,0);
rectDown = PRectangle(0,0,0,0);
lineHeight = 1;
startHighlight = 0;
endHighlight = 0;
colourBG.desired = ColourDesired(0xff, 0xff, 0xff);
colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80);
colourSel.desired = ColourDesired(0, 0, 0x80);
colourShade.desired = ColourDesired(0, 0, 0);
colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0);
}
CallTip::~CallTip() {
font.Release();
wCallTip.Destroy();
delete []val;
val = 0;
}
const int widthArrow = 14;
void CallTip::RefreshColourPalette(Palette &pal, bool want) {
pal.WantFind(colourBG, want);
pal.WantFind(colourUnSel, want);
pal.WantFind(colourSel, want);
pal.WantFind(colourShade, want);
pal.WantFind(colourLight, want);
}
static bool IsArrowCharacter(char ch) {
return (ch == 0) || (ch == '\001') || (ch == '\002');
}
void CallTip::DrawChunk(Surface *surface, int &x, const char *s,
int posStart, int posEnd, int ytext, PRectangle rcClient,
bool highlight, bool draw) {
s += posStart;
int len = posEnd - posStart;
int maxEnd = 0;
int ends[10];
for (int i=0;i<len;i++) {
if (IsArrowCharacter(s[i])) {
if (i > 0)
ends[maxEnd++] = i;
ends[maxEnd++] = i+1;
}
}
ends[maxEnd++] = len;
int startSeg = 0;
int xEnd;
for (int seg = 0; seg<maxEnd; seg++) {
int endSeg = ends[seg];
if (endSeg > startSeg) {
if (IsArrowCharacter(s[startSeg])) {
xEnd = x + widthArrow;
offsetMain = xEnd;
rcClient.left = x;
rcClient.right = xEnd;
if (draw) {
const int halfWidth = widthArrow / 2 - 3;
const int centreX = x + widthArrow / 2 - 1;
const int centreY = (rcClient.top + rcClient.bottom) / 2;
surface->FillRectangle(rcClient, colourBG.allocated);
PRectangle rcClientInner(rcClient.left+1, rcClient.top+1, rcClient.right-2, rcClient.bottom-1);
surface->FillRectangle(rcClientInner, colourUnSel.allocated);
if (s[startSeg] == '\001') {
// Up arrow
Point pts[] = {
Point(centreX - halfWidth, centreY + halfWidth / 2),
Point(centreX + halfWidth, centreY + halfWidth / 2),
Point(centreX, centreY - halfWidth + halfWidth / 2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
colourBG.allocated, colourBG.allocated);
} else {
// Down arrow
Point pts[] = {
Point(centreX - halfWidth, centreY - halfWidth / 2),
Point(centreX + halfWidth, centreY - halfWidth / 2),
Point(centreX, centreY + halfWidth - halfWidth / 2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
colourBG.allocated, colourBG.allocated);
}
}
if (s[startSeg] == '\001') {
rectUp = rcClient;
} else if (s[startSeg] == '\002') {
rectDown = rcClient;
}
} else {
xEnd = x + surface->WidthText(font, s+startSeg, endSeg - startSeg);
if (draw) {
rcClient.left = x;
rcClient.right = xEnd;
surface->DrawTextNoClip(rcClient, font, ytext,
s+startSeg, endSeg - startSeg,
highlight ? colourSel.allocated : colourUnSel.allocated,
colourBG.allocated);
}
}
x = xEnd;
startSeg = endSeg;
}
}
}
int CallTip::PaintContents(Surface *surfaceWindow, bool draw) {
PRectangle rcClientPos = wCallTip.GetClientPosition();
PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
rcClientPos.bottom - rcClientPos.top);
PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);
// To make a nice small call tip window, it is only sized to fit most normal characters without accents
int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font);
// For each line...
// Draw the definition in three parts: before highlight, highlighted, after highlight
int ytext = rcClient.top + ascent + 1;
rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1;
char *chunkVal = val;
bool moreChunks = true;
int maxWidth = 0;
while (moreChunks) {
char *chunkEnd = strchr(chunkVal, '\n');
if (chunkEnd == NULL) {
chunkEnd = chunkVal + strlen(chunkVal);
moreChunks = false;
}
int chunkOffset = chunkVal - val;
int chunkLength = chunkEnd - chunkVal;
int chunkEndOffset = chunkOffset + chunkLength;
int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset);
thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset);
thisStartHighlight -= chunkOffset;
int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset);
thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset);
thisEndHighlight -= chunkOffset;
rcClient.top = ytext - ascent - 1;
int x = 5;
DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight,
ytext, rcClient, false, draw);
DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight,
ytext, rcClient, true, draw);
DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength,
ytext, rcClient, false, draw);
chunkVal = chunkEnd + 1;
ytext += lineHeight;
rcClient.bottom += lineHeight;
maxWidth = Platform::Maximum(maxWidth, x);
}
return maxWidth;
}
void CallTip::PaintCT(Surface *surfaceWindow) {
if (!val)
return;
PRectangle rcClientPos = wCallTip.GetClientPosition();
PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left,
rcClientPos.bottom - rcClientPos.top);
PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1);
surfaceWindow->FillRectangle(rcClient, colourBG.allocated);
offsetMain = 5;
PaintContents(surfaceWindow, true);
// Draw a raised border around the edges of the window
surfaceWindow->MoveTo(0, rcClientSize.bottom - 1);
surfaceWindow->PenColour(colourShade.allocated);
surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1);
surfaceWindow->LineTo(rcClientSize.right - 1, 0);
surfaceWindow->PenColour(colourLight.allocated);
surfaceWindow->LineTo(0, 0);
surfaceWindow->LineTo(0, rcClientSize.bottom - 1);
}
void CallTip::MouseClick(Point pt) {
clickPlace = 0;
if (rectUp.Contains(pt))
clickPlace = 1;
if (rectDown.Contains(pt))
clickPlace = 2;
}
PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn,
const char *faceName, int size,
int codePage_, int characterSet, Window &wParent) {
clickPlace = 0;
if (val)
delete []val;
val = new char[strlen(defn) + 1];
if (!val)
return PRectangle();
strcpy(val, defn);
codePage = codePage_;
Surface *surfaceMeasure = Surface::Allocate();
if (!surfaceMeasure)
return PRectangle();
surfaceMeasure->Init(wParent.GetID());
surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage);
surfaceMeasure->SetDBCSMode(codePage);
startHighlight = 0;
endHighlight = 0;
inCallTipMode = true;
posStartCallTip = pos;
int deviceHeight = surfaceMeasure->DeviceHeightFont(size);
font.Create(faceName, characterSet, deviceHeight, false, false);
// Look for multiple lines in the text
// Only support \n here - simply means container must avoid \r!
int numLines = 1;
const char *newline;
const char *look = val;
rectUp = PRectangle(0,0,0,0);
rectDown = PRectangle(0,0,0,0);
offsetMain = 5;
int width = PaintContents(surfaceMeasure, false) + 5;
while ((newline = strchr(look, '\n')) != NULL) {
look = newline + 1;
numLines++;
}
lineHeight = surfaceMeasure->Height(font);
// Extra line for border and an empty line at top and bottom
int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2;
delete surfaceMeasure;
return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height);
}
void CallTip::CallTipCancel() {
inCallTipMode = false;
if (wCallTip.Created()) {
wCallTip.Destroy();
}
}
void CallTip::SetHighlight(int start, int end) {
// Avoid flashing by checking something has really changed
if ((start != startHighlight) || (end != endHighlight)) {
startHighlight = start;
endHighlight = end;
if (wCallTip.Created()) {
wCallTip.InvalidateAll();
}
}
}

View File

@@ -0,0 +1,65 @@
// Scintilla source code edit control
/** @file CallTip.h
** Interface to the call tip control.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef CALLTIP_H
#define CALLTIP_H
/**
*/
class CallTip {
int startHighlight;
int endHighlight;
char *val;
Font font;
PRectangle rectUp;
PRectangle rectDown;
int lineHeight;
int offsetMain;
// Private so CallTip objects can not be copied
CallTip(const CallTip &) {}
CallTip &operator=(const CallTip &) { return *this; }
void DrawChunk(Surface *surface, int &x, const char *s,
int posStart, int posEnd, int ytext, PRectangle rcClient,
bool highlight, bool draw);
int PaintContents(Surface *surfaceWindow, bool draw);
public:
Window wCallTip;
Window wDraw;
bool inCallTipMode;
int posStartCallTip;
ColourPair colourBG;
ColourPair colourUnSel;
ColourPair colourSel;
ColourPair colourShade;
ColourPair colourLight;
int codePage;
int clickPlace;
CallTip();
~CallTip();
/// Claim or accept palette entries for the colours required to paint a calltip.
void RefreshColourPalette(Palette &pal, bool want);
void PaintCT(Surface *surfaceWindow);
void MouseClick(Point pt);
/// Setup the calltip and return a rectangle of the area required.
PRectangle CallTipStart(int pos, Point pt, const char *defn,
const char *faceName, int size, int codePage_,
int characterSet, Window &wParent);
void CallTipCancel();
/// Set a range of characters to be displayed in a highlight style.
/// Commonly used to highlight the current parameter.
void SetHighlight(int start, int end);
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,250 @@
// Scintilla source code edit control
/** @file CellBuffer.h
** Manages the text of the document.
**/
// Copyright 1998-2004 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef CELLBUFFER_H
#define CELLBUFFER_H
/**
* This holds the marker identifier and the marker type to display.
* MarkerHandleNumbers are members of lists.
*/
struct MarkerHandleNumber {
int handle;
int number;
MarkerHandleNumber *next;
};
/**
* A marker handle set contains any number of MarkerHandleNumbers.
*/
class MarkerHandleSet {
MarkerHandleNumber *root;
public:
MarkerHandleSet();
~MarkerHandleSet();
int Length();
int NumberFromHandle(int handle);
int MarkValue(); ///< Bit set of marker numbers.
bool Contains(int handle);
bool InsertHandle(int handle, int markerNum);
void RemoveHandle(int handle);
bool RemoveNumber(int markerNum);
void CombineWith(MarkerHandleSet *other);
};
/**
* Each line stores the starting position of the first character of the line in the cell buffer
* and potentially a marker handle set. Often a line will not have any attached markers.
*/
struct LineData {
int startPosition;
MarkerHandleSet *handleSet;
LineData() : startPosition(0), handleSet(0) {
}
};
/**
* The line vector contains information about each of the lines in a cell buffer.
*/
class LineVector {
public:
int growSize;
int lines;
LineData *linesData;
int size;
int *levels;
int sizeLevels;
/// Handles are allocated sequentially and should never have to be reused as 32 bit ints are very big.
int handleCurrent;
LineVector();
~LineVector();
void Init();
void Expand(int sizeNew);
void ExpandLevels(int sizeNew=-1);
void ClearLevels();
void InsertValue(int pos, int value);
void SetValue(int pos, int value);
void Remove(int pos);
int LineFromPosition(int pos);
int AddMark(int line, int marker);
void MergeMarkers(int pos);
void DeleteMark(int line, int markerNum, bool all);
void DeleteMarkFromHandle(int markerHandle);
int LineFromHandle(int markerHandle);
};
enum actionType { insertAction, removeAction, startAction };
/**
* Actions are used to store all the information required to perform one undo/redo step.
*/
class Action {
public:
actionType at;
int position;
char *data;
int lenData;
bool mayCoalesce;
Action();
~Action();
void Create(actionType at_, int position_=0, char *data_=0, int lenData_=0, bool mayCoalesce_=true);
void Destroy();
void Grab(Action *source);
};
/**
*
*/
class UndoHistory {
Action *actions;
int lenActions;
int maxAction;
int currentAction;
int undoSequenceDepth;
int savePoint;
void EnsureUndoRoom();
public:
UndoHistory();
~UndoHistory();
void AppendAction(actionType at, int position, char *data, int length);
void BeginUndoAction();
void EndUndoAction();
void DropUndoSequence();
void DeleteUndoHistory();
/// The save point is a marker in the undo stack where the container has stated that
/// the buffer was saved. Undo and redo can move over the save point.
void SetSavePoint();
bool IsSavePoint() const;
/// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is
/// called that many times. Similarly for redo.
bool CanUndo() const;
int StartUndo();
const Action &GetUndoStep() const;
void CompletedUndoStep();
bool CanRedo() const;
int StartRedo();
const Action &GetRedoStep() const;
void CompletedRedoStep();
};
/**
* Holder for an expandable array of characters that supports undo and line markers.
* Based on article "Data Structures in a Bit-Mapped Text Editor"
* by Wilfred J. Hansen, Byte January 1987, page 183.
*/
class CellBuffer {
private:
char *body; ///< The cell buffer itself.
int size; ///< Allocated size of the buffer.
int length; ///< Total length of the data.
int part1len; ///< Length of the first part.
int gaplen; ///< Length of the gap between the two parts.
char *part2body; ///< The second part of the cell buffer.
///< Doesn't point after the gap but set so that
///< part2body[position] is consistent with body[position].
bool readOnly;
int growSize;
bool collectingUndo;
UndoHistory uh;
LineVector lv;
SVector lineStates;
void GapTo(int position);
void RoomFor(int insertionLength);
inline char ByteAt(int position);
void SetByteAt(int position, char ch);
public:
CellBuffer(int initialLength = 4000);
~CellBuffer();
/// Retrieving positions outside the range of the buffer works and returns 0
char CharAt(int position);
void GetCharRange(char *buffer, int position, int lengthRetrieve);
char StyleAt(int position);
int ByteLength();
int Length();
void Allocate(int newSize);
int Lines();
int LineStart(int line);
int LineFromPosition(int pos) { return lv.LineFromPosition(pos); }
const char *InsertString(int position, char *s, int insertLength);
/// Setting styles for positions outside the range of the buffer is safe and has no effect.
/// @return true if the style of a character is changed.
bool SetStyleAt(int position, char style, char mask='\377');
bool SetStyleFor(int position, int length, char style, char mask);
const char *DeleteChars(int position, int deleteLength);
bool IsReadOnly();
void SetReadOnly(bool set);
/// The save point is a marker in the undo stack where the container has stated that
/// the buffer was saved. Undo and redo can move over the save point.
void SetSavePoint();
bool IsSavePoint();
/// Line marker functions
int AddMark(int line, int markerNum);
void DeleteMark(int line, int markerNum);
void DeleteMarkFromHandle(int markerHandle);
int GetMark(int line);
void DeleteAllMarks(int markerNum);
int LineFromHandle(int markerHandle);
/// Actions without undo
void BasicInsertString(int position, char *s, int insertLength);
void BasicDeleteChars(int position, int deleteLength);
bool SetUndoCollection(bool collectUndo);
bool IsCollectingUndo();
void BeginUndoAction();
void EndUndoAction();
void DeleteUndoHistory();
/// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is
/// called that many times. Similarly for redo.
bool CanUndo();
int StartUndo();
const Action &GetUndoStep() const;
void PerformUndoStep();
bool CanRedo();
int StartRedo();
const Action &GetRedoStep() const;
void PerformRedoStep();
int SetLineState(int line, int state);
int GetLineState(int line);
int GetMaxLineState();
int SetLevel(int line, int level);
int GetLevel(int line);
void ClearLevels();
};
#define CELL_SIZE 2
#endif

View File

@@ -0,0 +1,283 @@
// Scintilla source code edit control
/** @file ContractionState.cxx
** Manages visibility of lines for folding.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "ContractionState.h"
OneLine::OneLine() {
displayLine = 0;
//docLine = 0;
visible = true;
height = 1;
expanded = true;
}
ContractionState::ContractionState() {
lines = 0;
size = 0;
linesInDoc = 1;
linesInDisplay = 1;
valid = false;
docLines = 0;
sizeDocLines = 0;
}
ContractionState::~ContractionState() {
Clear();
}
void ContractionState::MakeValid() const {
if (!valid) {
// Could be cleverer by keeping the index of the last still valid entry
// rather than invalidating all.
linesInDisplay = 0;
for (int lineInDoc=0; lineInDoc<linesInDoc; lineInDoc++) {
lines[lineInDoc].displayLine = linesInDisplay;
if (lines[lineInDoc].visible) {
linesInDisplay += lines[lineInDoc].height;
}
}
if (sizeDocLines < linesInDisplay) {
delete []docLines;
int *docLinesNew = new int[linesInDisplay + growSize];
if (!docLinesNew) {
docLines = 0;
sizeDocLines = 0;
return;
}
docLines = docLinesNew;
sizeDocLines = linesInDisplay + growSize;
}
int lineInDisplay=0;
for (int line=0; line<linesInDoc; line++) {
if (lines[line].visible) {
for (int linePiece=0; linePiece<lines[line].height; linePiece++) {
docLines[lineInDisplay] = line;
lineInDisplay++;
}
}
}
valid = true;
}
}
void ContractionState::Clear() {
delete []lines;
lines = 0;
size = 0;
linesInDoc = 1;
linesInDisplay = 1;
delete []docLines;
docLines = 0;
sizeDocLines = 0;
}
int ContractionState::LinesInDoc() const {
return linesInDoc;
}
int ContractionState::LinesDisplayed() const {
if (size != 0) {
MakeValid();
}
return linesInDisplay;
}
int ContractionState::DisplayFromDoc(int lineDoc) const {
if (size == 0) {
return lineDoc;
}
MakeValid();
if ((lineDoc >= 0) && (lineDoc < linesInDoc)) {
return lines[lineDoc].displayLine;
}
return -1;
}
int ContractionState::DocFromDisplay(int lineDisplay) const {
if (lineDisplay <= 0)
return 0;
if (lineDisplay >= linesInDisplay)
return linesInDoc;
if (size == 0)
return lineDisplay;
MakeValid();
if (docLines) { // Valid allocation
return docLines[lineDisplay];
} else {
return 0;
}
}
void ContractionState::Grow(int sizeNew) {
OneLine *linesNew = new OneLine[sizeNew];
if (linesNew) {
int i = 0;
for (; i < size; i++) {
linesNew[i] = lines[i];
}
for (; i < sizeNew; i++) {
linesNew[i].displayLine = i;
}
delete []lines;
lines = linesNew;
size = sizeNew;
valid = false;
} else {
Platform::DebugPrintf("No memory available\n");
// TODO: Blow up
}
}
void ContractionState::InsertLines(int lineDoc, int lineCount) {
if (size == 0) {
linesInDoc += lineCount;
linesInDisplay += lineCount;
return;
}
//Platform::DebugPrintf("InsertLine[%d] = %d\n", lineDoc);
if ((linesInDoc + lineCount + 2) >= size) {
Grow(linesInDoc + lineCount + growSize);
}
linesInDoc += lineCount;
for (int i = linesInDoc; i >= lineDoc + lineCount; i--) {
lines[i].visible = lines[i - lineCount].visible;
lines[i].height = lines[i - lineCount].height;
linesInDisplay += lines[i].height;
lines[i].expanded = lines[i - lineCount].expanded;
}
for (int d=0;d<lineCount;d++) {
lines[lineDoc+d].visible = true; // Should inherit visibility from context ?
lines[lineDoc+d].height = 1;
lines[lineDoc+d].expanded = true;
}
valid = false;
}
void ContractionState::DeleteLines(int lineDoc, int lineCount) {
if (size == 0) {
linesInDoc -= lineCount;
linesInDisplay -= lineCount;
return;
}
int deltaDisplayed = 0;
for (int d=0;d<lineCount;d++) {
if (lines[lineDoc+d].visible)
deltaDisplayed -= lines[lineDoc+d].height;
}
for (int i = lineDoc; i < linesInDoc-lineCount; i++) {
if (i != 0) // Line zero is always visible
lines[i].visible = lines[i + lineCount].visible;
lines[i].expanded = lines[i + lineCount].expanded;
lines[i].height = lines[i + lineCount].height;
}
linesInDoc -= lineCount;
linesInDisplay += deltaDisplayed;
valid = false;
}
bool ContractionState::GetVisible(int lineDoc) const {
if (size == 0)
return true;
if ((lineDoc >= 0) && (lineDoc < linesInDoc)) {
return lines[lineDoc].visible;
} else {
return false;
}
}
bool ContractionState::SetVisible(int lineDocStart, int lineDocEnd, bool visible) {
if (lineDocStart == 0)
lineDocStart++;
if (lineDocStart > lineDocEnd)
return false;
if (size == 0) {
Grow(linesInDoc + growSize);
}
// TODO: modify docLine members to mirror displayLine
int delta = 0;
// Change lineDocs
if ((lineDocStart <= lineDocEnd) && (lineDocStart >= 0) && (lineDocEnd < linesInDoc)) {
for (int line=lineDocStart; line <= lineDocEnd; line++) {
if (lines[line].visible != visible) {
delta += visible ? lines[line].height : -lines[line].height;
lines[line].visible = visible;
}
}
}
linesInDisplay += delta;
valid = false;
return delta != 0;
}
bool ContractionState::GetExpanded(int lineDoc) const {
if (size == 0)
return true;
if ((lineDoc >= 0) && (lineDoc < linesInDoc)) {
return lines[lineDoc].expanded;
} else {
return false;
}
}
bool ContractionState::SetExpanded(int lineDoc, bool expanded) {
if (size == 0) {
if (expanded) {
// If in completely expanded state then setting
// one line to expanded has no effect.
return false;
}
Grow(linesInDoc + growSize);
}
if ((lineDoc >= 0) && (lineDoc < linesInDoc)) {
if (lines[lineDoc].expanded != expanded) {
lines[lineDoc].expanded = expanded;
return true;
}
}
return false;
}
int ContractionState::GetHeight(int lineDoc) const {
if (size == 0)
return 1;
if ((lineDoc >= 0) && (lineDoc < linesInDoc)) {
return lines[lineDoc].height;
} else {
return 1;
}
}
// Set the number of display lines needed for this line.
// Return true if this is a change.
bool ContractionState::SetHeight(int lineDoc, int height) {
if (lineDoc > linesInDoc)
return false;
if (size == 0) {
if (height == 1) {
// If in completely expanded state then all lines
// assumed to have height of one so no effect here.
return false;
}
Grow(linesInDoc + growSize);
}
if (lines[lineDoc].height != height) {
lines[lineDoc].height = height;
valid = false;
return true;
} else {
return false;
}
}
void ContractionState::ShowAll() {
delete []lines;
lines = 0;
size = 0;
}

View File

@@ -0,0 +1,65 @@
// Scintilla source code edit control
/** @file ContractionState.h
** Manages visibility of lines for folding.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef CONTRACTIONSTATE_H
#define CONTRACTIONSTATE_H
/**
*/
class OneLine {
public:
int displayLine; ///< Position within set of visible lines
//int docLine; ///< Inverse of @a displayLine
int height; ///< Number of display lines needed to show all of the line
bool visible;
bool expanded;
OneLine();
virtual ~OneLine() {}
};
/**
*/
class ContractionState {
void Grow(int sizeNew);
enum { growSize = 4000 };
int linesInDoc;
mutable int linesInDisplay;
mutable OneLine *lines;
int size;
mutable int *docLines;
mutable int sizeDocLines;
mutable bool valid;
void MakeValid() const;
public:
ContractionState();
virtual ~ContractionState();
void Clear();
int LinesInDoc() const;
int LinesDisplayed() const;
int DisplayFromDoc(int lineDoc) const;
int DocFromDisplay(int lineDisplay) const;
void InsertLines(int lineDoc, int lineCount);
void DeleteLines(int lineDoc, int lineCount);
bool GetVisible(int lineDoc) const;
bool SetVisible(int lineDocStart, int lineDocEnd, bool visible);
bool GetExpanded(int lineDoc) const;
bool SetExpanded(int lineDoc, bool expanded);
int GetHeight(int lineDoc) const;
bool SetHeight(int lineDoc, int height);
void ShowAll();
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,305 @@
// Scintilla source code edit control
/** @file Document.h
** Text document that handles notifications, DBCS, styling, words and end of line.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef DOCUMENT_H
#define DOCUMENT_H
/**
* A Position is a position within a document between two characters or at the beginning or end.
* Sometimes used as a character index where it identifies the character after the position.
*/
typedef int Position;
const Position invalidPosition = -1;
/**
* The range class represents a range of text in a document.
* The two values are not sorted as one end may be more significant than the other
* as is the case for the selection where the end position is the position of the caret.
* If either position is invalidPosition then the range is invalid and most operations will fail.
*/
class Range {
public:
Position start;
Position end;
Range(Position pos=0) :
start(pos), end(pos) {
};
Range(Position start_, Position end_) :
start(start_), end(end_) {
};
bool Valid() const {
return (start != invalidPosition) && (end != invalidPosition);
}
// Is the position within the range?
bool Contains(Position pos) const {
if (start < end) {
return (pos >= start && pos <= end);
} else {
return (pos <= start && pos >= end);
}
}
// Is the character after pos within the range?
bool ContainsCharacter(Position pos) const {
if (start < end) {
return (pos >= start && pos < end);
} else {
return (pos < start && pos >= end);
}
}
bool Contains(Range other) const {
return Contains(other.start) && Contains(other.end);
}
bool Overlaps(Range other) const {
return
Contains(other.start) ||
Contains(other.end) ||
other.Contains(start) ||
other.Contains(end);
}
};
class DocWatcher;
class DocModification;
class RESearch;
/**
*/
class Document {
public:
/** Used to pair watcher pointer with user data. */
class WatcherWithUserData {
public:
DocWatcher *watcher;
void *userData;
WatcherWithUserData() {
watcher = 0;
userData = 0;
}
};
enum charClassification { ccSpace, ccNewLine, ccWord, ccPunctuation };
private:
int refCount;
CellBuffer cb;
charClassification charClass[256];
char stylingMask;
int endStyled;
int styleClock;
int enteredCount;
int enteredReadOnlyCount;
WatcherWithUserData *watchers;
int lenWatchers;
bool matchesValid;
RESearch *pre;
char *substituted;
public:
int stylingBits;
int stylingBitsMask;
int eolMode;
/// Can also be SC_CP_UTF8 to enable UTF-8 mode
int dbcsCodePage;
int tabInChars;
int indentInChars;
int actualIndentInChars;
bool useTabs;
bool tabIndents;
bool backspaceUnindents;
Document();
virtual ~Document();
int AddRef();
int Release();
int LineFromPosition(int pos);
int ClampPositionIntoDocument(int pos);
bool IsCrLf(int pos);
int LenChar(int pos);
int MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd=true);
// Gateways to modifying document
void ModifiedAt(int pos);
bool DeleteChars(int pos, int len);
bool InsertStyledString(int position, char *s, int insertLength);
int Undo();
int Redo();
bool CanUndo() { return cb.CanUndo(); }
bool CanRedo() { return cb.CanRedo(); }
void DeleteUndoHistory() { cb.DeleteUndoHistory(); }
bool SetUndoCollection(bool collectUndo) {
return cb.SetUndoCollection(collectUndo);
}
bool IsCollectingUndo() { return cb.IsCollectingUndo(); }
void BeginUndoAction() { cb.BeginUndoAction(); }
void EndUndoAction() { cb.EndUndoAction(); }
void SetSavePoint();
bool IsSavePoint() { return cb.IsSavePoint(); }
int GetLineIndentation(int line);
void SetLineIndentation(int line, int indent);
int GetLineIndentPosition(int line);
int GetColumn(int position);
int FindColumn(int line, int column);
void Indent(bool forwards, int lineBottom, int lineTop);
static char *TransformLineEnds(int *pLenOut, const char *s, size_t len, int eolMode);
void ConvertLineEnds(int eolModeSet);
void SetReadOnly(bool set) { cb.SetReadOnly(set); }
bool IsReadOnly() { return cb.IsReadOnly(); }
bool InsertChar(int pos, char ch);
bool InsertString(int position, const char *s);
bool InsertString(int position, const char *s, size_t insertLength);
void ChangeChar(int pos, char ch);
void DelChar(int pos);
void DelCharBack(int pos);
char CharAt(int position) { return cb.CharAt(position); }
void GetCharRange(char *buffer, int position, int lengthRetrieve) {
cb.GetCharRange(buffer, position, lengthRetrieve);
}
char StyleAt(int position) { return cb.StyleAt(position); }
int GetMark(int line) { return cb.GetMark(line); }
int AddMark(int line, int markerNum);
void AddMarkSet(int line, int valueSet);
void DeleteMark(int line, int markerNum);
void DeleteMarkFromHandle(int markerHandle);
void DeleteAllMarks(int markerNum);
int LineFromHandle(int markerHandle) { return cb.LineFromHandle(markerHandle); }
int LineStart(int line);
int LineEnd(int line);
int LineEndPosition(int position);
int VCHomePosition(int position);
int SetLevel(int line, int level);
int GetLevel(int line) { return cb.GetLevel(line); }
void ClearLevels() { cb.ClearLevels(); }
int GetLastChild(int lineParent, int level=-1);
int GetFoldParent(int line);
void Indent(bool forwards);
int ExtendWordSelect(int pos, int delta, bool onlyWordCharacters=false);
int NextWordStart(int pos, int delta);
int NextWordEnd(int pos, int delta);
int Length() { return cb.Length(); }
void Allocate(int newSize) { cb.Allocate(newSize*2); }
long FindText(int minPos, int maxPos, const char *s,
bool caseSensitive, bool word, bool wordStart, bool regExp, bool posix, int *length);
long FindText(int iMessage, unsigned long wParam, long lParam);
const char *SubstituteByPosition(const char *text, int *length);
int LinesTotal();
void ChangeCase(Range r, bool makeUpperCase);
void SetDefaultCharClasses(bool includeWordClass);
void SetCharClasses(const unsigned char *chars, charClassification newCharClass);
void SetStylingBits(int bits);
void StartStyling(int position, char mask);
bool SetStyleFor(int length, char style);
bool SetStyles(int length, char *styles);
int GetEndStyled() { return endStyled; }
bool EnsureStyledTo(int pos);
int GetStyleClock() { return styleClock; }
void IncrementStyleClock();
int SetLineState(int line, int state) { return cb.SetLineState(line, state); }
int GetLineState(int line) { return cb.GetLineState(line); }
int GetMaxLineState() { return cb.GetMaxLineState(); }
bool AddWatcher(DocWatcher *watcher, void *userData);
bool RemoveWatcher(DocWatcher *watcher, void *userData);
const WatcherWithUserData *GetWatchers() const { return watchers; }
int GetLenWatchers() const { return lenWatchers; }
bool IsWordPartSeparator(char ch);
int WordPartLeft(int pos);
int WordPartRight(int pos);
int ExtendStyleRange(int pos, int delta, bool singleLine = false);
bool IsWhiteLine(int line);
int ParaUp(int pos);
int ParaDown(int pos);
int IndentSize() { return actualIndentInChars; }
int BraceMatch(int position, int maxReStyle);
private:
void CheckReadOnly();
charClassification WordCharClass(unsigned char ch);
bool IsWordStartAt(int pos);
bool IsWordEndAt(int pos);
bool IsWordAt(int start, int end);
void NotifyModifyAttempt();
void NotifySavePoint(bool atSavePoint);
void NotifyModified(DocModification mh);
};
/**
* To optimise processing of document modifications by DocWatchers, a hint is passed indicating the
* scope of the change.
* If the DocWatcher is a document view then this can be used to optimise screen updating.
*/
class DocModification {
public:
int modificationType;
int position;
int length;
int linesAdded; /**< Negative if lines deleted. */
const char *text; /**< Only valid for changes to text, not for changes to style. */
int line;
int foldLevelNow;
int foldLevelPrev;
DocModification(int modificationType_, int position_=0, int length_=0,
int linesAdded_=0, const char *text_=0, int line_=0) :
modificationType(modificationType_),
position(position_),
length(length_),
linesAdded(linesAdded_),
text(text_),
line(line_),
foldLevelNow(0),
foldLevelPrev(0) {}
DocModification(int modificationType_, const Action &act, int linesAdded_=0) :
modificationType(modificationType_),
position(act.position),
length(act.lenData),
linesAdded(linesAdded_),
text(act.data),
line(0),
foldLevelNow(0),
foldLevelPrev(0) {}
};
/**
* A class that wants to receive notifications from a Document must be derived from DocWatcher
* and implement the notification methods. It can then be added to the watcher list with AddWatcher.
*/
class DocWatcher {
public:
virtual ~DocWatcher() {}
virtual void NotifyModifyAttempt(Document *doc, void *userData) = 0;
virtual void NotifySavePoint(Document *doc, void *userData, bool atSavePoint) = 0;
virtual void NotifyModified(Document *doc, DocModification mh, void *userData) = 0;
virtual void NotifyDeleted(Document *doc, void *userData) = 0;
virtual void NotifyStyleNeeded(Document *doc, void *userData, int endPos) = 0;
};
#endif

View File

@@ -0,0 +1,186 @@
// Scintilla source code edit control
/** @file DocumentAccessor.cxx
** Rapid easy access to contents of a Scintilla.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "SVector.h"
#include "Accessor.h"
#include "DocumentAccessor.h"
#include "CellBuffer.h"
#include "Scintilla.h"
#include "Document.h"
DocumentAccessor::~DocumentAccessor() {
}
bool DocumentAccessor::InternalIsLeadByte(char ch) {
if (SC_CP_UTF8 == codePage)
// For lexing, all characters >= 0x80 are treated the
// same so none is considered a lead byte.
return false;
else
return Platform::IsDBCSLeadByte(codePage, ch);
}
void DocumentAccessor::Fill(int position) {
if (lenDoc == -1)
lenDoc = pdoc->Length();
startPos = position - slopSize;
if (startPos + bufferSize > lenDoc)
startPos = lenDoc - bufferSize;
if (startPos < 0)
startPos = 0;
endPos = startPos + bufferSize;
if (endPos > lenDoc)
endPos = lenDoc;
pdoc->GetCharRange(buf, startPos, endPos-startPos);
buf[endPos-startPos] = '\0';
}
bool DocumentAccessor::Match(int pos, const char *s) {
for (int i=0; *s; i++) {
if (*s != SafeGetCharAt(pos+i))
return false;
s++;
}
return true;
}
char DocumentAccessor::StyleAt(int position) {
// Mask off all bits which aren't in the 'mask'.
return static_cast<char>(pdoc->StyleAt(position) & mask);
}
int DocumentAccessor::GetLine(int position) {
return pdoc->LineFromPosition(position);
}
int DocumentAccessor::LineStart(int line) {
return pdoc->LineStart(line);
}
int DocumentAccessor::LevelAt(int line) {
return pdoc->GetLevel(line);
}
int DocumentAccessor::Length() {
if (lenDoc == -1)
lenDoc = pdoc->Length();
return lenDoc;
}
int DocumentAccessor::GetLineState(int line) {
return pdoc->GetLineState(line);
}
int DocumentAccessor::SetLineState(int line, int state) {
return pdoc->SetLineState(line, state);
}
void DocumentAccessor::StartAt(unsigned int start, char chMask) {
// Store the mask specified for use with StyleAt.
mask = chMask;
pdoc->StartStyling(start, chMask);
startPosStyling = start;
}
void DocumentAccessor::StartSegment(unsigned int pos) {
startSeg = pos;
}
void DocumentAccessor::ColourTo(unsigned int pos, int chAttr) {
// Only perform styling if non empty range
if (pos != startSeg - 1) {
if (pos < startSeg) {
Platform::DebugPrintf("Bad colour positions %d - %d\n", startSeg, pos);
}
if (validLen + (pos - startSeg + 1) >= bufferSize)
Flush();
if (validLen + (pos - startSeg + 1) >= bufferSize) {
// Too big for buffer so send directly
pdoc->SetStyleFor(pos - startSeg + 1, static_cast<char>(chAttr));
} else {
if (chAttr != chWhile)
chFlags = 0;
chAttr |= chFlags;
for (unsigned int i = startSeg; i <= pos; i++) {
PLATFORM_ASSERT((startPosStyling + validLen) < Length());
styleBuf[validLen++] = static_cast<char>(chAttr);
}
}
}
startSeg = pos+1;
}
void DocumentAccessor::SetLevel(int line, int level) {
pdoc->SetLevel(line, level);
}
void DocumentAccessor::Flush() {
startPos = extremePosition;
lenDoc = -1;
if (validLen > 0) {
pdoc->SetStyles(validLen, styleBuf);
startPosStyling += validLen;
validLen = 0;
}
}
int DocumentAccessor::IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader) {
int end = Length();
int spaceFlags = 0;
// Determines the indentation level of the current line and also checks for consistent
// indentation compared to the previous line.
// Indentation is judged consistent when the indentation whitespace of each line lines
// the same or the indentation of one line is a prefix of the other.
int pos = LineStart(line);
char ch = (*this)[pos];
int indent = 0;
bool inPrevPrefix = line > 0;
int posPrev = inPrevPrefix ? LineStart(line-1) : 0;
while ((ch == ' ' || ch == '\t') && (pos < end)) {
if (inPrevPrefix) {
char chPrev = (*this)[posPrev++];
if (chPrev == ' ' || chPrev == '\t') {
if (chPrev != ch)
spaceFlags |= wsInconsistent;
} else {
inPrevPrefix = false;
}
}
if (ch == ' ') {
spaceFlags |= wsSpace;
indent++;
} else { // Tab
spaceFlags |= wsTab;
if (spaceFlags & wsSpace)
spaceFlags |= wsSpaceTab;
indent = (indent / 8 + 1) * 8;
}
ch = (*this)[++pos];
}
*flags = spaceFlags;
indent += SC_FOLDLEVELBASE;
// if completely empty line or the start of a comment...
if ((ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') ||
(pfnIsCommentLeader && (*pfnIsCommentLeader)(*this, pos, end-pos)) )
return indent | SC_FOLDLEVELWHITEFLAG;
else
return indent;
}

View File

@@ -0,0 +1,67 @@
// Scintilla source code edit control
/** @file DocumentAccessor.h
** Implementation of BufferAccess and StylingAccess on a Scintilla
** rapid easy access to contents of a Scintilla.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
class Document;
/**
*/
class DocumentAccessor : public Accessor {
// Private so DocumentAccessor objects can not be copied
DocumentAccessor(const DocumentAccessor &source) : Accessor(), props(source.props) {}
DocumentAccessor &operator=(const DocumentAccessor &) { return *this; }
protected:
Document *pdoc;
PropSet &props;
WindowID id;
int lenDoc;
char styleBuf[bufferSize];
int validLen;
char chFlags;
char chWhile;
unsigned int startSeg;
int startPosStyling;
int mask;
bool InternalIsLeadByte(char ch);
void Fill(int position);
public:
DocumentAccessor(Document *pdoc_, PropSet &props_, WindowID id_=0) :
Accessor(), pdoc(pdoc_), props(props_), id(id_),
lenDoc(-1), validLen(0), chFlags(0), chWhile(0),
startSeg(0), startPosStyling(0),
mask(127) { // Initialize the mask to be big enough for any lexer.
}
~DocumentAccessor();
bool Match(int pos, const char *s);
char StyleAt(int position);
int GetLine(int position);
int LineStart(int line);
int LevelAt(int line);
int Length();
void Flush();
int GetLineState(int line);
int SetLineState(int line, int state);
int GetPropertyInt(const char *key, int defaultValue=0) {
return props.GetInt(key, defaultValue);
}
char *GetProperties() {
return props.ToString();
}
WindowID GetWindow() { return id; }
void StartAt(unsigned int start, char chMask=31);
void SetFlags(char chFlags_, char chWhile_) {chFlags = chFlags_; chWhile = chWhile_; };
unsigned int GetStartSegment() { return startSeg; }
void StartSegment(unsigned int pos);
void ColourTo(unsigned int pos, int chAttr);
void SetLevel(int line, int level);
int IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader = 0);
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,581 @@
// Scintilla source code edit control
/** @file Editor.h
** Defines the main editor class.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef EDITOR_H
#define EDITOR_H
/**
*/
class Caret {
public:
bool active;
bool on;
int period;
Caret();
};
/**
*/
class Timer {
public:
bool ticking;
int ticksToWait;
enum {tickSize = 100};
TickerID tickerID;
Timer();
};
/**
*/
class Idler {
public:
bool state;
IdlerID idlerID;
Idler();
};
/**
*/
class LineLayout {
private:
friend class LineLayoutCache;
int *lineStarts;
int lenLineStarts;
/// Drawing is only performed for @a maxLineLength characters on each line.
int lineNumber;
bool inCache;
public:
enum { wrapWidthInfinite = 0x7ffffff };
int maxLineLength;
int numCharsInLine;
enum validLevel { llInvalid, llCheckTextAndStyle, llPositions, llLines } validity;
int xHighlightGuide;
bool highlightColumn;
int selStart;
int selEnd;
bool containsCaret;
int edgeColumn;
char *chars;
unsigned char *styles;
int styleBitsSet;
char *indicators;
int *positions;
char bracePreviousStyles[2];
// Hotspot support
int hsStart;
int hsEnd;
// Wrapped line support
int widthLine;
int lines;
LineLayout(int maxLineLength_);
virtual ~LineLayout();
void Resize(int maxLineLength_);
void Free();
void Invalidate(validLevel validity_);
int LineStart(int line) {
if (line <= 0) {
return 0;
} else if ((line >= lines) || !lineStarts) {
return numCharsInLine;
} else {
return lineStarts[line];
}
}
void SetLineStart(int line, int start);
void SetBracesHighlight(Range rangeLine, Position braces[],
char bracesMatchStyle, int xHighlight);
void RestoreBracesHighlight(Range rangeLine, Position braces[]);
};
/**
*/
class LineLayoutCache {
int level;
int length;
int size;
LineLayout **cache;
bool allInvalidated;
int styleClock;
int useCount;
void Allocate(int length_);
void AllocateForLevel(int linesOnScreen, int linesInDoc);
public:
LineLayoutCache();
virtual ~LineLayoutCache();
void Deallocate();
enum {
llcNone=SC_CACHE_NONE,
llcCaret=SC_CACHE_CARET,
llcPage=SC_CACHE_PAGE,
llcDocument=SC_CACHE_DOCUMENT
};
void Invalidate(LineLayout::validLevel validity_);
void SetLevel(int level_);
int GetLevel() { return level; }
LineLayout *Retrieve(int lineNumber, int lineCaret, int maxChars, int styleClock_,
int linesOnScreen, int linesInDoc);
void Dispose(LineLayout *ll);
};
/**
* Hold a piece of text selected for copying or dragging.
* The text is expected to hold a terminating "\0" and this is counted in len.
*/
class SelectionText {
public:
char *s;
int len;
bool rectangular;
int codePage;
int characterSet;
SelectionText() : s(0), len(0), rectangular(false), codePage(0), characterSet(0) {}
~SelectionText() {
Free();
}
void Free() {
Set(0, 0, 0, 0, false);
}
void Set(char *s_, int len_, int codePage_, int characterSet_, bool rectangular_) {
delete []s;
s = s_;
if (s)
len = len_;
else
len = 0;
codePage = codePage_;
characterSet = characterSet_;
rectangular = rectangular_;
}
void Copy(const char *s_, int len_, int codePage_, int characterSet_, bool rectangular_) {
delete []s;
s = new char[len_];
if (s) {
len = len_;
for (int i = 0; i < len_; i++) {
s[i] = s_[i];
}
} else {
len = 0;
}
codePage = codePage_;
characterSet = characterSet_;
rectangular = rectangular_;
}
void Copy(const SelectionText &other) {
Copy(other.s, other.len, other.codePage, other.characterSet, other.rectangular);
}
};
/**
*/
class Editor : public DocWatcher {
// Private so Editor objects can not be copied
Editor(const Editor &) : DocWatcher() {}
Editor &operator=(const Editor &) { return *this; }
protected: // ScintillaBase subclass needs access to much of Editor
/** On GTK+, Scintilla is a container widget holding two scroll bars
* whereas on Windows there is just one window with both scroll bars turned on. */
Window wMain; ///< The Scintilla parent window
/** Style resources may be expensive to allocate so are cached between uses.
* When a style attribute is changed, this cache is flushed. */
bool stylesValid;
ViewStyle vs;
Palette palette;
int printMagnification;
int printColourMode;
int printWrapState;
int cursorMode;
int controlCharSymbol;
bool hasFocus;
bool hideSelection;
bool inOverstrike;
int errorStatus;
bool mouseDownCaptures;
/** In bufferedDraw mode, graphics operations are drawn to a pixmap and then copied to
* the screen. This avoids flashing but is about 30% slower. */
bool bufferedDraw;
/** In twoPhaseDraw mode, drawing is performed in two phases, first the background
* and then the foreground. This avoids chopping off characters that overlap the next run. */
bool twoPhaseDraw;
int xOffset; ///< Horizontal scrolled amount in pixels
int xCaretMargin; ///< Ensure this many pixels visible on both sides of caret
bool horizontalScrollBarVisible;
int scrollWidth;
bool verticalScrollBarVisible;
bool endAtLastLine;
bool caretSticky;
Surface *pixmapLine;
Surface *pixmapSelMargin;
Surface *pixmapSelPattern;
Surface *pixmapIndentGuide;
Surface *pixmapIndentGuideHighlight;
LineLayoutCache llc;
KeyMap kmap;
Caret caret;
Timer timer;
Timer autoScrollTimer;
enum { autoScrollDelay = 200 };
Idler idler;
Point lastClick;
unsigned int lastClickTime;
int dwellDelay;
int ticksToDwell;
bool dwelling;
enum { selChar, selWord, selLine } selectionType;
Point ptMouseLast;
bool inDragDrop;
bool dropWentOutside;
int posDrag;
int posDrop;
int lastXChosen;
int lineAnchor;
int originalAnchorPos;
int currentPos;
int anchor;
int targetStart;
int targetEnd;
int searchFlags;
int topLine;
int posTopLine;
int lengthForEncode;
bool needUpdateUI;
Position braces[2];
int bracesMatchStyle;
int highlightGuideColumn;
int theEdge;
enum { notPainting, painting, paintAbandoned } paintState;
PRectangle rcPaint;
bool paintingAllText;
int modEventMask;
SelectionText drag;
enum selTypes { noSel, selStream, selRectangle, selLines };
selTypes selType;
bool moveExtendsSelection;
int xStartSelect; ///< x position of start of rectangular selection
int xEndSelect; ///< x position of end of rectangular selection
bool primarySelection;
int caretXPolicy;
int caretXSlop; ///< Ensure this many pixels visible on both sides of caret
int caretYPolicy;
int caretYSlop; ///< Ensure this many lines visible on both sides of caret
int visiblePolicy;
int visibleSlop;
int searchAnchor;
bool recordingMacro;
int foldFlags;
ContractionState cs;
// Hotspot support
int hsStart;
int hsEnd;
// Wrapping support
enum { eWrapNone, eWrapWord, eWrapChar } wrapState;
bool backgroundWrapEnabled;
int wrapWidth;
int docLineLastWrapped;
int docLastLineToWrap;
int wrapVisualFlags;
int wrapVisualFlagsLocation;
int wrapVisualStartIndent;
int actualWrapVisualStartIndent;
bool convertPastes;
Document *pdoc;
Editor();
virtual ~Editor();
virtual void Initialise() = 0;
virtual void Finalise();
void InvalidateStyleData();
void InvalidateStyleRedraw();
virtual void RefreshColourPalette(Palette &pal, bool want);
void RefreshStyleData();
void DropGraphics();
virtual PRectangle GetClientRectangle();
PRectangle GetTextRectangle();
int LinesOnScreen();
int LinesToScroll();
int MaxScrollPos();
Point LocationFromPosition(int pos);
int XFromPosition(int pos);
int PositionFromLocation(Point pt);
int PositionFromLocationClose(Point pt);
int PositionFromLineX(int line, int x);
int LineFromLocation(Point pt);
void SetTopLine(int topLineNew);
bool AbandonPaint();
void RedrawRect(PRectangle rc);
void Redraw();
void RedrawSelMargin(int line=-1);
PRectangle RectangleFromRange(int start, int end);
void InvalidateRange(int start, int end);
int CurrentPosition();
bool SelectionEmpty();
int SelectionStart();
int SelectionEnd();
void SetRectangularRange();
void InvalidateSelection(int currentPos_, int anchor_);
void SetSelection(int currentPos_, int anchor_);
void SetSelection(int currentPos_);
void SetEmptySelection(int currentPos_);
bool RangeContainsProtected(int start, int end) const;
bool SelectionContainsProtected();
int MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd=true);
int MovePositionTo(int newPos, selTypes sel=noSel, bool ensureVisible=true);
int MovePositionSoVisible(int pos, int moveDir);
void SetLastXChosen();
void ScrollTo(int line, bool moveThumb=true);
virtual void ScrollText(int linesToMove);
void HorizontalScrollTo(int xPos);
void MoveCaretInsideView(bool ensureVisible=true);
int DisplayFromPosition(int pos);
void EnsureCaretVisible(bool useMargin=true, bool vert=true, bool horiz=true);
void ShowCaretAtCurrentPosition();
void DropCaret();
void InvalidateCaret();
virtual void UpdateSystemCaret();
void NeedWrapping(int docLineStartWrapping = 0, int docLineEndWrapping = 0x7ffffff);
bool WrapLines(bool fullWrap, int priorityWrapLineStart);
void LinesJoin();
void LinesSplit(int pixelWidth);
int SubstituteMarkerIfEmpty(int markerCheck, int markerDefault);
void PaintSelMargin(Surface *surface, PRectangle &rc);
LineLayout *RetrieveLineLayout(int lineNumber);
void LayoutLine(int line, Surface *surface, ViewStyle &vstyle, LineLayout *ll,
int width=LineLayout::wrapWidthInfinite);
ColourAllocated TextBackground(ViewStyle &vsDraw, bool overrideBackground, ColourAllocated background, bool inSelection, bool inHotspot, int styleMain, int i, LineLayout *ll);
void DrawIndentGuide(Surface *surface, int lineVisible, int lineHeight, int start, PRectangle rcSegment, bool highlight);
void DrawWrapMarker(Surface *surface, PRectangle rcPlace, bool isEndMarker, ColourAllocated wrapColour);
void DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, LineLayout *ll,
int line, int lineEnd, int xStart, int subLine, int subLineStart,
bool overrideBackground, ColourAllocated background,
bool drawWrapMark, ColourAllocated wrapColour);
void DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVisible, int xStart,
PRectangle rcLine, LineLayout *ll, int subLine=0);
void RefreshPixMaps(Surface *surfaceWindow);
void Paint(Surface *surfaceWindow, PRectangle rcArea);
long FormatRange(bool draw, RangeToFormat *pfr);
int TextWidth(int style, const char *text);
virtual void SetVerticalScrollPos() = 0;
virtual void SetHorizontalScrollPos() = 0;
virtual bool ModifyScrollBars(int nMax, int nPage) = 0;
virtual void ReconfigureScrollBars();
void SetScrollBars();
void ChangeSize();
void AddChar(char ch);
virtual void AddCharUTF(char *s, unsigned int len, bool treatAsDBCS=false);
void ClearSelection();
void ClearAll();
void ClearDocumentStyle();
void Cut();
void PasteRectangular(int pos, const char *ptr, int len);
virtual void Copy() = 0;
virtual bool CanPaste();
virtual void Paste() = 0;
void OpenAppArmorInclude();
void Clear();
void SelectAll();
void Undo();
void Redo();
void DelChar();
void DelCharBack(bool allowLineStartDeletion);
virtual void ClaimSelection() = 0;
virtual void NotifyChange() = 0;
virtual void NotifyFocus(bool focus);
virtual int GetCtrlID() { return ctrlID; }
virtual void NotifyParent(SCNotification scn) = 0;
virtual void NotifyStyleToNeeded(int endStyleNeeded);
void NotifyChar(int ch);
void NotifyMove(int position);
void NotifySavePoint(bool isSavePoint);
void NotifyModifyAttempt();
virtual void NotifyDoubleClick(Point pt, bool shift);
void NotifyHotSpotClicked(int position, bool shift, bool ctrl, bool alt);
void NotifyHotSpotDoubleClicked(int position, bool shift, bool ctrl, bool alt);
void NotifyUpdateUI();
void NotifyPainted();
bool NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt);
void NotifyNeedShown(int pos, int len);
void NotifyDwelling(Point pt, bool state);
void NotifyZoom();
void NotifyModifyAttempt(Document *document, void *userData);
void NotifySavePoint(Document *document, void *userData, bool atSavePoint);
void CheckModificationForWrap(DocModification mh);
void NotifyModified(Document *document, DocModification mh, void *userData);
void NotifyDeleted(Document *document, void *userData);
void NotifyStyleNeeded(Document *doc, void *userData, int endPos);
void NotifyMacroRecord(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
void PageMove(int direction, selTypes sel=noSel, bool stuttered = false);
void ChangeCaseOfSelection(bool makeUpperCase);
void LineTranspose();
void Duplicate(bool forLine);
virtual void CancelModes();
void NewLine();
void CursorUpOrDown(int direction, selTypes sel=noSel);
void ParaUpOrDown(int direction, selTypes sel=noSel);
int StartEndDisplayLine(int pos, bool start);
virtual int KeyCommand(unsigned int iMessage);
virtual int KeyDefault(int /* key */, int /*modifiers*/);
int KeyDown(int key, bool shift, bool ctrl, bool alt, bool *consumed=0);
int GetWhitespaceVisible();
void SetWhitespaceVisible(int view);
void Indent(bool forwards);
long FindText(uptr_t wParam, sptr_t lParam);
void SearchAnchor();
long SearchText(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
long SearchInTarget(const char *text, int length);
void GoToLine(int lineNo);
virtual void CopyToClipboard(const SelectionText &selectedText) = 0;
char *CopyRange(int start, int end);
void CopySelectionFromRange(SelectionText *ss, int start, int end);
void CopySelectionRange(SelectionText *ss);
void CopyRangeToClipboard(int start, int end);
void CopyText(int length, const char *text);
void SetDragPosition(int newPos);
virtual void DisplayCursor(Window::Cursor c);
virtual void StartDrag();
void DropAt(int position, const char *value, bool moving, bool rectangular);
/** PositionInSelection returns 0 if position in selection, -1 if position before selection, and 1 if after.
* Before means either before any line of selection or before selection on its line, with a similar meaning to after. */
int PositionInSelection(int pos);
bool PointInSelection(Point pt);
bool PointInSelMargin(Point pt);
void LineSelection(int lineCurrent_, int lineAnchor_);
void DwellEnd(bool mouseMoved);
virtual void ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt);
void ButtonMove(Point pt);
void ButtonUp(Point pt, unsigned int curTime, bool ctrl);
void Tick();
bool Idle();
virtual void SetTicking(bool on) = 0;
virtual bool SetIdle(bool) { return false; }
virtual void SetMouseCapture(bool on) = 0;
virtual bool HaveMouseCapture() = 0;
void SetFocusState(bool focusState);
virtual bool PaintContains(PRectangle rc);
bool PaintContainsMargin();
void CheckForChangeOutsidePaint(Range r);
void SetBraceHighlight(Position pos0, Position pos1, int matchStyle);
void SetDocPointer(Document *document);
void Expand(int &line, bool doExpand);
void ToggleContraction(int line);
void EnsureLineVisible(int lineDoc, bool enforcePolicy);
int ReplaceTarget(bool replacePatterns, const char *text, int length=-1);
bool PositionIsHotspot(int position);
bool PointIsHotspot(Point pt);
void SetHotSpotRange(Point *pt);
void GetHotSpotRange(int& hsStart, int& hsEnd);
int CodePage() const;
int WrapCount(int line);
virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) = 0;
public:
// Public so the COM thunks can access it.
bool IsUnicodeMode() const;
// Public so scintilla_send_message can use it.
virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
// Public so scintilla_set_id can use it.
int ctrlID;
friend class AutoSurface;
friend class SelectionLineIterator;
};
/**
* A smart pointer class to ensure Surfaces are set up and deleted correctly.
*/
class AutoSurface {
private:
Surface *surf;
public:
AutoSurface(Editor *ed) : surf(0) {
if (ed->wMain.GetID()) {
surf = Surface::Allocate();
if (surf) {
surf->Init(ed->wMain.GetID());
surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage());
surf->SetDBCSMode(ed->CodePage());
}
}
}
AutoSurface(SurfaceID sid, Editor *ed) : surf(0) {
if (ed->wMain.GetID()) {
surf = Surface::Allocate();
if (surf) {
surf->Init(sid, ed->wMain.GetID());
surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage());
surf->SetDBCSMode(ed->CodePage());
}
}
}
~AutoSurface() {
delete surf;
}
Surface *operator->() const {
return surf;
}
operator Surface *() const {
return surf;
}
};
#endif

View File

@@ -0,0 +1,257 @@
// Scintilla source code edit control
/** @file ExternalLexer.cxx
** Support external lexers in DLLs.
**/
// Copyright 2001 Simon Steele <ss@pnotepad.org>, portions copyright Neil Hodgson.
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "Platform.h"
#include "SciLexer.h"
#include "PropSet.h"
#include "Accessor.h"
#include "DocumentAccessor.h"
#include "KeyWords.h"
#include "ExternalLexer.h"
LexerManager *LexerManager::theInstance = NULL;
//------------------------------------------
//
// ExternalLexerModule
//
//------------------------------------------
char **WordListsToStrings(WordList *val[]) {
int dim = 0;
while (val[dim])
dim++;
char **wls = new char * [dim + 1];
for (int i = 0;i < dim;i++) {
SString words;
words = "";
for (int n = 0; n < val[i]->len; n++) {
words += val[i]->words[n];
if (n != val[i]->len - 1)
words += " ";
}
wls[i] = new char[words.length() + 1];
strcpy(wls[i], words.c_str());
}
wls[dim] = 0;
return wls;
}
void DeleteWLStrings(char *strs[]) {
int dim = 0;
while (strs[dim]) {
delete strs[dim];
dim++;
}
delete [] strs;
}
void ExternalLexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (!fneLexer)
return ;
char **kwds = WordListsToStrings(keywordlists);
char *ps = styler.GetProperties();
// The accessor passed in is always a DocumentAccessor so this cast and the subsequent
// access will work. Can not use the stricter dynamic_cast as that requires RTTI.
DocumentAccessor &da = static_cast<DocumentAccessor &>(styler);
WindowID wID = da.GetWindow();
fneLexer(externalLanguage, startPos, lengthDoc, initStyle, kwds, wID, ps);
delete ps;
DeleteWLStrings(kwds);
}
void ExternalLexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (!fneFolder)
return ;
char **kwds = WordListsToStrings(keywordlists);
char *ps = styler.GetProperties();
// The accessor passed in is always a DocumentAccessor so this cast and the subsequent
// access will work. Can not use the stricter dynamic_cast as that requires RTTI.
DocumentAccessor &da = static_cast<DocumentAccessor &>(styler);
WindowID wID = da.GetWindow();
fneFolder(externalLanguage, startPos, lengthDoc, initStyle, kwds, wID, ps);
delete ps;
DeleteWLStrings(kwds);
}
void ExternalLexerModule::SetExternal(ExtLexerFunction fLexer, ExtFoldFunction fFolder, int index) {
fneLexer = fLexer;
fneFolder = fFolder;
externalLanguage = index;
}
//------------------------------------------
//
// LexerLibrary
//
//------------------------------------------
LexerLibrary::LexerLibrary(const char* ModuleName) {
// Initialise some members...
first = NULL;
last = NULL;
// Load the DLL
lib = DynamicLibrary::Load(ModuleName);
if (lib->IsValid()) {
m_sModuleName = ModuleName;
//Cannot use reinterpret_cast because: ANSI C++ forbids casting between pointers to functions and objects
GetLexerCountFn GetLexerCount = (GetLexerCountFn)lib->FindFunction("GetLexerCount");
if (GetLexerCount) {
ExternalLexerModule *lex;
LexerMinder *lm;
// Find functions in the DLL
GetLexerNameFn GetLexerName = (GetLexerNameFn)lib->FindFunction("GetLexerName");
ExtLexerFunction Lexer = (ExtLexerFunction)lib->FindFunction("Lex");
ExtFoldFunction Folder = (ExtFoldFunction)lib->FindFunction("Fold");
// Assign a buffer for the lexer name.
char lexname[100];
strcpy(lexname, "");
int nl = GetLexerCount();
for (int i = 0; i < nl; i++) {
GetLexerName(i, lexname, 100);
lex = new ExternalLexerModule(SCLEX_AUTOMATIC, NULL, lexname, NULL);
// Create a LexerMinder so we don't leak the ExternalLexerModule...
lm = new LexerMinder;
lm->self = lex;
lm->next = NULL;
if (first != NULL) {
last->next = lm;
last = lm;
} else {
first = lm;
last = lm;
}
// The external lexer needs to know how to call into its DLL to
// do its lexing and folding, we tell it here. Folder may be null.
lex->SetExternal(Lexer, Folder, i);
}
}
}
next = NULL;
}
LexerLibrary::~LexerLibrary() {
Release();
delete lib;
}
void LexerLibrary::Release() {
//TODO maintain a list of lexers created, and delete them!
LexerMinder *lm;
LexerMinder *next;
lm = first;
while (NULL != lm) {
next = lm->next;
delete lm->self;
delete lm;
lm = next;
}
first = NULL;
last = NULL;
}
//------------------------------------------
//
// LexerManager
//
//------------------------------------------
/// Return the single LexerManager instance...
LexerManager *LexerManager::GetInstance() {
if(!theInstance)
theInstance = new LexerManager;
return theInstance;
}
/// Delete any LexerManager instance...
void LexerManager::DeleteInstance()
{
if(theInstance) {
delete theInstance;
theInstance = NULL;
}
}
/// protected constructor - this is a singleton...
LexerManager::LexerManager() {
first = NULL;
last = NULL;
}
LexerManager::~LexerManager() {
Clear();
}
void LexerManager::Load(const char* path)
{
LoadLexerLibrary(path);
}
void LexerManager::LoadLexerLibrary(const char* module)
{
LexerLibrary *lib = new LexerLibrary(module);
if (NULL != first) {
last->next = lib;
last = lib;
} else {
first = lib;
last = lib;
}
}
void LexerManager::Clear()
{
if (NULL != first) {
LexerLibrary *cur = first;
LexerLibrary *next;
while (cur) {
next = cur->next;
delete cur;
cur = next;
}
first = NULL;
last = NULL;
}
}
//------------------------------------------
//
// LexerManager
//
//------------------------------------------
LMMinder::~LMMinder()
{
LexerManager::DeleteInstance();
}
LMMinder minder;

View File

@@ -0,0 +1,91 @@
// Scintilla source code edit control
/** @file ExternalLexer.h
** Support external lexers in DLLs.
**/
// Copyright 2001 Simon Steele <ss@pnotepad.org>, portions copyright Neil Hodgson.
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef EXTERNALLEXER_H
#define EXTERNALLEXER_H
#define EXT_LEXER_DECL
// External Lexer function definitions...
typedef void (EXT_LEXER_DECL *ExtLexerFunction)(unsigned int lexer, unsigned int startPos, int length, int initStyle,
char *words[], WindowID window, char *props);
typedef void (EXT_LEXER_DECL *ExtFoldFunction)(unsigned int lexer, unsigned int startPos, int length, int initStyle,
char *words[], WindowID window, char *props);
typedef void* (EXT_LEXER_DECL *GetLexerFunction)(unsigned int Index);
typedef int (EXT_LEXER_DECL *GetLexerCountFn)();
typedef void (EXT_LEXER_DECL *GetLexerNameFn)(unsigned int Index, char *name, int buflength);
//class DynamicLibrary;
/// Sub-class of LexerModule to use an external lexer.
class ExternalLexerModule : protected LexerModule {
protected:
ExtLexerFunction fneLexer;
ExtFoldFunction fneFolder;
int externalLanguage;
char name[100];
public:
ExternalLexerModule(int language_, LexerFunction fnLexer_,
const char *languageName_=0, LexerFunction fnFolder_=0) : LexerModule(language_, fnLexer_, 0, fnFolder_){
strncpy(name, languageName_, sizeof(name));
languageName = name;
};
virtual void Lex(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const;
virtual void Fold(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const;
virtual void SetExternal(ExtLexerFunction fLexer, ExtFoldFunction fFolder, int index);
};
/// LexerMinder points to an ExternalLexerModule - so we don't leak them.
class LexerMinder {
public:
ExternalLexerModule *self;
LexerMinder *next;
};
/// LexerLibrary exists for every External Lexer DLL, contains LexerMinders.
class LexerLibrary {
DynamicLibrary *lib;
LexerMinder *first;
LexerMinder *last;
public:
LexerLibrary(const char* ModuleName);
~LexerLibrary();
void Release();
LexerLibrary *next;
SString m_sModuleName;
};
/// LexerManager manages external lexers, contains LexerLibrarys.
class LexerManager {
public:
~LexerManager();
static LexerManager *GetInstance();
static void DeleteInstance();
void Load(const char* path);
void Clear();
private:
LexerManager();
static LexerManager *theInstance;
void LoadLexerLibrary(const char* module);
LexerLibrary *first;
LexerLibrary *last;
};
class LMMinder {
public:
~LMMinder();
};
#endif

View File

@@ -0,0 +1,71 @@
// Scintilla source code edit control
/** @file Indicator.cxx
** Defines the style of indicators which are text decorations such as underlining.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "Scintilla.h"
#include "Indicator.h"
void Indicator::Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine) {
surface->PenColour(fore.allocated);
int ymid = (rc.bottom + rc.top) / 2;
if (style == INDIC_SQUIGGLE) {
surface->MoveTo(rc.left, rc.top);
int x = rc.left + 2;
int y = 2;
while (x < rc.right) {
surface->LineTo(x, rc.top + y);
x += 2;
y = 2 - y;
}
surface->LineTo(rc.right, rc.top + y); // Finish the line
} else if (style == INDIC_TT) {
surface->MoveTo(rc.left, ymid);
int x = rc.left + 5;
while (x < rc.right) {
surface->LineTo(x, ymid);
surface->MoveTo(x-3, ymid);
surface->LineTo(x-3, ymid+2);
x++;
surface->MoveTo(x, ymid);
x += 5;
}
surface->LineTo(rc.right, ymid); // Finish the line
if (x - 3 <= rc.right) {
surface->MoveTo(x-3, ymid);
surface->LineTo(x-3, ymid+2);
}
} else if (style == INDIC_DIAGONAL) {
int x = rc.left;
while (x < rc.right) {
surface->MoveTo(x, rc.top+2);
int endX = x+3;
int endY = rc.top - 1;
if (endX > rc.right) {
endY += endX - rc.right;
endX = rc.right;
}
surface->LineTo(endX, endY);
x += 4;
}
} else if (style == INDIC_STRIKE) {
surface->MoveTo(rc.left, rc.top - 4);
surface->LineTo(rc.right, rc.top - 4);
} else if (style == INDIC_HIDDEN) {
// Draw nothing
} else if (style == INDIC_BOX) {
surface->MoveTo(rc.left, ymid+1);
surface->LineTo(rc.right, ymid+1);
surface->LineTo(rc.right, rcLine.top+1);
surface->LineTo(rc.left, rcLine.top+1);
surface->LineTo(rc.left, ymid+1);
} else { // Either INDIC_PLAIN or unknown
surface->MoveTo(rc.left, ymid);
surface->LineTo(rc.right, ymid);
}
}

View File

@@ -0,0 +1,22 @@
// Scintilla source code edit control
/** @file Indicator.h
** Defines the style of indicators which are text decorations such as underlining.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef INDICATOR_H
#define INDICATOR_H
/**
*/
class Indicator {
public:
int style;
ColourPair fore;
Indicator() : style(INDIC_PLAIN), fore(ColourDesired(0,0,0)) {
}
void Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine);
};
#endif

View File

@@ -0,0 +1,148 @@
// Scintilla source code edit control
/** @file KeyMap.cxx
** Defines a mapping between keystrokes and commands.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "Scintilla.h"
#include "KeyMap.h"
KeyMap::KeyMap() : kmap(0), len(0), alloc(0) {
for (int i = 0; MapDefault[i].key; i++) {
AssignCmdKey(MapDefault[i].key,
MapDefault[i].modifiers,
MapDefault[i].msg);
}
}
KeyMap::~KeyMap() {
Clear();
}
void KeyMap::Clear() {
delete []kmap;
kmap = 0;
len = 0;
alloc = 0;
}
void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) {
if ((len+1) >= alloc) {
KeyToCommand *ktcNew = new KeyToCommand[alloc + 5];
if (!ktcNew)
return;
for (int k = 0; k < len; k++)
ktcNew[k] = kmap[k];
alloc += 5;
delete []kmap;
kmap = ktcNew;
}
for (int keyIndex = 0; keyIndex < len; keyIndex++) {
if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) {
kmap[keyIndex].msg = msg;
return;
}
}
kmap[len].key = key;
kmap[len].modifiers = modifiers;
kmap[len].msg = msg;
len++;
}
unsigned int KeyMap::Find(int key, int modifiers) {
for (int i = 0; i < len; i++) {
if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) {
return kmap[i].msg;
}
}
return 0;
}
const KeyToCommand KeyMap::MapDefault[] = {
{SCK_DOWN, SCI_NORM, SCI_LINEDOWN},
{SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND},
{SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN},
{SCK_DOWN, SCI_ASHIFT, SCI_LINEDOWNRECTEXTEND},
{SCK_UP, SCI_NORM, SCI_LINEUP},
{SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND},
{SCK_UP, SCI_CTRL, SCI_LINESCROLLUP},
{SCK_UP, SCI_ASHIFT, SCI_LINEUPRECTEXTEND},
{'[', SCI_CTRL, SCI_PARAUP},
{'[', SCI_CSHIFT, SCI_PARAUPEXTEND},
{']', SCI_CTRL, SCI_PARADOWN},
{']', SCI_CSHIFT, SCI_PARADOWNEXTEND},
{SCK_LEFT, SCI_NORM, SCI_CHARLEFT},
{SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND},
{SCK_LEFT, SCI_CTRL, SCI_WORDLEFT},
{SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND},
{SCK_LEFT, SCI_ASHIFT, SCI_CHARLEFTRECTEXTEND},
{SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT},
{SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND},
{SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT},
{SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND},
{SCK_RIGHT, SCI_ASHIFT, SCI_CHARRIGHTRECTEXTEND},
{'/', SCI_CTRL, SCI_WORDPARTLEFT},
{'/', SCI_CSHIFT, SCI_WORDPARTLEFTEXTEND},
{'\\', SCI_CTRL, SCI_WORDPARTRIGHT},
{'\\', SCI_CSHIFT, SCI_WORDPARTRIGHTEXTEND},
{SCK_HOME, SCI_NORM, SCI_VCHOME},
{SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND},
{SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART},
{SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND},
{SCK_HOME, SCI_ALT, SCI_HOMEDISPLAY},
// {SCK_HOME, SCI_ASHIFT, SCI_HOMEDISPLAYEXTEND},
{SCK_HOME, SCI_ASHIFT, SCI_VCHOMERECTEXTEND},
{SCK_END, SCI_NORM, SCI_LINEEND},
{SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND},
{SCK_END, SCI_CTRL, SCI_DOCUMENTEND},
{SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND},
{SCK_END, SCI_ALT, SCI_LINEENDDISPLAY},
// {SCK_END, SCI_ASHIFT, SCI_LINEENDDISPLAYEXTEND},
{SCK_END, SCI_ASHIFT, SCI_LINEENDRECTEXTEND},
{SCK_PRIOR, SCI_NORM, SCI_PAGEUP},
{SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND},
{SCK_PRIOR, SCI_ASHIFT, SCI_PAGEUPRECTEXTEND},
{SCK_NEXT, SCI_NORM, SCI_PAGEDOWN},
{SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND},
{SCK_NEXT, SCI_ASHIFT, SCI_PAGEDOWNRECTEXTEND},
{SCK_DELETE, SCI_NORM, SCI_CLEAR},
{SCK_DELETE, SCI_SHIFT, SCI_CUT},
{SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT},
{SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT},
{SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE},
{SCK_INSERT, SCI_SHIFT, SCI_PASTE},
{SCK_INSERT, SCI_CTRL, SCI_COPY},
{SCK_ESCAPE, SCI_NORM, SCI_CANCEL},
{SCK_BACK, SCI_NORM, SCI_DELETEBACK},
{SCK_BACK, SCI_SHIFT, SCI_DELETEBACK},
{SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT},
{SCK_BACK, SCI_ALT, SCI_UNDO},
{SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT},
{'Z', SCI_CTRL, SCI_UNDO},
{'Y', SCI_CTRL, SCI_REDO},
{'X', SCI_CTRL, SCI_CUT},
{'C', SCI_CTRL, SCI_COPY},
{'V', SCI_CTRL, SCI_PASTE},
{'A', SCI_CTRL, SCI_SELECTALL},
{SCK_TAB, SCI_NORM, SCI_TAB},
{SCK_TAB, SCI_SHIFT, SCI_BACKTAB},
{SCK_RETURN, SCI_NORM, SCI_NEWLINE},
{SCK_RETURN, SCI_SHIFT, SCI_NEWLINE},
{SCK_ADD, SCI_CTRL, SCI_ZOOMIN},
{SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT},
{SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM},
//'L', SCI_CTRL, SCI_FORMFEED,
{'L', SCI_CTRL, SCI_LINECUT},
{'L', SCI_CSHIFT, SCI_LINEDELETE},
{'T', SCI_CSHIFT, SCI_LINECOPY},
{'T', SCI_CTRL, SCI_LINETRANSPOSE},
{'D', SCI_CTRL, SCI_SELECTIONDUPLICATE},
{'U', SCI_CTRL, SCI_LOWERCASE},
{'U', SCI_CSHIFT, SCI_UPPERCASE},
{0,0,0},
};

View File

@@ -0,0 +1,43 @@
// Scintilla source code edit control
/** @file KeyMap.h
** Defines a mapping between keystrokes and commands.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef KEYTOCOMMAND_H
#define KEYTOCOMMAND_H
#define SCI_NORM 0
#define SCI_SHIFT SCMOD_SHIFT
#define SCI_CTRL SCMOD_CTRL
#define SCI_ALT SCMOD_ALT
#define SCI_CSHIFT (SCI_CTRL | SCI_SHIFT)
#define SCI_ASHIFT (SCI_ALT | SCI_SHIFT)
/**
*/
class KeyToCommand {
public:
int key;
int modifiers;
unsigned int msg;
};
/**
*/
class KeyMap {
KeyToCommand *kmap;
int len;
int alloc;
static const KeyToCommand MapDefault[];
public:
KeyMap();
~KeyMap();
void Clear();
void AssignCmdKey(int key, int modifiers, unsigned int msg);
unsigned int Find(int key, int modifiers); // 0 returned on failure
};
#endif

View File

@@ -0,0 +1,142 @@
// Scintilla source code edit control
/** @file KeyWords.cxx
** Colourise for particular languages.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
const LexerModule *LexerModule::base = 0;
int LexerModule::nextLanguage = SCLEX_AUTOMATIC+1;
LexerModule::LexerModule(int language_,
LexerFunction fnLexer_,
const char *languageName_,
LexerFunction fnFolder_,
const char * const wordListDescriptions_[],
int styleBits_) :
language(language_),
fnLexer(fnLexer_),
fnFolder(fnFolder_),
wordListDescriptions(wordListDescriptions_),
styleBits(styleBits_),
languageName(languageName_) {
next = base;
base = this;
if (language == SCLEX_AUTOMATIC) {
language = nextLanguage;
nextLanguage++;
}
}
int LexerModule::GetNumWordLists() const {
if (wordListDescriptions == NULL) {
return -1;
} else {
int numWordLists = 0;
while (wordListDescriptions[numWordLists]) {
++numWordLists;
}
return numWordLists;
}
}
const char *LexerModule::GetWordListDescription(int index) const {
static const char *emptyStr = "";
PLATFORM_ASSERT(index < GetNumWordLists());
if (index >= GetNumWordLists()) {
return emptyStr;
} else {
return wordListDescriptions[index];
}
}
int LexerModule::GetStyleBitsNeeded() const {
return styleBits;
}
const LexerModule *LexerModule::Find(int language) {
const LexerModule *lm = base;
while (lm) {
if (lm->language == language) {
return lm;
}
lm = lm->next;
}
return 0;
}
const LexerModule *LexerModule::Find(const char *languageName) {
if (languageName) {
const LexerModule *lm = base;
while (lm) {
if (lm->languageName && 0 == strcmp(lm->languageName, languageName)) {
return lm;
}
lm = lm->next;
}
}
return 0;
}
void LexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (fnLexer)
fnLexer(startPos, lengthDoc, initStyle, keywordlists, styler);
}
void LexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (fnFolder) {
int lineCurrent = styler.GetLine(startPos);
// Move back one line in case deletion wrecked current line fold state
if (lineCurrent > 0) {
lineCurrent--;
int newStartPos = styler.LineStart(lineCurrent);
lengthDoc += startPos - newStartPos;
startPos = newStartPos;
initStyle = 0;
if (startPos > 0) {
initStyle = styler.StyleAt(startPos - 1);
}
}
fnFolder(startPos, lengthDoc, initStyle, keywordlists, styler);
}
}
// Alternative historical name for Scintilla_LinkLexers
int wxForceScintillaLexers(void) {
return Scintilla_LinkLexers();
}
// To add or remove a lexer, add or remove its file and run LexGen.py.
// Force a reference to all of the Scintilla lexers so that the linker will
// not remove the code of the lexers.
int Scintilla_LinkLexers() {
static int forcer = 0;
// Shorten the code that declares a lexer and ensures it is linked in by calling a method.
#define LINK_LEXER(lexer) extern LexerModule lexer; forcer += lexer.GetLanguage();
//++Autogenerated -- run src/LexGen.py to regenerate
//**\(\tLINK_LEXER(\*);\n\)
LINK_LEXER(lmAppArmor);
return 1;
}

View File

@@ -0,0 +1,82 @@
// Scintilla source code edit control
/** @file KeyWords.h
** Colourise for particular languages.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
typedef void (*LexerFunction)(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler);
/**
* A LexerModule is responsible for lexing and folding a particular language.
* The class maintains a list of LexerModules which can be searched to find a
* module appropriate to a particular language.
*/
class LexerModule {
protected:
const LexerModule *next;
int language;
LexerFunction fnLexer;
LexerFunction fnFolder;
const char * const * wordListDescriptions;
int styleBits;
static const LexerModule *base;
static int nextLanguage;
public:
const char *languageName;
LexerModule(int language_,
LexerFunction fnLexer_,
const char *languageName_=0,
LexerFunction fnFolder_=0,
const char * const wordListDescriptions_[] = NULL,
int styleBits_=5);
virtual ~LexerModule() {
}
int GetLanguage() const { return language; }
// -1 is returned if no WordList information is available
int GetNumWordLists() const;
const char *GetWordListDescription(int index) const;
int GetStyleBitsNeeded() const;
virtual void Lex(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const;
virtual void Fold(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const;
static const LexerModule *Find(int language);
static const LexerModule *Find(const char *languageName);
};
/**
* Check if a character is a space.
* This is ASCII specific but is safe with chars >= 0x80.
*/
inline bool isspacechar(unsigned char ch) {
return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d));
}
inline bool iswordchar(char ch) {
return isascii(ch) && (isalnum(ch) || ch == '.' || ch == '_');
}
inline bool iswordstart(char ch) {
return isascii(ch) && (isalnum(ch) || ch == '_');
}
inline bool isoperator(char ch) {
if (isascii(ch) && isalnum(ch))
return false;
// '.' left out as it is used to make up numbers
if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
ch == '(' || ch == ')' || ch == '-' || ch == '+' ||
ch == '=' || ch == '|' || ch == '{' || ch == '}' ||
ch == '[' || ch == ']' || ch == ':' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' || ch == '/' ||
ch == '?' || ch == '!' || ch == '.' || ch == '~')
return true;
return false;
}

View File

@@ -0,0 +1,189 @@
// Scintilla source code edit control
/** @file LexOthers.cxx
** Lexers for batch files, diff results, properties files, make files and error lists.
** Also lexer for LaTeX documents.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "StyleContext.h"
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static void ColouriseAppArmorDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler)
{
initStyle = SCE_APPARMOR_DEFAULT;
int stateHash = 19;
int stateCap = 20;
int pathSpaceAllowed = 0;
int pathQuoteCount = 0;
int chPrevNonWhite = ' ';
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
// Handle line continuation
if (sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Reset the states if we need to
if (sc.state == SCE_APPARMOR_PATH) {
if (sc.ch == '\"') {
if (pathQuoteCount == 1) {
// This is the end of a quote
pathQuoteCount = 0;
sc.ForwardSetState(SCE_APPARMOR_DEFAULT);
} else {
pathQuoteCount = 1;
sc.Forward();
sc.SetState(SCE_APPARMOR_PATH);
}
} else if ((sc.ch == ' ') || (sc.ch == '\t')) {
if (pathSpaceAllowed == 1) {
pathSpaceAllowed = 0;
sc.ForwardSetState(SCE_APPARMOR_PATH);
} else if (pathQuoteCount == 1) {
pathSpaceAllowed = 0;
sc.ForwardSetState(SCE_APPARMOR_PATH);
} else {
sc.SetState(SCE_APPARMOR_PATH_TRANSITION);
}
} else if (sc.ch == '\\') {
pathSpaceAllowed = 1;
sc.SetState(SCE_APPARMOR_PATH);
}
}
else if (sc.state == stateHash) {
if (!IsAWordChar(sc.ch)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (strcmp(s, "#include") == 0) {
sc.ChangeState(SCE_APPARMOR_INCLUDE);
} else {
sc.ChangeState(SCE_APPARMOR_COMMENT);
}
}
} else if (sc.state == stateCap) {
if (!IsAWordChar(sc.ch)) {
char t[100];
sc.GetCurrentLowered(t, sizeof(t));
if (strcmp(t, "capability") == 0) {
sc.ChangeState(SCE_APPARMOR_CAPABILITY);
}
sc.SetState(SCE_APPARMOR_DEFAULT);
}
} else if (sc.state == SCE_APPARMOR_INCLUDE) {
if (sc.ch == '\r' || sc.ch == '\n') {
sc.ForwardSetState(SCE_APPARMOR_DEFAULT);
}
} else if (sc.state == SCE_APPARMOR_COMMENT) {
if (sc.ch == '\r' || sc.ch == '\n') {
sc.ForwardSetState(SCE_APPARMOR_DEFAULT);
} else if (sc.atLineStart) {
sc.SetState(SCE_APPARMOR_DEFAULT);
} else {
sc.ForwardSetState(SCE_APPARMOR_COMMENT);
}
} else if (sc.state == SCE_APPARMOR_PATH_TRANSITION) {
if (sc.ch == 'r'
|| sc.ch == 'w'
|| sc.ch == 'l'
|| sc.ch == 'x'
|| sc.ch == 'p'
|| sc.ch == 'u'
|| sc.ch == 'i'
|| sc.ch == 'm'
|| sc.ch == 'W'
|| sc.ch == 'R'
|| sc.ch == 'X'
|| sc.ch == 'L'
|| sc.ch == 'M'
|| sc.ch == 'P'
|| sc.ch == 'U'
|| sc.ch == 'I'
|| sc.ch == ',') {
sc.SetState(SCE_APPARMOR_PERMS);
} else if (sc.ch == ' ' || sc.ch == '\t') {
sc.SetState(SCE_APPARMOR_PATH_TRANSITION);
} else {
sc.SetState (SCE_APPARMOR_DEFAULT);
}
} else if (sc.state == SCE_APPARMOR_PERMS) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '{') {
sc.SetState(SCE_APPARMOR_DEFAULT);
}
}
// See if we need to enter a new state
if (sc.state == SCE_APPARMOR_DEFAULT) {
if (sc.ch == '#') {
if (sc.chNext == ' ') {
// This'll have to be a comment
sc.SetState(SCE_APPARMOR_COMMENT);
} else {
sc.SetState(stateHash);
}
} else if (sc.ch == '/') {
sc.SetState(SCE_APPARMOR_PATH);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(stateCap);
} else if (sc.ch == '\"') {
if (sc.chNext == '/') {
pathQuoteCount = 1;
sc.SetState(SCE_APPARMOR_PATH);
}
}
}
if (sc.atLineEnd) {
chPrevNonWhite = ' ';
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
}
}
sc.Complete();
}
static const char * const appArmorWordListDesc[] = {
"Keywords",
0
};
LexerModule lmAppArmor(SCLEX_APPARMOR, ColouriseAppArmorDoc, "apparmor", 0, appArmorWordListDesc);

View File

@@ -0,0 +1,301 @@
// Scintilla source code edit control
/** @file LineMarker.cxx
** Defines the look of a line marker in the margin .
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include "Platform.h"
#include "Scintilla.h"
#include "XPM.h"
#include "LineMarker.h"
void LineMarker::RefreshColourPalette(Palette &pal, bool want) {
pal.WantFind(fore, want);
pal.WantFind(back, want);
if (pxpm) {
pxpm->RefreshColourPalette(pal, want);
}
}
void LineMarker::SetXPM(const char *textForm) {
delete pxpm;
pxpm = new XPM(textForm);
markType = SC_MARK_PIXMAP;
}
void LineMarker::SetXPM(const char * const *linesForm) {
delete pxpm;
pxpm = new XPM(linesForm);
markType = SC_MARK_PIXMAP;
}
static void DrawBox(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rc;
rc.left = centreX - armSize;
rc.top = centreY - armSize;
rc.right = centreX + armSize + 1;
rc.bottom = centreY + armSize + 1;
surface->RectangleDraw(rc, back, fore);
}
static void DrawCircle(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore, ColourAllocated back) {
PRectangle rcCircle;
rcCircle.left = centreX - armSize;
rcCircle.top = centreY - armSize;
rcCircle.right = centreX + armSize + 1;
rcCircle.bottom = centreY + armSize + 1;
surface->Ellipse(rcCircle, back, fore);
}
static void DrawPlus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcV(centreX, centreY - armSize + 2, centreX + 1, centreY + armSize - 2 + 1);
surface->FillRectangle(rcV, fore);
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize, ColourAllocated fore) {
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
void LineMarker::Draw(Surface *surface, PRectangle &rcWhole, Font &fontForCharacter) {
if ((markType == SC_MARK_PIXMAP) && (pxpm)) {
pxpm->Draw(surface, rcWhole);
return;
}
// Restrict most shapes a bit
PRectangle rc = rcWhole;
rc.top++;
rc.bottom--;
int minDim = Platform::Minimum(rc.Width(), rc.Height());
minDim--; // Ensure does not go beyond edge
int centreX = (rc.right + rc.left) / 2;
int centreY = (rc.bottom + rc.top) / 2;
int dimOn2 = minDim / 2;
int dimOn4 = minDim / 4;
int blobSize = dimOn2-1;
int armSize = dimOn2-2;
if (rc.Width() > (rc.Height() * 2)) {
// Wide column is line number so move to left to try to avoid overlapping number
centreX = rc.left + dimOn2 + 1;
}
if (markType == SC_MARK_ROUNDRECT) {
PRectangle rcRounded = rc;
rcRounded.left = rc.left + 1;
rcRounded.right = rc.right - 1;
surface->RoundedRectangle(rcRounded, fore.allocated, back.allocated);
} else if (markType == SC_MARK_CIRCLE) {
PRectangle rcCircle;
rcCircle.left = centreX - dimOn2;
rcCircle.top = centreY - dimOn2;
rcCircle.right = centreX + dimOn2;
rcCircle.bottom = centreY + dimOn2;
surface->Ellipse(rcCircle, fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROW) {
Point pts[] = {
Point(centreX - dimOn4, centreY - dimOn2),
Point(centreX - dimOn4, centreY + dimOn2),
Point(centreX + dimOn2 - dimOn4, centreY),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROWDOWN) {
Point pts[] = {
Point(centreX - dimOn2, centreY - dimOn4),
Point(centreX + dimOn2, centreY - dimOn4),
Point(centreX, centreY + dimOn2 - dimOn4),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_PLUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX - 1, centreY - 1),
Point(centreX - 1, centreY - armSize),
Point(centreX + 1, centreY - armSize),
Point(centreX + 1, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX + 1, centreY + 1),
Point(centreX + 1, centreY + armSize),
Point(centreX - 1, centreY + armSize),
Point(centreX - 1, centreY + 1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_MINUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_SMALLRECT) {
PRectangle rcSmall;
rcSmall.left = rc.left + 1;
rcSmall.top = rc.top + 2;
rcSmall.right = rc.right - 1;
rcSmall.bottom = rc.bottom - 2;
surface->RectangleDraw(rcSmall, fore.allocated, back.allocated);
} else if (markType == SC_MARK_EMPTY || markType == SC_MARK_BACKGROUND) {
// An invisible marker so don't draw anything
} else if (markType == SC_MARK_VLINE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_LCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_LCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_BOXPLUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_BOXPLUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_BOXMINUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_BOXMINUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEPLUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_CIRCLEPLUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEMINUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType >= SC_MARK_CHARACTER) {
char character[1];
character[0] = static_cast<char>(markType - SC_MARK_CHARACTER);
int width = surface->WidthText(fontForCharacter, character, 1);
rc.left += (rc.Width() - width) / 2;
rc.right = rc.left + width;
surface->DrawTextClipped(rc, fontForCharacter, rc.bottom - 2,
character, 1, fore.allocated, back.allocated);
} else if (markType == SC_MARK_DOTDOTDOT) {
int right = centreX - 6;
for (int b=0; b<3; b++) {
PRectangle rcBlob(right, rc.bottom - 4, right + 2, rc.bottom-2);
surface->FillRectangle(rcBlob, fore.allocated);
right += 5;
}
} else if (markType == SC_MARK_ARROWS) {
surface->PenColour(fore.allocated);
int right = centreX - 2;
for (int b=0; b<3; b++) {
surface->MoveTo(right - 4, centreY - 4);
surface->LineTo(right, centreY);
surface->LineTo(right - 5, centreY + 5);
right += 4;
}
} else if (markType == SC_MARK_SHORTARROW) {
Point pts[] = {
Point(centreX, centreY + dimOn2),
Point(centreX + dimOn2, centreY),
Point(centreX, centreY - dimOn2),
Point(centreX, centreY - dimOn4),
Point(centreX - dimOn4, centreY - dimOn4),
Point(centreX - dimOn4, centreY + dimOn4),
Point(centreX, centreY + dimOn4),
Point(centreX, centreY + dimOn2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else { // SC_MARK_FULLRECT
surface->FillRectangle(rcWhole, back.allocated);
}
}

View File

@@ -0,0 +1,50 @@
// Scintilla source code edit control
/** @file LineMarker.h
** Defines the look of a line marker in the margin .
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef LINEMARKER_H
#define LINEMARKER_H
/**
*/
class LineMarker {
public:
int markType;
ColourPair fore;
ColourPair back;
XPM *pxpm;
LineMarker() {
markType = SC_MARK_CIRCLE;
fore = ColourDesired(0,0,0);
back = ColourDesired(0xff,0xff,0xff);
pxpm = NULL;
}
LineMarker(const LineMarker &) {
// Defined to avoid pxpm being blindly copied, not as real copy constructor
markType = SC_MARK_CIRCLE;
fore = ColourDesired(0,0,0);
back = ColourDesired(0xff,0xff,0xff);
pxpm = NULL;
}
~LineMarker() {
delete pxpm;
}
LineMarker &operator=(const LineMarker &) {
// Defined to avoid pxpm being blindly copied, not as real assignment operator
markType = SC_MARK_CIRCLE;
fore = ColourDesired(0,0,0);
back = ColourDesired(0xff,0xff,0xff);
delete pxpm;
pxpm = NULL;
return *this;
}
void RefreshColourPalette(Palette &pal, bool want);
void SetXPM(const char *textForm);
void SetXPM(const char * const *linesForm);
void Draw(Surface *surface, PRectangle &rc, Font &fontForCharacter);
};
#endif

View File

@@ -0,0 +1,19 @@
METASOURCES = AUTO
noinst_LIBRARIES = libAppArmorStyledTextCtrl.a
libAppArmorStyledTextCtrl_a_SOURCES = AutoComplete.cxx CallTip.cxx \
CellBuffer.cxx ContractionState.cxx DocumentAccessor.cxx Document.cxx Editor.cxx \
ExternalLexer.cxx Indicator.cxx KeyMap.cxx KeyWords.cxx LineMarker.cxx PlatWX.cpp \
PropSet.cxx RESearch.cxx ScintillaBase.cxx ScintillaWX.cpp stc.cpp StyleContext.cxx \
Style.cxx UniConversion.cxx ViewStyle.cxx WindowAccessor.cxx XPM.cxx \
LexAppArmor.cxx
noinst_HEADERS = Accessor.h AutoComplete.h CallTip.h CellBuffer.h \
ContractionState.h DocumentAccessor.h Document.h Editor.h ExternalLexer.h Indicator.h \
KeyMap.h KeyWords.h LineMarker.h Platform.h PlatWX.h PropSet.h RESearch.h \
SciLexer.h ScintillaBase.h Scintilla.h ScintillaWidget.h ScintillaWX.h SString.h \
stc_cwc_d.h stc_cwc.h stc_cw_d.h stc_cw.h stc.h StyleContext.h Style.h SVector.h \
UniConversion.h ViewStyle.h WindowAccessor.h XPM.h
AM_CFLAGS = -DSCI_LEXER -DLINK_LEXERS -fPIC -DPIC -DWX_PRECOMP -DNO_GCC_PRAGMA \
-D__WXGTK__ -D__WX__
AM_CXXFLAGS = -DSCI_LEXER -DLINK_LEXERS -fPIC -DPIC -DWX_PRECOMP -DNO_GCC_PRAGMA

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
wxRect wxRectFromPRectangle(PRectangle prc);
PRectangle PRectangleFromwxRect(wxRect rc);
wxColour wxColourFromCA(const ColourAllocated& ca);

View File

@@ -0,0 +1,506 @@
// Scintilla source code edit control
/** @file Platform.h
** Interface to platform facilities. Also includes some basic utilities.
** Implemented in PlatGTK.cxx for GTK+/Linux, PlatWin.cxx for Windows, and PlatWX.cxx for wxWidgets.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef PLATFORM_H
#define PLATFORM_H
// PLAT_GTK = GTK+ on Linux or Win32
// PLAT_GTK_WIN32 is defined additionally when running PLAT_GTK under Win32
// PLAT_WIN = Win32 API on Win32 OS
// PLAT_WX is wxWidgets on any supported platform
#define PLAT_GTK 0
#define PLAT_GTK_WIN32 0
#define PLAT_WIN 0
#define PLAT_WX 0
#define PLAT_FOX 0
#if defined(FOX)
#undef PLAT_FOX
#define PLAT_FOX 1
#elif defined(__WX__)
#undef PLAT_WX
#define PLAT_WX 1
#elif defined(GTK)
#undef PLAT_GTK
#define PLAT_GTK 1
#ifdef _MSC_VER
#undef PLAT_GTK_WIN32
#define PLAT_GTK_WIN32 1
#endif
#else
#undef PLAT_WIN
#define PLAT_WIN 1
#endif
// Underlying the implementation of the platform classes are platform specific types.
// Sometimes these need to be passed around by client code so they are defined here
typedef void *FontID;
typedef void *SurfaceID;
typedef void *WindowID;
typedef void *MenuID;
typedef void *TickerID;
typedef void *Function;
typedef void *IdlerID;
/**
* A geometric point class.
* Point is exactly the same as the Win32 POINT and GTK+ GdkPoint so can be used interchangeably.
*/
class Point {
public:
int x;
int y;
explicit Point(int x_=0, int y_=0) : x(x_), y(y_) {
}
// Other automatically defined methods (assignment, copy constructor, destructor) are fine
static Point FromLong(long lpoint);
};
/**
* A geometric rectangle class.
* PRectangle is exactly the same as the Win32 RECT so can be used interchangeably.
* PRectangles contain their top and left sides, but not their right and bottom sides.
*/
class PRectangle {
public:
int left;
int top;
int right;
int bottom;
PRectangle(int left_=0, int top_=0, int right_=0, int bottom_ = 0) :
left(left_), top(top_), right(right_), bottom(bottom_) {
}
// Other automatically defined methods (assignment, copy constructor, destructor) are fine
bool operator==(PRectangle &rc) {
return (rc.left == left) && (rc.right == right) &&
(rc.top == top) && (rc.bottom == bottom);
}
bool Contains(Point pt) {
return (pt.x >= left) && (pt.x <= right) &&
(pt.y >= top) && (pt.y <= bottom);
}
bool Contains(PRectangle rc) {
return (rc.left >= left) && (rc.right <= right) &&
(rc.top >= top) && (rc.bottom <= bottom);
}
bool Intersects(PRectangle other) {
return (right > other.left) && (left < other.right) &&
(bottom > other.top) && (top < other.bottom);
}
void Move(int xDelta, int yDelta) {
left += xDelta;
top += yDelta;
right += xDelta;
bottom += yDelta;
}
int Width() { return right - left; }
int Height() { return bottom - top; }
};
/**
* In some circumstances, including Win32 in paletted mode and GTK+, each colour
* must be allocated before use. The desired colours are held in the ColourDesired class,
* and after allocation the allocation entry is stored in the ColourAllocated class. In other
* circumstances, such as Win32 in true colour mode, the allocation process just copies
* the RGB values from the desired to the allocated class.
* As each desired colour requires allocation before it can be used, the ColourPair class
* holds both a ColourDesired and a ColourAllocated
* The Palette class is responsible for managing the palette of colours which contains a
* list of ColourPair objects and performs the allocation.
*/
/**
* Holds a desired RGB colour.
*/
class ColourDesired {
long co;
public:
ColourDesired(long lcol=0) {
co = lcol;
}
ColourDesired(unsigned int red, unsigned int green, unsigned int blue) {
Set(red, green, blue);
}
bool operator==(const ColourDesired &other) const {
return co == other.co;
}
void Set(long lcol) {
co = lcol;
}
void Set(unsigned int red, unsigned int green, unsigned int blue) {
co = red | (green << 8) | (blue << 16);
}
static inline unsigned int ValueOfHex(const char ch) {
if (ch >= '0' && ch <= '9')
return ch - '0';
else if (ch >= 'A' && ch <= 'F')
return ch - 'A' + 10;
else if (ch >= 'a' && ch <= 'f')
return ch - 'a' + 10;
else
return 0;
}
void Set(const char *val) {
if (*val == '#') {
val++;
}
unsigned int r = ValueOfHex(val[0]) * 16 + ValueOfHex(val[1]);
unsigned int g = ValueOfHex(val[2]) * 16 + ValueOfHex(val[3]);
unsigned int b = ValueOfHex(val[4]) * 16 + ValueOfHex(val[5]);
Set(r, g, b);
}
long AsLong() const {
return co;
}
unsigned int GetRed() {
return co & 0xff;
}
unsigned int GetGreen() {
return (co >> 8) & 0xff;
}
unsigned int GetBlue() {
return (co >> 16) & 0xff;
}
};
/**
* Holds an allocated RGB colour which may be an approximation to the desired colour.
*/
class ColourAllocated {
long coAllocated;
public:
ColourAllocated(long lcol=0) {
coAllocated = lcol;
}
void Set(long lcol) {
coAllocated = lcol;
}
long AsLong() const {
return coAllocated;
}
};
/**
* Colour pairs hold a desired colour and an allocated colour.
*/
struct ColourPair {
ColourDesired desired;
ColourAllocated allocated;
ColourPair(ColourDesired desired_=ColourDesired(0,0,0)) {
desired = desired_;
allocated.Set(desired.AsLong());
}
void Copy() {
allocated.Set(desired.AsLong());
}
};
class Window; // Forward declaration for Palette
/**
* Colour palette management.
*/
class Palette {
int used;
enum {numEntries = 100};
ColourPair entries[numEntries];
void *allocatedPalette; // GdkColor *
int allocatedLen;
public:
bool allowRealization;
Palette();
~Palette();
void Release();
/**
* This method either adds a colour to the list of wanted colours (want==true)
* or retrieves the allocated colour back to the ColourPair.
* This is one method to make it easier to keep the code for wanting and retrieving in sync.
*/
void WantFind(ColourPair &cp, bool want);
void Allocate(Window &w);
};
/**
* Font management.
*/
class Font {
protected:
FontID id;
int ascent;
// Private so Font objects can not be copied
Font(const Font &) {}
Font &operator=(const Font &) { id=0; return *this; }
public:
Font();
virtual ~Font();
virtual void Create(const char *faceName, int characterSet, int size,
bool bold, bool italic, bool extraFontFlag=false);
virtual void Release();
FontID GetID() { return id; }
// Alias another font - caller guarantees not to Release
void SetID(FontID id_) { id = id_; }
friend class Surface;
friend class SurfaceImpl;
};
/**
* A surface abstracts a place to draw.
*/
class Surface {
private:
// Private so Surface objects can not be copied
Surface(const Surface &) {}
Surface &operator=(const Surface &) { return *this; }
public:
Surface() {};
virtual ~Surface() {};
static Surface *Allocate();
virtual void Init(WindowID wid)=0;
virtual void Init(SurfaceID sid, WindowID wid)=0;
virtual void InitPixMap(int width, int height, Surface *surface_, WindowID wid)=0;
virtual void Release()=0;
virtual bool Initialised()=0;
virtual void PenColour(ColourAllocated fore)=0;
virtual int LogPixelsY()=0;
virtual int DeviceHeightFont(int points)=0;
virtual void MoveTo(int x_, int y_)=0;
virtual void LineTo(int x_, int y_)=0;
virtual void Polygon(Point *pts, int npts, ColourAllocated fore, ColourAllocated back)=0;
virtual void RectangleDraw(PRectangle rc, ColourAllocated fore, ColourAllocated back)=0;
virtual void FillRectangle(PRectangle rc, ColourAllocated back)=0;
virtual void FillRectangle(PRectangle rc, Surface &surfacePattern)=0;
virtual void RoundedRectangle(PRectangle rc, ColourAllocated fore, ColourAllocated back)=0;
virtual void Ellipse(PRectangle rc, ColourAllocated fore, ColourAllocated back)=0;
virtual void Copy(PRectangle rc, Point from, Surface &surfaceSource)=0;
virtual void DrawTextNoClip(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back)=0;
virtual void DrawTextClipped(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back)=0;
virtual void DrawTextTransparent(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore)=0;
virtual void MeasureWidths(Font &font_, const char *s, int len, int *positions)=0;
virtual int WidthText(Font &font_, const char *s, int len)=0;
virtual int WidthChar(Font &font_, char ch)=0;
virtual int Ascent(Font &font_)=0;
virtual int Descent(Font &font_)=0;
virtual int InternalLeading(Font &font_)=0;
virtual int ExternalLeading(Font &font_)=0;
virtual int Height(Font &font_)=0;
virtual int AverageCharWidth(Font &font_)=0;
virtual int SetPalette(Palette *pal, bool inBackGround)=0;
virtual void SetClip(PRectangle rc)=0;
virtual void FlushCachedState()=0;
virtual void SetUnicodeMode(bool unicodeMode_)=0;
virtual void SetDBCSMode(int codePage)=0;
};
/**
* A simple callback action passing one piece of untyped user data.
*/
typedef void (*CallBackAction)(void*);
/**
* Class to hide the details of window manipulation.
* Does not own the window which will normally have a longer life than this object.
*/
class Window {
protected:
WindowID id;
public:
Window() : id(0), cursorLast(cursorInvalid) {}
Window(const Window &source) : id(source.id), cursorLast(cursorInvalid) {}
virtual ~Window();
Window &operator=(WindowID id_) {
id = id_;
return *this;
}
WindowID GetID() const { return id; }
bool Created() const { return id != 0; }
void Destroy();
bool HasFocus();
PRectangle GetPosition();
void SetPosition(PRectangle rc);
void SetPositionRelative(PRectangle rc, Window relativeTo);
PRectangle GetClientPosition();
void Show(bool show=true);
void InvalidateAll();
void InvalidateRectangle(PRectangle rc);
virtual void SetFont(Font &font);
enum Cursor { cursorInvalid, cursorText, cursorArrow, cursorUp, cursorWait, cursorHoriz, cursorVert, cursorReverseArrow, cursorHand };
void SetCursor(Cursor curs);
void SetTitle(const char *s);
private:
Cursor cursorLast;
};
/**
* Listbox management.
*/
class ListBox : public Window {
public:
ListBox();
virtual ~ListBox();
static ListBox *Allocate();
virtual void SetFont(Font &font)=0;
virtual void Create(Window &parent, int ctrlID, Point location, int lineHeight_, bool unicodeMode_)=0;
virtual void SetAverageCharWidth(int width)=0;
virtual void SetVisibleRows(int rows)=0;
virtual int GetVisibleRows() const=0;
virtual PRectangle GetDesiredRect()=0;
virtual int CaretFromEdge()=0;
virtual void Clear()=0;
virtual void Append(char *s, int type = -1)=0;
virtual int Length()=0;
virtual void Select(int n)=0;
virtual int GetSelection()=0;
virtual int Find(const char *prefix)=0;
virtual void GetValue(int n, char *value, int len)=0;
virtual void RegisterImage(int type, const char *xpm_data)=0;
virtual void ClearRegisteredImages()=0;
virtual void SetDoubleClickAction(CallBackAction, void *)=0;
virtual void SetList(const char* list, char separator, char typesep)=0;
};
/**
* Menu management.
*/
class Menu {
MenuID id;
public:
Menu();
MenuID GetID() { return id; }
void CreatePopUp();
void Destroy();
void Show(Point pt, Window &w);
};
class ElapsedTime {
long bigBit;
long littleBit;
public:
ElapsedTime();
double Duration(bool reset=false);
};
/**
* Dynamic Library (DLL/SO/...) loading
*/
class DynamicLibrary {
public:
virtual ~DynamicLibrary() {};
/// @return Pointer to function "name", or NULL on failure.
virtual Function FindFunction(const char *name) = 0;
/// @return true if the library was loaded successfully.
virtual bool IsValid() = 0;
/// @return An instance of a DynamicLibrary subclass with "modulePath" loaded.
static DynamicLibrary *Load(const char *modulePath);
};
/**
* Platform class used to retrieve system wide parameters such as double click speed
* and chrome colour. Not a creatable object, more of a module with several functions.
*/
class Platform {
// Private so Platform objects can not be copied
Platform(const Platform &) {}
Platform &operator=(const Platform &) { return *this; }
public:
// Should be private because no new Platforms are ever created
// but gcc warns about this
Platform() {}
~Platform() {}
static ColourDesired Chrome();
static ColourDesired ChromeHighlight();
static const char *DefaultFont();
static int DefaultFontSize();
static unsigned int DoubleClickTime();
static bool MouseButtonBounce();
static void DebugDisplay(const char *s);
static bool IsKeyDown(int key);
static long SendScintilla(
WindowID w, unsigned int msg, unsigned long wParam=0, long lParam=0);
static long SendScintillaPointer(
WindowID w, unsigned int msg, unsigned long wParam=0, void *lParam=0);
static bool IsDBCSLeadByte(int codePage, char ch);
static int DBCSCharLength(int codePage, const char *s);
static int DBCSCharMaxLength();
// These are utility functions not really tied to a platform
static int Minimum(int a, int b);
static int Maximum(int a, int b);
// Next three assume 16 bit shorts and 32 bit longs
static long LongFromTwoShorts(short a,short b) {
return (a) | ((b) << 16);
}
static short HighShortFromLong(long x) {
return static_cast<short>(x >> 16);
}
static short LowShortFromLong(long x) {
return static_cast<short>(x & 0xffff);
}
static void DebugPrintf(const char *format, ...);
static bool ShowAssertionPopUps(bool assertionPopUps_);
static void Assert(const char *c, const char *file, int line);
static int Clamp(int val, int minVal, int maxVal);
};
#ifdef NDEBUG
#define PLATFORM_ASSERT(c) ((void)0)
#else
#define PLATFORM_ASSERT(c) ((c) ? (void)(0) : Platform::Assert(#c, __FILE__, __LINE__))
#endif
// Shut up annoying Visual C++ warnings:
#ifdef _MSC_VER
#pragma warning(disable: 4244 4309 4514 4710)
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,114 @@
// Scintilla source code edit control
/** @file PropSet.h
** A Java style properties file module.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef PROPSET_H
#define PROPSET_H
#include "SString.h"
bool EqualCaseInsensitive(const char *a, const char *b);
bool isprefix(const char *target, const char *prefix);
struct Property {
unsigned int hash;
char *key;
char *val;
Property *next;
Property() : hash(0), key(0), val(0), next(0) {}
};
/**
*/
class PropSet {
protected:
enum { hashRoots=31 };
Property *props[hashRoots];
Property *enumnext;
int enumhash;
static bool caseSensitiveFilenames;
static unsigned int HashString(const char *s, size_t len) {
unsigned int ret = 0;
while (len--) {
ret <<= 4;
ret ^= *s;
s++;
}
return ret;
}
static bool IncludesVar(const char *value, const char *key);
public:
PropSet *superPS;
PropSet();
~PropSet();
void Set(const char *key, const char *val, int lenKey=-1, int lenVal=-1);
void Set(const char *keyVal);
void Unset(const char *key, int lenKey=-1);
void SetMultiple(const char *s);
SString Get(const char *key);
SString GetExpanded(const char *key);
SString Expand(const char *withVars, int maxExpands=100);
int GetInt(const char *key, int defaultValue=0);
SString GetWild(const char *keybase, const char *filename);
SString GetNewExpand(const char *keybase, const char *filename="");
void Clear();
char *ToString(); // Caller must delete[] the return value
bool GetFirst(char **key, char **val);
bool GetNext(char **key, char **val);
static void SetCaseSensitiveFilenames(bool caseSensitiveFilenames_) {
caseSensitiveFilenames = caseSensitiveFilenames_;
}
private:
// copy-value semantics not implemented
PropSet(const PropSet &copy);
void operator=(const PropSet &assign);
};
/**
*/
class WordList {
public:
// Each word contains at least one character - a empty word acts as sentinel at the end.
char **words;
char **wordsNoCase;
char *list;
int len;
bool onlyLineEnds; ///< Delimited by any white space or only line ends
bool sorted;
bool sortedNoCase;
int starts[256];
WordList(bool onlyLineEnds_ = false) :
words(0), wordsNoCase(0), list(0), len(0), onlyLineEnds(onlyLineEnds_),
sorted(false), sortedNoCase(false) {}
~WordList() { Clear(); }
operator bool() { return len ? true : false; }
char *operator[](int ind) { return words[ind]; }
void Clear();
void Set(const char *s);
char *Allocate(int size);
void SetFromAllocated();
bool InList(const char *s);
bool InListAbbreviated(const char *s, const char marker);
const char *GetNearestWord(const char *wordStart, int searchLen,
bool ignoreCase = false, SString wordCharacters="", int wordIndex = -1);
char *GetNearestWords(const char *wordStart, int searchLen,
bool ignoreCase=false, char otherSeparator='\0', bool exactLen=false);
};
inline bool IsAlphabetic(unsigned int ch) {
return ((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z'));
}
#ifdef _MSC_VER
// Visual C++ doesn't like the private copy idiom for disabling
// the default copy constructor and operator=, but it's fine.
#pragma warning(disable: 4511 4512)
#endif
#endif

View File

@@ -0,0 +1,835 @@
// Scintilla source code edit control
/** @file RESearch.cxx
** Regular expression search library.
**/
/*
* regex - Regular expression pattern matching and replacement
*
* By: Ozan S. Yigit (oz)
* Dept. of Computer Science
* York University
*
* Original code available from http://www.cs.yorku.ca/~oz/
* Translation to C++ by Neil Hodgson neilh@scintilla.org
* Removed all use of register.
* Converted to modern function prototypes.
* Put all global/static variables into an object so this code can be
* used from multiple threads etc.
*
* These routines are the PUBLIC DOMAIN equivalents of regex
* routines as found in 4.nBSD UN*X, with minor extensions.
*
* These routines are derived from various implementations found
* in software tools books, and Conroy's grep. They are NOT derived
* from licensed/restricted software.
* For more interesting/academic/complicated implementations,
* see Henry Spencer's regexp routines, or GNU Emacs pattern
* matching module.
*
* Modification history removed.
*
* Interfaces:
* RESearch::Compile: compile a regular expression into a NFA.
*
* char *RESearch::Compile(s)
* char *s;
*
* RESearch::Execute: execute the NFA to match a pattern.
*
* int RESearch::Execute(s)
* char *s;
*
* RESearch::ModifyWord change RESearch::Execute's understanding of what a "word"
* looks like (for \< and \>) by adding into the
* hidden word-syntax table.
*
* void RESearch::ModifyWord(s)
* char *s;
*
* RESearch::Substitute: substitute the matched portions in a new string.
*
* int RESearch::Substitute(src, dst)
* char *src;
* char *dst;
*
* re_fail: failure routine for RESearch::Execute.
*
* void re_fail(msg, op)
* char *msg;
* char op;
*
* Regular Expressions:
*
* [1] char matches itself, unless it is a special
* character (metachar): . \ [ ] * + ^ $
*
* [2] . matches any character.
*
* [3] \ matches the character following it, except
* when followed by a left or right round bracket,
* a digit 1 to 9 or a left or right angle bracket.
* (see [7], [8] and [9])
* It is used as an escape character for all
* other meta-characters, and itself. When used
* in a set ([4]), it is treated as an ordinary
* character.
*
* [4] [set] matches one of the characters in the set.
* If the first character in the set is "^",
* it matches a character NOT in the set, i.e.
* complements the set. A shorthand S-E is
* used to specify a set of characters S upto
* E, inclusive. The special characters "]" and
* "-" have no special meaning if they appear
* as the first chars in the set.
* examples: match:
*
* [a-z] any lowercase alpha
*
* [^]-] any char except ] and -
*
* [^A-Z] any char except uppercase
* alpha
*
* [a-zA-Z] any alpha
*
* [5] * any regular expression form [1] to [4], followed by
* closure char (*) matches zero or more matches of
* that form.
*
* [6] + same as [5], except it matches one or more.
*
* [7] a regular expression in the form [1] to [10], enclosed
* as \(form\) matches what form matches. The enclosure
* creates a set of tags, used for [8] and for
* pattern substution. The tagged forms are numbered
* starting from 1.
*
* [8] a \ followed by a digit 1 to 9 matches whatever a
* previously tagged regular expression ([7]) matched.
*
* [9] \< a regular expression starting with a \< construct
* \> and/or ending with a \> construct, restricts the
* pattern matching to the beginning of a word, and/or
* the end of a word. A word is defined to be a character
* string beginning and/or ending with the characters
* A-Z a-z 0-9 and _. It must also be preceded and/or
* followed by any character outside those mentioned.
*
* [10] a composite regular expression xy where x and y
* are in the form [1] to [10] matches the longest
* match of x followed by a match for y.
*
* [11] ^ a regular expression starting with a ^ character
* $ and/or ending with a $ character, restricts the
* pattern matching to the beginning of the line,
* or the end of line. [anchors] Elsewhere in the
* pattern, ^ and $ are treated as ordinary characters.
*
*
* Acknowledgements:
*
* HCR's Hugh Redelmeier has been most helpful in various
* stages of development. He convinced me to include BOW
* and EOW constructs, originally invented by Rob Pike at
* the University of Toronto.
*
* References:
* Software tools Kernighan & Plauger
* Software tools in Pascal Kernighan & Plauger
* Grep [rsx-11 C dist] David Conroy
* ed - text editor Un*x Programmer's Manual
* Advanced editing on Un*x B. W. Kernighan
* RegExp routines Henry Spencer
*
* Notes:
*
* This implementation uses a bit-set representation for character
* classes for speed and compactness. Each character is represented
* by one bit in a 128-bit block. Thus, CCL always takes a
* constant 16 bytes in the internal nfa, and RESearch::Execute does a single
* bit comparison to locate the character in the set.
*
* Examples:
*
* pattern: foo*.*
* compile: CHR f CHR o CLO CHR o END CLO ANY END END
* matches: fo foo fooo foobar fobar foxx ...
*
* pattern: fo[ob]a[rz]
* compile: CHR f CHR o CCL bitset CHR a CCL bitset END
* matches: fobar fooar fobaz fooaz
*
* pattern: foo\\+
* compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END
* matches: foo\ foo\\ foo\\\ ...
*
* pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo)
* compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END
* matches: foo1foo foo2foo foo3foo
*
* pattern: \(fo.*\)-\1
* compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END
* matches: foo-foo fo-fo fob-fob foobar-foobar ...
*/
#include "RESearch.h"
#define OKP 1
#define NOP 0
#define CHR 1
#define ANY 2
#define CCL 3
#define BOL 4
#define EOL 5
#define BOT 6
#define EOT 7
#define BOW 8
#define EOW 9
#define REF 10
#define CLO 11
#define END 0
/*
* The following defines are not meant to be changeable.
* They are for readability only.
*/
#define BLKIND 0370
#define BITIND 07
#define ASCIIB 0177
const char bitarr[] = {1,2,4,8,16,32,64,'\200'};
#define badpat(x) (*nfa = END, x)
RESearch::RESearch() {
Init();
}
RESearch::~RESearch() {
Clear();
}
void RESearch::Init() {
sta = NOP; /* status of lastpat */
bol = 0;
for (int i=0; i<MAXTAG; i++)
pat[i] = 0;
for (int j=0; j<BITBLK; j++)
bittab[j] = 0;
}
void RESearch::Clear() {
for (int i=0; i<MAXTAG; i++) {
delete []pat[i];
pat[i] = 0;
bopat[i] = NOTFOUND;
eopat[i] = NOTFOUND;
}
}
bool RESearch::GrabMatches(CharacterIndexer &ci) {
bool success = true;
for (unsigned int i=0; i<MAXTAG; i++) {
if ((bopat[i] != NOTFOUND) && (eopat[i] != NOTFOUND)) {
unsigned int len = eopat[i] - bopat[i];
pat[i] = new char[len + 1];
if (pat[i]) {
for (unsigned int j=0; j<len; j++)
pat[i][j] = ci.CharAt(bopat[i] + j);
pat[i][len] = '\0';
} else {
success = false;
}
}
}
return success;
}
void RESearch::ChSet(char c) {
bittab[((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND];
}
void RESearch::ChSetWithCase(char c, bool caseSensitive) {
if (caseSensitive) {
ChSet(c);
} else {
if ((c >= 'a') && (c <= 'z')) {
ChSet(c);
ChSet(static_cast<char>(c - 'a' + 'A'));
} else if ((c >= 'A') && (c <= 'Z')) {
ChSet(c);
ChSet(static_cast<char>(c - 'A' + 'a'));
} else {
ChSet(c);
}
}
}
const char escapeValue(char ch) {
switch (ch) {
case 'a': return '\a';
case 'b': return '\b';
case 'f': return '\f';
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
case 'v': return '\v';
}
return 0;
}
const char *RESearch::Compile(const char *pat, int length, bool caseSensitive, bool posix) {
char *mp=nfa; /* nfa pointer */
char *lp; /* saved pointer.. */
char *sp=nfa; /* another one.. */
char *mpMax = mp + MAXNFA - BITBLK - 10;
int tagi = 0; /* tag stack index */
int tagc = 1; /* actual tag count */
int n;
char mask; /* xor mask -CCL/NCL */
int c1, c2;
if (!pat || !length)
if (sta)
return 0;
else
return badpat("No previous regular expression");
sta = NOP;
const char *p=pat; /* pattern pointer */
for (int i=0; i<length; i++, p++) {
if (mp > mpMax)
return badpat("Pattern too long");
lp = mp;
switch(*p) {
case '.': /* match any char.. */
*mp++ = ANY;
break;
case '^': /* match beginning.. */
if (p == pat)
*mp++ = BOL;
else {
*mp++ = CHR;
*mp++ = *p;
}
break;
case '$': /* match endofline.. */
if (!*(p+1))
*mp++ = EOL;
else {
*mp++ = CHR;
*mp++ = *p;
}
break;
case '[': /* match char class..*/
*mp++ = CCL;
i++;
if (*++p == '^') {
mask = '\377';
i++;
p++;
} else
mask = 0;
if (*p == '-') { /* real dash */
i++;
ChSet(*p++);
}
if (*p == ']') { /* real brace */
i++;
ChSet(*p++);
}
while (*p && *p != ']') {
if (*p == '-' && *(p+1) && *(p+1) != ']') {
i++;
p++;
c1 = *(p-2) + 1;
i++;
c2 = *p++;
while (c1 <= c2) {
ChSetWithCase(static_cast<char>(c1++), caseSensitive);
}
} else if (*p == '\\' && *(p+1)) {
i++;
p++;
char escape = escapeValue(*p);
if (escape)
ChSetWithCase(escape, caseSensitive);
else
ChSetWithCase(*p, caseSensitive);
i++;
p++;
} else {
i++;
ChSetWithCase(*p++, caseSensitive);
}
}
if (!*p)
return badpat("Missing ]");
for (n = 0; n < BITBLK; bittab[n++] = (char) 0)
*mp++ = static_cast<char>(mask ^ bittab[n]);
break;
case '*': /* match 0 or more.. */
case '+': /* match 1 or more.. */
if (p == pat)
return badpat("Empty closure");
lp = sp; /* previous opcode */
if (*lp == CLO) /* equivalence.. */
break;
switch(*lp) {
case BOL:
case BOT:
case EOT:
case BOW:
case EOW:
case REF:
return badpat("Illegal closure");
default:
break;
}
if (*p == '+')
for (sp = mp; lp < sp; lp++)
*mp++ = *lp;
*mp++ = END;
*mp++ = END;
sp = mp;
while (--mp > lp)
*mp = mp[-1];
*mp = CLO;
mp = sp;
break;
case '\\': /* tags, backrefs .. */
i++;
switch(*++p) {
case '<':
*mp++ = BOW;
break;
case '>':
if (*sp == BOW)
return badpat("Null pattern inside \\<\\>");
*mp++ = EOW;
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
n = *p-'0';
if (tagi > 0 && tagstk[tagi] == n)
return badpat("Cyclical reference");
if (tagc > n) {
*mp++ = static_cast<char>(REF);
*mp++ = static_cast<char>(n);
}
else
return badpat("Undetermined reference");
break;
case 'a':
case 'b':
case 'n':
case 'f':
case 'r':
case 't':
case 'v':
*mp++ = CHR;
*mp++ = escapeValue(*p);
break;
default:
if (!posix && *p == '(') {
if (tagc < MAXTAG) {
tagstk[++tagi] = tagc;
*mp++ = BOT;
*mp++ = static_cast<char>(tagc++);
}
else
return badpat("Too many \\(\\) pairs");
} else if (!posix && *p == ')') {
if (*sp == BOT)
return badpat("Null pattern inside \\(\\)");
if (tagi > 0) {
*mp++ = static_cast<char>(EOT);
*mp++ = static_cast<char>(tagstk[tagi--]);
}
else
return badpat("Unmatched \\)");
} else {
*mp++ = CHR;
*mp++ = *p;
}
}
break;
default : /* an ordinary char */
if (posix && *p == '(') {
if (tagc < MAXTAG) {
tagstk[++tagi] = tagc;
*mp++ = BOT;
*mp++ = static_cast<char>(tagc++);
}
else
return badpat("Too many () pairs");
} else if (posix && *p == ')') {
if (*sp == BOT)
return badpat("Null pattern inside ()");
if (tagi > 0) {
*mp++ = static_cast<char>(EOT);
*mp++ = static_cast<char>(tagstk[tagi--]);
}
else
return badpat("Unmatched )");
} else if (caseSensitive) {
*mp++ = CHR;
*mp++ = *p;
} else {
*mp++ = CCL;
mask = 0;
ChSetWithCase(*p, false);
for (n = 0; n < BITBLK; bittab[n++] = (char) 0)
*mp++ = static_cast<char>(mask ^ bittab[n]);
}
break;
}
sp = lp;
}
if (tagi > 0)
return badpat((posix ? "Unmatched (" : "Unmatched \\("));
*mp = END;
sta = OKP;
return 0;
}
/*
* RESearch::Execute:
* execute nfa to find a match.
*
* special cases: (nfa[0])
* BOL
* Match only once, starting from the
* beginning.
* CHR
* First locate the character without
* calling PMatch, and if found, call
* PMatch for the remaining string.
* END
* RESearch::Compile failed, poor luser did not
* check for it. Fail fast.
*
* If a match is found, bopat[0] and eopat[0] are set
* to the beginning and the end of the matched fragment,
* respectively.
*
*/
int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) {
char c;
int ep = NOTFOUND;
char *ap = nfa;
bol = lp;
failure = 0;
Clear();
switch(*ap) {
case BOL: /* anchored: match from BOL only */
ep = PMatch(ci, lp, endp, ap);
break;
case EOL: /* just searching for end of line normal path doesn't work */
if (*(ap+1) == END) {
lp = endp;
ep = lp;
break;
} else {
return 0;
}
case CHR: /* ordinary char: locate it fast */
c = *(ap+1);
while ((lp < endp) && (ci.CharAt(lp) != c))
lp++;
if (lp >= endp) /* if EOS, fail, else fall thru. */
return 0;
default: /* regular matching all the way. */
while (lp < endp) {
ep = PMatch(ci, lp, endp, ap);
if (ep != NOTFOUND)
break;
lp++;
}
break;
case END: /* munged automaton. fail always */
return 0;
}
if (ep == NOTFOUND)
return 0;
bopat[0] = lp;
eopat[0] = ep;
return 1;
}
/*
* PMatch: internal routine for the hard part
*
* This code is partly snarfed from an early grep written by
* David Conroy. The backref and tag stuff, and various other
* innovations are by oz.
*
* special case optimizations: (nfa[n], nfa[n+1])
* CLO ANY
* We KNOW .* will match everything upto the
* end of line. Thus, directly go to the end of
* line, without recursive PMatch calls. As in
* the other closure cases, the remaining pattern
* must be matched by moving backwards on the
* string recursively, to find a match for xy
* (x is ".*" and y is the remaining pattern)
* where the match satisfies the LONGEST match for
* x followed by a match for y.
* CLO CHR
* We can again scan the string forward for the
* single char and at the point of failure, we
* execute the remaining nfa recursively, same as
* above.
*
* At the end of a successful match, bopat[n] and eopat[n]
* are set to the beginning and end of subpatterns matched
* by tagged expressions (n = 1 to 9).
*
*/
extern void re_fail(char *,char);
/*
* character classification table for word boundary operators BOW
* and EOW. the reason for not using ctype macros is that we can
* let the user add into our own table. see RESearch::ModifyWord. This table
* is not in the bitset form, since we may wish to extend it in the
* future for other character classifications.
*
* TRUE for 0-9 A-Z a-z _
*/
static char chrtyp[MAXCHR] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 1, 0, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 0, 0, 0, 0
};
#define inascii(x) (0177&(x))
#define iswordc(x) chrtyp[inascii(x)]
#define isinset(x,y) ((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND])
/*
* skip values for CLO XXX to skip past the closure
*/
#define ANYSKIP 2 /* [CLO] ANY END ... */
#define CHRSKIP 3 /* [CLO] CHR chr END ... */
#define CCLSKIP 34 /* [CLO] CCL 32bytes END ... */
int RESearch::PMatch(CharacterIndexer &ci, int lp, int endp, char *ap) {
int op, c, n;
int e; /* extra pointer for CLO */
int bp; /* beginning of subpat.. */
int ep; /* ending of subpat.. */
int are; /* to save the line ptr. */
while ((op = *ap++) != END)
switch(op) {
case CHR:
if (ci.CharAt(lp++) != *ap++)
return NOTFOUND;
break;
case ANY:
if (lp++ >= endp)
return NOTFOUND;
break;
case CCL:
c = ci.CharAt(lp++);
if (!isinset(ap,c))
return NOTFOUND;
ap += BITBLK;
break;
case BOL:
if (lp != bol)
return NOTFOUND;
break;
case EOL:
if (lp < endp)
return NOTFOUND;
break;
case BOT:
bopat[*ap++] = lp;
break;
case EOT:
eopat[*ap++] = lp;
break;
case BOW:
if (lp!=bol && iswordc(ci.CharAt(lp-1)) || !iswordc(ci.CharAt(lp)))
return NOTFOUND;
break;
case EOW:
if (lp==bol || !iswordc(ci.CharAt(lp-1)) || iswordc(ci.CharAt(lp)))
return NOTFOUND;
break;
case REF:
n = *ap++;
bp = bopat[n];
ep = eopat[n];
while (bp < ep)
if (ci.CharAt(bp++) != ci.CharAt(lp++))
return NOTFOUND;
break;
case CLO:
are = lp;
switch(*ap) {
case ANY:
while (lp < endp)
lp++;
n = ANYSKIP;
break;
case CHR:
c = *(ap+1);
while ((lp < endp) && (c == ci.CharAt(lp)))
lp++;
n = CHRSKIP;
break;
case CCL:
while ((lp < endp) && isinset(ap+1,ci.CharAt(lp)))
lp++;
n = CCLSKIP;
break;
default:
failure = true;
//re_fail("closure: bad nfa.", *ap);
return NOTFOUND;
}
ap += n;
while (lp >= are) {
if ((e = PMatch(ci, lp, endp, ap)) != NOTFOUND)
return e;
--lp;
}
return NOTFOUND;
default:
//re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op));
return NOTFOUND;
}
return lp;
}
/*
* RESearch::ModifyWord:
* add new characters into the word table to change RESearch::Execute's
* understanding of what a word should look like. Note that we
* only accept additions into the word definition.
*
* If the string parameter is 0 or null string, the table is
* reset back to the default containing A-Z a-z 0-9 _. [We use
* the compact bitset representation for the default table]
*/
static char deftab[16] = {
0, 0, 0, 0, 0, 0, '\377', 003, '\376', '\377', '\377', '\207',
'\376', '\377', '\377', 007
};
void RESearch::ModifyWord(char *s) {
int i;
if (!s || !*s) {
for (i = 0; i < MAXCHR; i++)
if (!isinset(deftab,i))
iswordc(i) = 0;
}
else
while(*s)
iswordc(*s++) = 1;
}
/*
* RESearch::Substitute:
* substitute the matched portions of the src in dst.
*
* & substitute the entire matched pattern.
*
* \digit substitute a subpattern, with the given tag number.
* Tags are numbered from 1 to 9. If the particular
* tagged subpattern does not exist, null is substituted.
*/
int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst) {
char c;
int pin;
int bp;
int ep;
if (!*src || !bopat[0])
return 0;
while ((c = *src++) != 0) {
switch(c) {
case '&':
pin = 0;
break;
case '\\':
c = *src++;
if (c >= '0' && c <= '9') {
pin = c - '0';
break;
}
default:
*dst++ = c;
continue;
}
if ((bp = bopat[pin]) != 0 && (ep = eopat[pin]) != 0) {
while (ci.CharAt(bp) && bp < ep)
*dst++ = ci.CharAt(bp++);
if (bp < ep)
return 0;
}
}
*dst = (char) 0;
return 1;
}

View File

@@ -0,0 +1,62 @@
// Scintilla source code edit control
/** @file RESearch.h
** Interface to the regular expression search library.
**/
// Written by Neil Hodgson <neilh@scintilla.org>
// Based on the work of Ozan S. Yigit.
// This file is in the public domain.
#ifndef RESEARCH_H
#define RESEARCH_H
/*
* The following defines are not meant to be changeable.
* They are for readability only.
*/
#define MAXCHR 256
#define CHRBIT 8
#define BITBLK MAXCHR/CHRBIT
class CharacterIndexer {
public:
virtual char CharAt(int index)=0;
virtual ~CharacterIndexer() {
}
};
class RESearch {
public:
RESearch();
~RESearch();
void Init();
void Clear();
bool GrabMatches(CharacterIndexer &ci);
void ChSet(char c);
void ChSetWithCase(char c, bool caseSensitive);
const char *Compile(const char *pat, int length, bool caseSensitive, bool posix);
int Execute(CharacterIndexer &ci, int lp, int endp);
void ModifyWord(char *s);
int Substitute(CharacterIndexer &ci, char *src, char *dst);
enum {MAXTAG=10};
enum {MAXNFA=2048};
enum {NOTFOUND=-1};
int bopat[MAXTAG];
int eopat[MAXTAG];
char *pat[MAXTAG];
private:
int PMatch(CharacterIndexer &ci, int lp, int endp, char *ap);
int bol;
int tagstk[MAXTAG]; /* subpat tag stack..*/
char nfa[MAXNFA]; /* automaton.. */
int sta;
char bittab[BITBLK]; /* bit table for CCL */
/* pre-set bits... */
int failure;
};
#endif

View File

@@ -0,0 +1,280 @@
// SciTE - Scintilla based Text Editor
/** @file SString.h
** A simple string class.
**/
// Copyright 1998-2004 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef SSTRING_H
#define SSTRING_H
// These functions are implemented because each platform calls them something different.
int CompareCaseInsensitive(const char *a, const char *b);
int CompareNCaseInsensitive(const char *a, const char *b, size_t len);
bool EqualCaseInsensitive(const char *a, const char *b);
// Define another string class.
// While it would be 'better' to use std::string, that doubles the executable size.
// An SString may contain embedded nul characters.
/**
* Base class from which the two other classes (SBuffer & SString)
* are derived.
*/
class SContainer {
public:
/** Type of string lengths (sizes) and positions (indexes). */
typedef size_t lenpos_t;
/** Out of bounds value indicating that the string argument should be measured. */
enum { measure_length=0xffffffffU};
protected:
char *s; ///< The C string
lenpos_t sSize; ///< The size of the buffer, less 1: ie. the maximum size of the string
SContainer() : s(0), sSize(0) {}
~SContainer() {
delete []s; // Suppose it was allocated using StringAllocate
s = 0;
sSize = 0;
}
/** Size of buffer. */
lenpos_t size() const {
if (s) {
return sSize;
} else {
return 0;
}
}
public:
/**
* Allocate uninitialized memory big enough to fit a string of the given length.
* @return the pointer to the new string
*/
static char *StringAllocate(lenpos_t len);
/**
* Duplicate a buffer/C string.
* Allocate memory of the given size, or big enough to fit the string if length isn't given;
* then copy the given string in the allocated memory.
* @return the pointer to the new string
*/
static char *StringAllocate(
const char *s, ///< The string to duplicate
lenpos_t len=measure_length); ///< The length of memory to allocate. Optional.
};
/**
* @brief A string buffer class.
*
* Main use is to ask an API the length of a string it can provide,
* then to allocate a buffer of the given size, and to provide this buffer
* to the API to put the string.
* This class is intended to be shortlived, to be transformed as SString
* as soon as it holds the string, so it has little members.
* Note: we assume the buffer is filled by the API. If the length can be shorter,
* we should set sLen to strlen(sb.ptr()) in related SString constructor and assignment.
*/
class SBuffer : protected SContainer {
public:
SBuffer(lenpos_t len) {
s = StringAllocate(len);
if (s) {
*s = '\0';
sSize = len;
} else {
sSize = 0;
}
}
private:
/// Copy constructor
// Here only to be on the safe size, user should avoid returning SBuffer values.
SBuffer(const SBuffer &source) : SContainer() {
s = StringAllocate(source.s, source.sSize);
sSize = (s) ? source.sSize : 0;
}
/// Default assignment operator
// Same here, shouldn't be used
SBuffer &operator=(const SBuffer &source) {
if (this != &source) {
delete []s;
s = StringAllocate(source.s, source.sSize);
sSize = (s) ? source.sSize : 0;
}
return *this;
}
public:
/** Provide direct read/write access to buffer. */
char *ptr() {
return s;
}
/** Ownership of the buffer have been taken, so release it. */
void reset() {
s = 0;
sSize = 0;
}
/** Size of buffer. */
lenpos_t size() const {
return SContainer::size();
}
};
/**
* @brief A simple string class.
*
* Hold the length of the string for quick operations,
* can have a buffer bigger than the string to avoid too many memory allocations and copies.
* May have embedded zeroes as a result of @a substitute, but relies too heavily on C string
* functions to allow reliable manipulations of these strings, other than simple appends, etc.
*/
class SString : protected SContainer {
lenpos_t sLen; ///< The size of the string in s
lenpos_t sizeGrowth; ///< Minimum growth size when appending strings
enum { sizeGrowthDefault = 64 };
bool grow(lenpos_t lenNew);
SString &assign(const char *sOther, lenpos_t sSize_=measure_length);
public:
SString() : sLen(0), sizeGrowth(sizeGrowthDefault) {}
SString(const SString &source) : SContainer(), sizeGrowth(sizeGrowthDefault) {
s = StringAllocate(source.s, source.sLen);
sSize = sLen = (s) ? source.sLen : 0;
}
SString(const char *s_) : sizeGrowth(sizeGrowthDefault) {
s = StringAllocate(s_);
sSize = sLen = (s) ? strlen(s) : 0;
}
SString(SBuffer &buf) : sizeGrowth(sizeGrowthDefault) {
s = buf.ptr();
sSize = sLen = buf.size();
// Consumes the given buffer!
buf.reset();
}
SString(const char *s_, lenpos_t first, lenpos_t last) : sizeGrowth(sizeGrowthDefault) {
// note: expects the "last" argument to point one beyond the range end (a la STL iterators)
s = StringAllocate(s_ + first, last - first);
sSize = sLen = (s) ? last - first : 0;
}
SString(int i);
SString(double d, int precision);
~SString() {
sLen = 0;
}
void clear() {
if (s) {
*s = '\0';
}
sLen = 0;
}
/** Size of buffer. */
lenpos_t size() const {
return SContainer::size();
}
/** Size of string in buffer. */
lenpos_t length() const {
return sLen;
}
/** Read access to a character of the string. */
char operator[](lenpos_t i) const {
return (s && i < sSize) ? s[i] : '\0';
}
SString &operator=(const char *source) {
return assign(source);
}
SString &operator=(const SString &source) {
if (this != &source) {
assign(source.s, source.sLen);
}
return *this;
}
bool operator==(const SString &sOther) const;
bool operator!=(const SString &sOther) const {
return !operator==(sOther);
}
bool operator==(const char *sOther) const;
bool operator!=(const char *sOther) const {
return !operator==(sOther);
}
bool contains(char ch) const {
return (s && *s) ? strchr(s, ch) != 0 : false;
}
void setsizegrowth(lenpos_t sizeGrowth_) {
sizeGrowth = sizeGrowth_;
}
const char *c_str() const {
return s ? s : "";
}
/** Give ownership of buffer to caller which must use delete[] to free buffer. */
char *detach() {
char *sRet = s;
s = 0;
sSize = 0;
sLen = 0;
return sRet;
}
SString substr(lenpos_t subPos, lenpos_t subLen=measure_length) const;
SString &lowercase(lenpos_t subPos = 0, lenpos_t subLen=measure_length);
SString &uppercase(lenpos_t subPos = 0, lenpos_t subLen=measure_length);
SString &append(const char *sOther, lenpos_t sLenOther=measure_length, char sep = '\0');
SString &operator+=(const char *sOther) {
return append(sOther, static_cast<lenpos_t>(measure_length));
}
SString &operator+=(const SString &sOther) {
return append(sOther.s, sOther.sLen);
}
SString &operator+=(char ch) {
return append(&ch, 1);
}
SString &appendwithseparator(const char *sOther, char sep) {
return append(sOther, strlen(sOther), sep);
}
SString &insert(lenpos_t pos, const char *sOther, lenpos_t sLenOther=measure_length);
/**
* Remove @a len characters from the @a pos position, included.
* Characters at pos + len and beyond replace characters at pos.
* If @a len is 0, or greater than the length of the string
* starting at @a pos, the string is just truncated at @a pos.
*/
void remove(lenpos_t pos, lenpos_t len);
SString &change(lenpos_t pos, char ch) {
if (pos < sLen) { // character changed must be in string bounds
*(s + pos) = ch;
}
return *this;
}
/** Read an integral numeric value from the string. */
int value() const {
return s ? atoi(s) : 0;
}
bool startswith(const char *prefix);
bool endswith(const char *suffix);
int search(const char *sFind, lenpos_t start=0) const;
bool contains(const char *sFind) const {
return search(sFind) >= 0;
}
int substitute(char chFind, char chReplace);
int substitute(const char *sFind, const char *sReplace);
int remove(const char *sFind) {
return substitute(sFind, "");
}
};
/**
* Duplicate a C string.
* Allocate memory of the given size, or big enough to fit the string if length isn't given;
* then copy the given string in the allocated memory.
* @return the pointer to the new string
*/
inline char *StringDup(
const char *s, ///< The string to duplicate
SContainer::lenpos_t len=SContainer::measure_length) ///< The length of memory to allocate. Optional.
{
return SContainer::StringAllocate(s, len);
}
#endif

View File

@@ -0,0 +1,127 @@
// Scintilla source code edit control
/** @file SVector.h
** A simple expandable vector.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@hare.net.au>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef SVECTOR_H
#define SVECTOR_H
/**
* A simple expandable integer vector.
* Storage not allocated for elements until an element is used.
* This makes it very lightweight unless used so is a good match for optional features.
*/
class SVector {
enum { allocSize = 4000 };
int *v; ///< The vector
unsigned int size; ///< Number of elements allocated
unsigned int len; ///< Number of elements used in vector
bool allocFailure; ///< A memory allocation call has failed
/** Internally allocate more elements than the user wants
* to avoid thrashing the memory allocator. */
void SizeTo(int newSize) {
if (newSize < allocSize)
newSize += allocSize;
else
newSize = (newSize * 3) / 2;
int* newv = new int[newSize];
if (!newv) {
allocFailure = true;
return;
}
size = newSize;
unsigned int i=0;
for (; i<len; i++) {
newv[i] = v[i];
}
for (; i<size; i++) {
newv[i] = 0;
}
delete []v;
v = newv;
}
public:
SVector() {
allocFailure = false;
v = 0;
len = 0;
size = 0;
}
~SVector() {
Free();
}
/// Constructor from another vector.
SVector(const SVector &other) {
allocFailure = false;
v = 0;
len = 0;
size = 0;
if (other.Length() > 0) {
SizeTo(other.Length());
if (!allocFailure) {
for (int i=0;i<other.Length();i++)
v[i] = other.v[i];
len = other.Length();
}
}
}
/// Copy constructor.
SVector &operator=(const SVector &other) {
if (this != &other) {
delete []v;
allocFailure = false;
v = 0;
len = 0;
size = 0;
if (other.Length() > 0) {
SizeTo(other.Length());
if (!allocFailure) {
for (int i=0;i<other.Length();i++)
v[i] = other.v[i];
}
len = other.Length();
}
}
return *this;
}
/** @brief Accessor.
* Allows to access values from the list, and grows it if accessing
* outside the current bounds. The returned value in this case is 0. */
int &operator[](unsigned int i) {
if (i >= len) {
if (i >= size) {
SizeTo(i);
}
len = i+1;
}
return v[i];
}
/// Reset vector.
void Free() {
delete []v;
v = 0;
size = 0;
len = 0;
}
/** @brief Grow vector size.
* Doesn't allow a vector to be shrinked. */
void SetLength(unsigned int newLength) {
if (newLength > len) {
if (newLength >= size) {
SizeTo(newLength);
}
}
len = newLength;
}
/// Get the current length (number of used elements) of the vector.
int Length() const {
return len;
}
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,768 @@
// Scintilla source code edit control
/** @file Scintilla.h
** Interface to the edit control.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
// Most of this file is automatically generated from the Scintilla.iface interface definition
// file which contains any comments about the definitions. HFacer.py does the generation.
#ifndef SCINTILLA_H
#define SCINTILLA_H
#if LCCWIN
typedef BOOL bool;
#endif
#if PLAT_WIN
// Return false on failure:
bool Scintilla_RegisterClasses(void *hInstance);
bool Scintilla_ReleaseResources();
#endif
int Scintilla_LinkLexers();
// Here should be placed typedefs for uptr_t, an unsigned integer type large enough to
// hold a pointer and sptr_t, a signed integer large enough to hold a pointer.
// May need to be changed for 64 bit platforms.
#if _MSC_VER >= 1300
#include <BaseTsd.h>
#endif
#ifdef MAXULONG_PTR
typedef ULONG_PTR uptr_t;
typedef LONG_PTR sptr_t;
#else
typedef unsigned long uptr_t;
typedef long sptr_t;
#endif
typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam);
//++Autogenerated -- start of section automatically generated from Scintilla.iface
#define INVALID_POSITION -1
#define SCI_START 2000
#define SCI_OPTIONAL_START 3000
#define SCI_LEXER_START 4000
#define SCI_ADDTEXT 2001
#define SCI_ADDSTYLEDTEXT 2002
#define SCI_INSERTTEXT 2003
#define SCI_CLEARALL 2004
#define SCI_CLEARDOCUMENTSTYLE 2005
#define SCI_GETLENGTH 2006
#define SCI_GETCHARAT 2007
#define SCI_GETCURRENTPOS 2008
#define SCI_GETANCHOR 2009
#define SCI_GETSTYLEAT 2010
#define SCI_REDO 2011
#define SCI_SETUNDOCOLLECTION 2012
#define SCI_SELECTALL 2013
#define SCI_SETSAVEPOINT 2014
#define SCI_GETSTYLEDTEXT 2015
#define SCI_CANREDO 2016
#define SCI_MARKERLINEFROMHANDLE 2017
#define SCI_MARKERDELETEHANDLE 2018
#define SCI_GETUNDOCOLLECTION 2019
#define SCWS_INVISIBLE 0
#define SCWS_VISIBLEALWAYS 1
#define SCWS_VISIBLEAFTERINDENT 2
#define SCI_GETVIEWWS 2020
#define SCI_SETVIEWWS 2021
#define SCI_POSITIONFROMPOINT 2022
#define SCI_POSITIONFROMPOINTCLOSE 2023
#define SCI_GOTOLINE 2024
#define SCI_GOTOPOS 2025
#define SCI_SETANCHOR 2026
#define SCI_GETCURLINE 2027
#define SCI_GETENDSTYLED 2028
#define SC_EOL_CRLF 0
#define SC_EOL_CR 1
#define SC_EOL_LF 2
#define SCI_CONVERTEOLS 2029
#define SCI_GETEOLMODE 2030
#define SCI_SETEOLMODE 2031
#define SCI_STARTSTYLING 2032
#define SCI_SETSTYLING 2033
#define SCI_GETBUFFEREDDRAW 2034
#define SCI_SETBUFFEREDDRAW 2035
#define SCI_SETTABWIDTH 2036
#define SCI_GETTABWIDTH 2121
#define SC_CP_UTF8 65001
#define SC_CP_DBCS 1
#define SCI_SETCODEPAGE 2037
#define SCI_SETUSEPALETTE 2039
#define MARKER_MAX 31
#define SC_MARK_CIRCLE 0
#define SC_MARK_ROUNDRECT 1
#define SC_MARK_ARROW 2
#define SC_MARK_SMALLRECT 3
#define SC_MARK_SHORTARROW 4
#define SC_MARK_EMPTY 5
#define SC_MARK_ARROWDOWN 6
#define SC_MARK_MINUS 7
#define SC_MARK_PLUS 8
#define SC_MARK_VLINE 9
#define SC_MARK_LCORNER 10
#define SC_MARK_TCORNER 11
#define SC_MARK_BOXPLUS 12
#define SC_MARK_BOXPLUSCONNECTED 13
#define SC_MARK_BOXMINUS 14
#define SC_MARK_BOXMINUSCONNECTED 15
#define SC_MARK_LCORNERCURVE 16
#define SC_MARK_TCORNERCURVE 17
#define SC_MARK_CIRCLEPLUS 18
#define SC_MARK_CIRCLEPLUSCONNECTED 19
#define SC_MARK_CIRCLEMINUS 20
#define SC_MARK_CIRCLEMINUSCONNECTED 21
#define SC_MARK_BACKGROUND 22
#define SC_MARK_DOTDOTDOT 23
#define SC_MARK_ARROWS 24
#define SC_MARK_PIXMAP 25
#define SC_MARK_FULLRECT 26
#define SC_MARK_CHARACTER 10000
#define SC_MARKNUM_FOLDEREND 25
#define SC_MARKNUM_FOLDEROPENMID 26
#define SC_MARKNUM_FOLDERMIDTAIL 27
#define SC_MARKNUM_FOLDERTAIL 28
#define SC_MARKNUM_FOLDERSUB 29
#define SC_MARKNUM_FOLDER 30
#define SC_MARKNUM_FOLDEROPEN 31
#define SC_MASK_FOLDERS 0xFE000000
#define SCI_MARKERDEFINE 2040
#define SCI_MARKERSETFORE 2041
#define SCI_MARKERSETBACK 2042
#define SCI_MARKERADD 2043
#define SCI_MARKERDELETE 2044
#define SCI_MARKERDELETEALL 2045
#define SCI_MARKERGET 2046
#define SCI_MARKERNEXT 2047
#define SCI_MARKERPREVIOUS 2048
#define SCI_MARKERDEFINEPIXMAP 2049
#define SCI_MARKERADDSET 2466
#define SC_MARGIN_SYMBOL 0
#define SC_MARGIN_NUMBER 1
#define SCI_SETMARGINTYPEN 2240
#define SCI_GETMARGINTYPEN 2241
#define SCI_SETMARGINWIDTHN 2242
#define SCI_GETMARGINWIDTHN 2243
#define SCI_SETMARGINMASKN 2244
#define SCI_GETMARGINMASKN 2245
#define SCI_SETMARGINSENSITIVEN 2246
#define SCI_GETMARGINSENSITIVEN 2247
#define STYLE_DEFAULT 32
#define STYLE_LINENUMBER 33
#define STYLE_BRACELIGHT 34
#define STYLE_BRACEBAD 35
#define STYLE_CONTROLCHAR 36
#define STYLE_INDENTGUIDE 37
#define STYLE_LASTPREDEFINED 39
#define STYLE_MAX 127
#define SC_CHARSET_ANSI 0
#define SC_CHARSET_DEFAULT 1
#define SC_CHARSET_BALTIC 186
#define SC_CHARSET_CHINESEBIG5 136
#define SC_CHARSET_EASTEUROPE 238
#define SC_CHARSET_GB2312 134
#define SC_CHARSET_GREEK 161
#define SC_CHARSET_HANGUL 129
#define SC_CHARSET_MAC 77
#define SC_CHARSET_OEM 255
#define SC_CHARSET_RUSSIAN 204
#define SC_CHARSET_CYRILLIC 1251
#define SC_CHARSET_SHIFTJIS 128
#define SC_CHARSET_SYMBOL 2
#define SC_CHARSET_TURKISH 162
#define SC_CHARSET_JOHAB 130
#define SC_CHARSET_HEBREW 177
#define SC_CHARSET_ARABIC 178
#define SC_CHARSET_VIETNAMESE 163
#define SC_CHARSET_THAI 222
#define SC_CHARSET_8859_15 1000
#define SCI_STYLECLEARALL 2050
#define SCI_STYLESETFORE 2051
#define SCI_STYLESETBACK 2052
#define SCI_STYLESETBOLD 2053
#define SCI_STYLESETITALIC 2054
#define SCI_STYLESETSIZE 2055
#define SCI_STYLESETFONT 2056
#define SCI_STYLESETEOLFILLED 2057
#define SCI_STYLERESETDEFAULT 2058
#define SCI_STYLESETUNDERLINE 2059
#define SC_CASE_MIXED 0
#define SC_CASE_UPPER 1
#define SC_CASE_LOWER 2
#define SCI_STYLESETCASE 2060
#define SCI_STYLESETCHARACTERSET 2066
#define SCI_STYLESETHOTSPOT 2409
#define SCI_SETSELFORE 2067
#define SCI_SETSELBACK 2068
#define SCI_SETCARETFORE 2069
#define SCI_ASSIGNCMDKEY 2070
#define SCI_CLEARCMDKEY 2071
#define SCI_CLEARALLCMDKEYS 2072
#define SCI_SETSTYLINGEX 2073
#define SCI_STYLESETVISIBLE 2074
#define SCI_GETCARETPERIOD 2075
#define SCI_SETCARETPERIOD 2076
#define SCI_SETWORDCHARS 2077
#define SCI_BEGINUNDOACTION 2078
#define SCI_ENDUNDOACTION 2079
#define INDIC_MAX 7
#define INDIC_PLAIN 0
#define INDIC_SQUIGGLE 1
#define INDIC_TT 2
#define INDIC_DIAGONAL 3
#define INDIC_STRIKE 4
#define INDIC_HIDDEN 5
#define INDIC_BOX 6
#define INDIC0_MASK 0x20
#define INDIC1_MASK 0x40
#define INDIC2_MASK 0x80
#define INDICS_MASK 0xE0
#define SCI_INDICSETSTYLE 2080
#define SCI_INDICGETSTYLE 2081
#define SCI_INDICSETFORE 2082
#define SCI_INDICGETFORE 2083
#define SCI_SETWHITESPACEFORE 2084
#define SCI_SETWHITESPACEBACK 2085
#define SCI_SETSTYLEBITS 2090
#define SCI_GETSTYLEBITS 2091
#define SCI_SETLINESTATE 2092
#define SCI_GETLINESTATE 2093
#define SCI_GETMAXLINESTATE 2094
#define SCI_GETCARETLINEVISIBLE 2095
#define SCI_SETCARETLINEVISIBLE 2096
#define SCI_GETCARETLINEBACK 2097
#define SCI_SETCARETLINEBACK 2098
#define SCI_STYLESETCHANGEABLE 2099
#define SCI_AUTOCSHOW 2100
#define SCI_AUTOCCANCEL 2101
#define SCI_AUTOCACTIVE 2102
#define SCI_AUTOCPOSSTART 2103
#define SCI_AUTOCCOMPLETE 2104
#define SCI_AUTOCSTOPS 2105
#define SCI_AUTOCSETSEPARATOR 2106
#define SCI_AUTOCGETSEPARATOR 2107
#define SCI_AUTOCSELECT 2108
#define SCI_AUTOCSETCANCELATSTART 2110
#define SCI_AUTOCGETCANCELATSTART 2111
#define SCI_AUTOCSETFILLUPS 2112
#define SCI_AUTOCSETCHOOSESINGLE 2113
#define SCI_AUTOCGETCHOOSESINGLE 2114
#define SCI_AUTOCSETIGNORECASE 2115
#define SCI_AUTOCGETIGNORECASE 2116
#define SCI_USERLISTSHOW 2117
#define SCI_AUTOCSETAUTOHIDE 2118
#define SCI_AUTOCGETAUTOHIDE 2119
#define SCI_AUTOCSETDROPRESTOFWORD 2270
#define SCI_AUTOCGETDROPRESTOFWORD 2271
#define SCI_REGISTERIMAGE 2405
#define SCI_CLEARREGISTEREDIMAGES 2408
#define SCI_AUTOCGETTYPESEPARATOR 2285
#define SCI_AUTOCSETTYPESEPARATOR 2286
#define SCI_AUTOCSETMAXWIDTH 2208
#define SCI_AUTOCGETMAXWIDTH 2209
#define SCI_AUTOCSETMAXHEIGHT 2210
#define SCI_AUTOCGETMAXHEIGHT 2211
#define SCI_SETINDENT 2122
#define SCI_GETINDENT 2123
#define SCI_SETUSETABS 2124
#define SCI_GETUSETABS 2125
#define SCI_SETLINEINDENTATION 2126
#define SCI_GETLINEINDENTATION 2127
#define SCI_GETLINEINDENTPOSITION 2128
#define SCI_GETCOLUMN 2129
#define SCI_SETHSCROLLBAR 2130
#define SCI_GETHSCROLLBAR 2131
#define SCI_SETINDENTATIONGUIDES 2132
#define SCI_GETINDENTATIONGUIDES 2133
#define SCI_SETHIGHLIGHTGUIDE 2134
#define SCI_GETHIGHLIGHTGUIDE 2135
#define SCI_GETLINEENDPOSITION 2136
#define SCI_GETCODEPAGE 2137
#define SCI_GETCARETFORE 2138
#define SCI_GETUSEPALETTE 2139
#define SCI_GETREADONLY 2140
#define SCI_SETCURRENTPOS 2141
#define SCI_SETSELECTIONSTART 2142
#define SCI_GETSELECTIONSTART 2143
#define SCI_SETSELECTIONEND 2144
#define SCI_GETSELECTIONEND 2145
#define SCI_SETPRINTMAGNIFICATION 2146
#define SCI_GETPRINTMAGNIFICATION 2147
#define SC_PRINT_NORMAL 0
#define SC_PRINT_INVERTLIGHT 1
#define SC_PRINT_BLACKONWHITE 2
#define SC_PRINT_COLOURONWHITE 3
#define SC_PRINT_COLOURONWHITEDEFAULTBG 4
#define SCI_SETPRINTCOLOURMODE 2148
#define SCI_GETPRINTCOLOURMODE 2149
#define SCFIND_WHOLEWORD 2
#define SCFIND_MATCHCASE 4
#define SCFIND_WORDSTART 0x00100000
#define SCFIND_REGEXP 0x00200000
#define SCFIND_POSIX 0x00400000
#define SCI_FINDTEXT 2150
#define SCI_FORMATRANGE 2151
#define SCI_GETFIRSTVISIBLELINE 2152
#define SCI_GETLINE 2153
#define SCI_GETLINECOUNT 2154
#define SCI_SETMARGINLEFT 2155
#define SCI_GETMARGINLEFT 2156
#define SCI_SETMARGINRIGHT 2157
#define SCI_GETMARGINRIGHT 2158
#define SCI_GETMODIFY 2159
#define SCI_SETSEL 2160
#define SCI_GETSELTEXT 2161
#define SCI_GETTEXTRANGE 2162
#define SCI_HIDESELECTION 2163
#define SCI_POINTXFROMPOSITION 2164
#define SCI_POINTYFROMPOSITION 2165
#define SCI_LINEFROMPOSITION 2166
#define SCI_POSITIONFROMLINE 2167
#define SCI_LINESCROLL 2168
#define SCI_SCROLLCARET 2169
#define SCI_REPLACESEL 2170
#define SCI_SETREADONLY 2171
#define SCI_NULL 2172
#define SCI_CANPASTE 2173
#define SCI_CANUNDO 2174
#define SCI_EMPTYUNDOBUFFER 2175
#define SCI_UNDO 2176
#define SCI_CUT 2177
#define SCI_COPY 2178
#define SCI_PASTE 2179
#define SCI_CLEAR 2180
#define SCI_SETTEXT 2181
#define SCI_GETTEXT 2182
#define SCI_GETTEXTLENGTH 2183
#define SCI_GETDIRECTFUNCTION 2184
#define SCI_GETDIRECTPOINTER 2185
#define SCI_SETOVERTYPE 2186
#define SCI_GETOVERTYPE 2187
#define SCI_SETCARETWIDTH 2188
#define SCI_GETCARETWIDTH 2189
#define SCI_SETTARGETSTART 2190
#define SCI_GETTARGETSTART 2191
#define SCI_SETTARGETEND 2192
#define SCI_GETTARGETEND 2193
#define SCI_REPLACETARGET 2194
#define SCI_REPLACETARGETRE 2195
#define SCI_SEARCHINTARGET 2197
#define SCI_SETSEARCHFLAGS 2198
#define SCI_GETSEARCHFLAGS 2199
#define SCI_CALLTIPSHOW 2200
#define SCI_CALLTIPCANCEL 2201
#define SCI_CALLTIPACTIVE 2202
#define SCI_CALLTIPPOSSTART 2203
#define SCI_CALLTIPSETHLT 2204
#define SCI_CALLTIPSETBACK 2205
#define SCI_CALLTIPSETFORE 2206
#define SCI_CALLTIPSETFOREHLT 2207
#define SCI_VISIBLEFROMDOCLINE 2220
#define SCI_DOCLINEFROMVISIBLE 2221
#define SCI_WRAPCOUNT 2235
#define SC_FOLDLEVELBASE 0x400
#define SC_FOLDLEVELWHITEFLAG 0x1000
#define SC_FOLDLEVELHEADERFLAG 0x2000
#define SC_FOLDLEVELBOXHEADERFLAG 0x4000
#define SC_FOLDLEVELBOXFOOTERFLAG 0x8000
#define SC_FOLDLEVELCONTRACTED 0x10000
#define SC_FOLDLEVELUNINDENT 0x20000
#define SC_FOLDLEVELNUMBERMASK 0x0FFF
#define SCI_SETFOLDLEVEL 2222
#define SCI_GETFOLDLEVEL 2223
#define SCI_GETLASTCHILD 2224
#define SCI_GETFOLDPARENT 2225
#define SCI_SHOWLINES 2226
#define SCI_HIDELINES 2227
#define SCI_GETLINEVISIBLE 2228
#define SCI_SETFOLDEXPANDED 2229
#define SCI_GETFOLDEXPANDED 2230
#define SCI_TOGGLEFOLD 2231
#define SCI_ENSUREVISIBLE 2232
#define SC_FOLDFLAG_LINEBEFORE_EXPANDED 0x0002
#define SC_FOLDFLAG_LINEBEFORE_CONTRACTED 0x0004
#define SC_FOLDFLAG_LINEAFTER_EXPANDED 0x0008
#define SC_FOLDFLAG_LINEAFTER_CONTRACTED 0x0010
#define SC_FOLDFLAG_LEVELNUMBERS 0x0040
#define SC_FOLDFLAG_BOX 0x0001
#define SCI_SETFOLDFLAGS 2233
#define SCI_ENSUREVISIBLEENFORCEPOLICY 2234
#define SCI_SETTABINDENTS 2260
#define SCI_GETTABINDENTS 2261
#define SCI_SETBACKSPACEUNINDENTS 2262
#define SCI_GETBACKSPACEUNINDENTS 2263
#define SC_TIME_FOREVER 10000000
#define SCI_SETMOUSEDWELLTIME 2264
#define SCI_GETMOUSEDWELLTIME 2265
#define SCI_WORDSTARTPOSITION 2266
#define SCI_WORDENDPOSITION 2267
#define SC_WRAP_NONE 0
#define SC_WRAP_WORD 1
#define SC_WRAP_CHAR 2
#define SCI_SETWRAPMODE 2268
#define SCI_GETWRAPMODE 2269
#define SC_WRAPVISUALFLAG_NONE 0x0000
#define SC_WRAPVISUALFLAG_END 0x0001
#define SC_WRAPVISUALFLAG_START 0x0002
#define SCI_SETWRAPVISUALFLAGS 2460
#define SCI_GETWRAPVISUALFLAGS 2461
#define SC_WRAPVISUALFLAGLOC_DEFAULT 0x0000
#define SC_WRAPVISUALFLAGLOC_END_BY_TEXT 0x0001
#define SC_WRAPVISUALFLAGLOC_START_BY_TEXT 0x0002
#define SCI_SETWRAPVISUALFLAGSLOCATION 2462
#define SCI_GETWRAPVISUALFLAGSLOCATION 2463
#define SCI_SETWRAPSTARTINDENT 2464
#define SCI_GETWRAPSTARTINDENT 2465
#define SC_CACHE_NONE 0
#define SC_CACHE_CARET 1
#define SC_CACHE_PAGE 2
#define SC_CACHE_DOCUMENT 3
#define SCI_SETLAYOUTCACHE 2272
#define SCI_GETLAYOUTCACHE 2273
#define SCI_SETSCROLLWIDTH 2274
#define SCI_GETSCROLLWIDTH 2275
#define SCI_TEXTWIDTH 2276
#define SCI_SETENDATLASTLINE 2277
#define SCI_GETENDATLASTLINE 2278
#define SCI_TEXTHEIGHT 2279
#define SCI_SETVSCROLLBAR 2280
#define SCI_GETVSCROLLBAR 2281
#define SCI_APPENDTEXT 2282
#define SCI_GETTWOPHASEDRAW 2283
#define SCI_SETTWOPHASEDRAW 2284
#define SCI_TARGETFROMSELECTION 2287
#define SCI_LINESJOIN 2288
#define SCI_LINESSPLIT 2289
#define SCI_SETFOLDMARGINCOLOUR 2290
#define SCI_SETFOLDMARGINHICOLOUR 2291
#define SCI_LINEDOWN 2300
#define SCI_LINEDOWNEXTEND 2301
#define SCI_LINEUP 2302
#define SCI_LINEUPEXTEND 2303
#define SCI_CHARLEFT 2304
#define SCI_CHARLEFTEXTEND 2305
#define SCI_CHARRIGHT 2306
#define SCI_CHARRIGHTEXTEND 2307
#define SCI_WORDLEFT 2308
#define SCI_WORDLEFTEXTEND 2309
#define SCI_WORDRIGHT 2310
#define SCI_WORDRIGHTEXTEND 2311
#define SCI_HOME 2312
#define SCI_HOMEEXTEND 2313
#define SCI_LINEEND 2314
#define SCI_LINEENDEXTEND 2315
#define SCI_DOCUMENTSTART 2316
#define SCI_DOCUMENTSTARTEXTEND 2317
#define SCI_DOCUMENTEND 2318
#define SCI_DOCUMENTENDEXTEND 2319
#define SCI_PAGEUP 2320
#define SCI_PAGEUPEXTEND 2321
#define SCI_PAGEDOWN 2322
#define SCI_PAGEDOWNEXTEND 2323
#define SCI_EDITTOGGLEOVERTYPE 2324
#define SCI_CANCEL 2325
#define SCI_DELETEBACK 2326
#define SCI_TAB 2327
#define SCI_BACKTAB 2328
#define SCI_NEWLINE 2329
#define SCI_FORMFEED 2330
#define SCI_VCHOME 2331
#define SCI_VCHOMEEXTEND 2332
#define SCI_ZOOMIN 2333
#define SCI_ZOOMOUT 2334
#define SCI_DELWORDLEFT 2335
#define SCI_DELWORDRIGHT 2336
#define SCI_LINECUT 2337
#define SCI_LINEDELETE 2338
#define SCI_LINETRANSPOSE 2339
#define SCI_LINEDUPLICATE 2404
#define SCI_LOWERCASE 2340
#define SCI_UPPERCASE 2341
#define SCI_LINESCROLLDOWN 2342
#define SCI_LINESCROLLUP 2343
#define SCI_DELETEBACKNOTLINE 2344
#define SCI_HOMEDISPLAY 2345
#define SCI_HOMEDISPLAYEXTEND 2346
#define SCI_LINEENDDISPLAY 2347
#define SCI_LINEENDDISPLAYEXTEND 2348
#define SCI_HOMEWRAP 2349
#define SCI_HOMEWRAPEXTEND 2450
#define SCI_LINEENDWRAP 2451
#define SCI_LINEENDWRAPEXTEND 2452
#define SCI_VCHOMEWRAP 2453
#define SCI_VCHOMEWRAPEXTEND 2454
#define SCI_LINECOPY 2455
#define SCI_MOVECARETINSIDEVIEW 2401
#define SCI_LINELENGTH 2350
#define SCI_BRACEHIGHLIGHT 2351
#define SCI_BRACEBADLIGHT 2352
#define SCI_BRACEMATCH 2353
#define SCI_GETVIEWEOL 2355
#define SCI_SETVIEWEOL 2356
#define SCI_GETDOCPOINTER 2357
#define SCI_SETDOCPOINTER 2358
#define SCI_SETMODEVENTMASK 2359
#define EDGE_NONE 0
#define EDGE_LINE 1
#define EDGE_BACKGROUND 2
#define SCI_GETEDGECOLUMN 2360
#define SCI_SETEDGECOLUMN 2361
#define SCI_GETEDGEMODE 2362
#define SCI_SETEDGEMODE 2363
#define SCI_GETEDGECOLOUR 2364
#define SCI_SETEDGECOLOUR 2365
#define SCI_SEARCHANCHOR 2366
#define SCI_SEARCHNEXT 2367
#define SCI_SEARCHPREV 2368
#define SCI_LINESONSCREEN 2370
#define SCI_USEPOPUP 2371
#define SCI_SELECTIONISRECTANGLE 2372
#define SCI_SETZOOM 2373
#define SCI_GETZOOM 2374
#define SCI_CREATEDOCUMENT 2375
#define SCI_ADDREFDOCUMENT 2376
#define SCI_RELEASEDOCUMENT 2377
#define SCI_GETMODEVENTMASK 2378
#define SCI_SETFOCUS 2380
#define SCI_GETFOCUS 2381
#define SCI_SETSTATUS 2382
#define SCI_GETSTATUS 2383
#define SCI_SETMOUSEDOWNCAPTURES 2384
#define SCI_GETMOUSEDOWNCAPTURES 2385
#define SC_CURSORNORMAL -1
#define SC_CURSORWAIT 4
#define SCI_SETCURSOR 2386
#define SCI_GETCURSOR 2387
#define SCI_SETCONTROLCHARSYMBOL 2388
#define SCI_GETCONTROLCHARSYMBOL 2389
#define SCI_WORDPARTLEFT 2390
#define SCI_WORDPARTLEFTEXTEND 2391
#define SCI_WORDPARTRIGHT 2392
#define SCI_WORDPARTRIGHTEXTEND 2393
#define VISIBLE_SLOP 0x01
#define VISIBLE_STRICT 0x04
#define SCI_SETVISIBLEPOLICY 2394
#define SCI_DELLINELEFT 2395
#define SCI_DELLINERIGHT 2396
#define SCI_SETXOFFSET 2397
#define SCI_GETXOFFSET 2398
#define SCI_CHOOSECARETX 2399
#define SCI_GRABFOCUS 2400
#define CARET_SLOP 0x01
#define CARET_STRICT 0x04
#define CARET_JUMPS 0x10
#define CARET_EVEN 0x08
#define SCI_SETXCARETPOLICY 2402
#define SCI_SETYCARETPOLICY 2403
#define SCI_SETPRINTWRAPMODE 2406
#define SCI_GETPRINTWRAPMODE 2407
#define SCI_SETHOTSPOTACTIVEFORE 2410
#define SCI_SETHOTSPOTACTIVEBACK 2411
#define SCI_SETHOTSPOTACTIVEUNDERLINE 2412
#define SCI_SETHOTSPOTSINGLELINE 2421
#define SCI_PARADOWN 2413
#define SCI_PARADOWNEXTEND 2414
#define SCI_PARAUP 2415
#define SCI_PARAUPEXTEND 2416
#define SCI_POSITIONBEFORE 2417
#define SCI_POSITIONAFTER 2418
#define SCI_COPYRANGE 2419
#define SCI_COPYTEXT 2420
#define SC_SEL_STREAM 0
#define SC_SEL_RECTANGLE 1
#define SC_SEL_LINES 2
#define SCI_SETSELECTIONMODE 2422
#define SCI_GETSELECTIONMODE 2423
#define SCI_GETLINESELSTARTPOSITION 2424
#define SCI_GETLINESELENDPOSITION 2425
#define SCI_LINEDOWNRECTEXTEND 2426
#define SCI_LINEUPRECTEXTEND 2427
#define SCI_CHARLEFTRECTEXTEND 2428
#define SCI_CHARRIGHTRECTEXTEND 2429
#define SCI_HOMERECTEXTEND 2430
#define SCI_VCHOMERECTEXTEND 2431
#define SCI_LINEENDRECTEXTEND 2432
#define SCI_PAGEUPRECTEXTEND 2433
#define SCI_PAGEDOWNRECTEXTEND 2434
#define SCI_STUTTEREDPAGEUP 2435
#define SCI_STUTTEREDPAGEUPEXTEND 2436
#define SCI_STUTTEREDPAGEDOWN 2437
#define SCI_STUTTEREDPAGEDOWNEXTEND 2438
#define SCI_WORDLEFTEND 2439
#define SCI_WORDLEFTENDEXTEND 2440
#define SCI_WORDRIGHTEND 2441
#define SCI_WORDRIGHTENDEXTEND 2442
#define SCI_SETWHITESPACECHARS 2443
#define SCI_SETCHARSDEFAULT 2444
#define SCI_AUTOCGETCURRENT 2445
#define SCI_ALLOCATE 2446
#define SCI_TARGETASUTF8 2447
#define SCI_SETLENGTHFORENCODE 2448
#define SCI_ENCODEDFROMUTF8 2449
#define SCI_FINDCOLUMN 2456
#define SCI_GETCARETSTICKY 2457
#define SCI_SETCARETSTICKY 2458
#define SCI_TOGGLECARETSTICKY 2459
#define SCI_SETPASTECONVERTENDINGS 2467
#define SCI_GETPASTECONVERTENDINGS 2468
#define SCI_SELECTIONDUPLICATE 2469
#define SCI_STARTRECORD 3001
#define SCI_STOPRECORD 3002
#define SCI_SETLEXER 4001
#define SCI_GETLEXER 4002
#define SCI_COLOURISE 4003
#define SCI_SETPROPERTY 4004
#define SCI_OPEN_INCLUDE 4110
#define KEYWORDSET_MAX 8
#define SCI_SETKEYWORDS 4005
#define SCI_SETLEXERLANGUAGE 4006
#define SCI_LOADLEXERLIBRARY 4007
#define SCI_GETPROPERTY 4008
#define SCI_GETPROPERTYEXPANDED 4009
#define SCI_GETPROPERTYINT 4010
#define SCI_GETSTYLEBITSNEEDED 4011
#define SC_MOD_INSERTTEXT 0x1
#define SC_MOD_DELETETEXT 0x2
#define SC_MOD_CHANGESTYLE 0x4
#define SC_MOD_CHANGEFOLD 0x8
#define SC_PERFORMED_USER 0x10
#define SC_PERFORMED_UNDO 0x20
#define SC_PERFORMED_REDO 0x40
#define SC_MULTISTEPUNDOREDO 0x80
#define SC_LASTSTEPINUNDOREDO 0x100
#define SC_MOD_CHANGEMARKER 0x200
#define SC_MOD_BEFOREINSERT 0x400
#define SC_MOD_BEFOREDELETE 0x800
#define SC_MULTILINEUNDOREDO 0x1000
#define SC_MODEVENTMASKALL 0x1FFF
#define SCEN_CHANGE 768
#define SCEN_SETFOCUS 512
#define SCEN_KILLFOCUS 256
#define SCK_DOWN 300
#define SCK_UP 301
#define SCK_LEFT 302
#define SCK_RIGHT 303
#define SCK_HOME 304
#define SCK_END 305
#define SCK_PRIOR 306
#define SCK_NEXT 307
#define SCK_DELETE 308
#define SCK_INSERT 309
#define SCK_ESCAPE 7
#define SCK_BACK 8
#define SCK_TAB 9
#define SCK_RETURN 13
#define SCK_ADD 310
#define SCK_SUBTRACT 311
#define SCK_DIVIDE 312
#define SCMOD_NORM 0
#define SCMOD_SHIFT 1
#define SCMOD_CTRL 2
#define SCMOD_ALT 4
#define SCN_STYLENEEDED 2000
#define SCN_CHARADDED 2001
#define SCN_SAVEPOINTREACHED 2002
#define SCN_SAVEPOINTLEFT 2003
#define SCN_MODIFYATTEMPTRO 2004
#define SCN_KEY 2005
#define SCN_DOUBLECLICK 2006
#define SCN_UPDATEUI 2007
#define SCN_MODIFIED 2008
#define SCN_MACRORECORD 2009
#define SCN_MARGINCLICK 2010
#define SCN_NEEDSHOWN 2011
#define SCN_PAINTED 2013
#define SCN_USERLISTSELECTION 2014
#define SCN_URIDROPPED 2015
#define SCN_DWELLSTART 2016
#define SCN_DWELLEND 2017
#define SCN_ZOOM 2018
#define SCN_HOTSPOTCLICK 2019
#define SCN_HOTSPOTDOUBLECLICK 2020
#define SCN_CALLTIPCLICK 2021
#define SCN_AUTOCSELECTION 2022
//--Autogenerated -- end of section automatically generated from Scintilla.iface
// These structures are defined to be exactly the same shape as the Win32
// CHARRANGE, TEXTRANGE, FINDTEXTEX, FORMATRANGE, and NMHDR structs.
// So older code that treats Scintilla as a RichEdit will work.
struct CharacterRange {
long cpMin;
long cpMax;
};
struct TextRange {
struct CharacterRange chrg;
char *lpstrText;
};
struct TextToFind {
struct CharacterRange chrg;
char *lpstrText;
struct CharacterRange chrgText;
};
#ifdef PLATFORM_H
// This structure is used in printing and requires some of the graphics types
// from Platform.h. Not needed by most client code.
struct RangeToFormat {
SurfaceID hdc;
SurfaceID hdcTarget;
PRectangle rc;
PRectangle rcPage;
CharacterRange chrg;
};
#endif
struct NotifyHeader {
// Compatible with Windows NMHDR.
// hwndFrom is really an environment specific window handle or pointer
// but most clients of Scintilla.h do not have this type visible.
void *hwndFrom;
uptr_t idFrom;
unsigned int code;
};
struct SCNotification {
struct NotifyHeader nmhdr;
int position; // SCN_STYLENEEDED, SCN_MODIFIED, SCN_DWELLSTART, SCN_DWELLEND
int ch; // SCN_CHARADDED, SCN_KEY
int modifiers; // SCN_KEY
int modificationType; // SCN_MODIFIED
const char *text; // SCN_MODIFIED, SCN_USERLISTSELECTION, SCN_AUTOCSELECTION
int length; // SCN_MODIFIED
int linesAdded; // SCN_MODIFIED
int message; // SCN_MACRORECORD
uptr_t wParam; // SCN_MACRORECORD
sptr_t lParam; // SCN_MACRORECORD
int line; // SCN_MODIFIED
int foldLevelNow; // SCN_MODIFIED
int foldLevelPrev; // SCN_MODIFIED
int margin; // SCN_MARGINCLICK
int listType; // SCN_USERLISTSELECTION
int x; // SCN_DWELLSTART, SCN_DWELLEND
int y; // SCN_DWELLSTART, SCN_DWELLEND
};
// Deprecation section listing all API features that are deprecated and will
// will be removed completely in a future version.
// To enable these features define INCLUDE_DEPRECATED_FEATURES
#ifdef INCLUDE_DEPRECATED_FEATURES
#define SCI_SETCARETPOLICY 2369
#define CARET_CENTER 0x02
#define CARET_XEVEN 0x08
#define CARET_XJUMPS 0x10
#define SCN_POSCHANGED 2012
#define SCN_CHECKBRACE 2007
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,728 @@
// Scintilla source code edit control
/** @file ScintillaBase.cxx
** An enhanced subclass of Editor with calltips, autocomplete and context menu.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "Platform.h"
#include "Scintilla.h"
#include "PropSet.h"
#ifdef SCI_LEXER
#include "SciLexer.h"
#include "Accessor.h"
#include "DocumentAccessor.h"
#include "KeyWords.h"
#endif
#include "ContractionState.h"
#include "SVector.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "XPM.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "AutoComplete.h"
#include "Document.h"
#include "Editor.h"
#include "ScintillaBase.h"
ScintillaBase::ScintillaBase() {
displayPopupMenu = true;
listType = 0;
maxListWidth = 0;
#ifdef SCI_LEXER
lexLanguage = SCLEX_CONTAINER;
performingStyle = false;
lexCurrent = 0;
for (int wl = 0;wl < numWordLists;wl++)
keyWordLists[wl] = new WordList;
keyWordLists[numWordLists] = 0;
#endif
}
ScintillaBase::~ScintillaBase() {
#ifdef SCI_LEXER
for (int wl = 0;wl < numWordLists;wl++)
delete keyWordLists[wl];
#endif
}
void ScintillaBase::Finalise() {
Editor::Finalise();
popup.Destroy();
}
void ScintillaBase::RefreshColourPalette(Palette &pal, bool want) {
Editor::RefreshColourPalette(pal, want);
ct.RefreshColourPalette(pal, want);
}
void ScintillaBase::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) {
bool isFillUp = ac.Active() && ac.IsFillUpChar(*s);
if (!isFillUp) {
Editor::AddCharUTF(s, len, treatAsDBCS);
}
if (ac.Active()) {
AutoCompleteCharacterAdded(s[0]);
// For fill ups add the character after the autocompletion has
// triggered so containers see the key so can display a calltip.
if (isFillUp) {
Editor::AddCharUTF(s, len, treatAsDBCS);
}
}
}
void ScintillaBase::Command(int cmdId) {
switch (cmdId) {
case idAutoComplete: // Nothing to do
break;
case idCallTip: // Nothing to do
break;
case idcmdUndo:
WndProc(SCI_UNDO, 0, 0);
break;
case idcmdRedo:
WndProc(SCI_REDO, 0, 0);
break;
case idcmdCut:
WndProc(SCI_CUT, 0, 0);
break;
case idcmdCopy:
WndProc(SCI_COPY, 0, 0);
break;
case idcmdPaste:
WndProc(SCI_PASTE, 0, 0);
break;
case idcmdDelete:
WndProc(SCI_CLEAR, 0, 0);
break;
case idcmdSelectAll:
WndProc(SCI_SELECTALL, 0, 0);
break;
}
}
int ScintillaBase::KeyCommand(unsigned int iMessage) {
// Most key commands cancel autocompletion mode
if (ac.Active()) {
switch (iMessage) {
// Except for these
case SCI_LINEDOWN:
AutoCompleteMove(1);
return 0;
case SCI_LINEUP:
AutoCompleteMove( -1);
return 0;
case SCI_PAGEDOWN:
AutoCompleteMove(5);
return 0;
case SCI_PAGEUP:
AutoCompleteMove( -5);
return 0;
case SCI_VCHOME:
AutoCompleteMove( -5000);
return 0;
case SCI_LINEEND:
AutoCompleteMove(5000);
return 0;
case SCI_DELETEBACK:
DelCharBack(true);
AutoCompleteCharacterDeleted();
EnsureCaretVisible();
return 0;
case SCI_DELETEBACKNOTLINE:
DelCharBack(false);
AutoCompleteCharacterDeleted();
EnsureCaretVisible();
return 0;
case SCI_TAB:
AutoCompleteCompleted();
return 0;
case SCI_NEWLINE:
AutoCompleteCompleted();
return 0;
default:
ac.Cancel();
}
}
if (ct.inCallTipMode) {
if (
(iMessage != SCI_CHARLEFT) &&
(iMessage != SCI_CHARLEFTEXTEND) &&
(iMessage != SCI_CHARRIGHT) &&
(iMessage != SCI_CHARLEFTEXTEND) &&
(iMessage != SCI_EDITTOGGLEOVERTYPE) &&
(iMessage != SCI_DELETEBACK) &&
(iMessage != SCI_DELETEBACKNOTLINE)
) {
ct.CallTipCancel();
}
if ((iMessage == SCI_DELETEBACK) || (iMessage == SCI_DELETEBACKNOTLINE)) {
if (currentPos <= ct.posStartCallTip) {
ct.CallTipCancel();
}
}
}
return Editor::KeyCommand(iMessage);
}
void ScintillaBase::AutoCompleteDoubleClick(void* p) {
ScintillaBase* sci = reinterpret_cast<ScintillaBase*>(p);
sci->AutoCompleteCompleted();
}
void ScintillaBase::AutoCompleteStart(int lenEntered, const char *list) {
//Platform::DebugPrintf("AutoComplete %s\n", list);
ct.CallTipCancel();
if (ac.chooseSingle && (listType == 0)) {
if (list && !strchr(list, ac.GetSeparator())) {
const char *typeSep = strchr(list, ac.GetTypesep());
size_t lenInsert = (typeSep) ? (typeSep-list) : strlen(list);
if (ac.ignoreCase) {
SetEmptySelection(currentPos - lenEntered);
pdoc->DeleteChars(currentPos, lenEntered);
SetEmptySelection(currentPos);
pdoc->InsertString(currentPos, list, lenInsert);
SetEmptySelection(currentPos + lenInsert);
} else {
SetEmptySelection(currentPos);
pdoc->InsertString(currentPos, list + lenEntered, lenInsert - lenEntered);
SetEmptySelection(currentPos + lenInsert - lenEntered);
}
return;
}
}
ac.Start(wMain, idAutoComplete, currentPos, LocationFromPosition(currentPos),
lenEntered, vs.lineHeight, IsUnicodeMode());
PRectangle rcClient = GetClientRectangle();
Point pt = LocationFromPosition(currentPos - lenEntered);
int heightLB = 100;
int widthLB = 100;
if (pt.x >= rcClient.right - widthLB) {
HorizontalScrollTo(xOffset + pt.x - rcClient.right + widthLB);
Redraw();
pt = LocationFromPosition(currentPos);
}
PRectangle rcac;
rcac.left = pt.x - ac.lb->CaretFromEdge();
if (pt.y >= rcClient.bottom - heightLB && // Wont fit below.
pt.y >= (rcClient.bottom + rcClient.top) / 2) { // and there is more room above.
rcac.top = pt.y - heightLB;
if (rcac.top < 0) {
heightLB += rcac.top;
rcac.top = 0;
}
} else {
rcac.top = pt.y + vs.lineHeight;
}
rcac.right = rcac.left + widthLB;
rcac.bottom = Platform::Minimum(rcac.top + heightLB, rcClient.bottom);
ac.lb->SetPositionRelative(rcac, wMain);
ac.lb->SetFont(vs.styles[STYLE_DEFAULT].font);
unsigned int aveCharWidth = vs.styles[STYLE_DEFAULT].aveCharWidth;
ac.lb->SetAverageCharWidth(aveCharWidth);
ac.lb->SetDoubleClickAction(AutoCompleteDoubleClick, this);
ac.SetList(list);
// Fiddle the position of the list so it is right next to the target and wide enough for all its strings
PRectangle rcList = ac.lb->GetDesiredRect();
int heightAlloced = rcList.bottom - rcList.top;
widthLB = Platform::Maximum(widthLB, rcList.right - rcList.left);
if (maxListWidth != 0)
widthLB = Platform::Minimum(widthLB, aveCharWidth*maxListWidth);
// Make an allowance for large strings in list
rcList.left = pt.x - ac.lb->CaretFromEdge();
rcList.right = rcList.left + widthLB;
if (((pt.y + vs.lineHeight) >= (rcClient.bottom - heightAlloced)) && // Wont fit below.
((pt.y + vs.lineHeight / 2) >= (rcClient.bottom + rcClient.top) / 2)) { // and there is more room above.
rcList.top = pt.y - heightAlloced;
} else {
rcList.top = pt.y + vs.lineHeight;
}
rcList.bottom = rcList.top + heightAlloced;
ac.lb->SetPositionRelative(rcList, wMain);
ac.Show(true);
if (lenEntered != 0) {
AutoCompleteMoveToCurrentWord();
}
}
void ScintillaBase::AutoCompleteCancel() {
ac.Cancel();
}
void ScintillaBase::AutoCompleteMove(int delta) {
ac.Move(delta);
}
void ScintillaBase::AutoCompleteMoveToCurrentWord() {
char wordCurrent[1000];
int i;
int startWord = ac.posStart - ac.startLen;
for (i = startWord; i < currentPos && i - startWord < 1000; i++)
wordCurrent[i - startWord] = pdoc->CharAt(i);
wordCurrent[Platform::Minimum(i - startWord, 999)] = '\0';
ac.Select(wordCurrent);
}
void ScintillaBase::AutoCompleteCharacterAdded(char ch) {
if (ac.IsFillUpChar(ch)) {
AutoCompleteCompleted();
} else if (ac.IsStopChar(ch)) {
ac.Cancel();
} else {
AutoCompleteMoveToCurrentWord();
}
}
void ScintillaBase::AutoCompleteCharacterDeleted() {
if (currentPos < ac.posStart - ac.startLen) {
ac.Cancel();
} else if (ac.cancelAtStartPos && (currentPos <= ac.posStart)) {
ac.Cancel();
} else {
AutoCompleteMoveToCurrentWord();
}
}
void ScintillaBase::AutoCompleteCompleted() {
int item = ac.lb->GetSelection();
char selected[1000];
selected[0] = '\0';
if (item != -1) {
ac.lb->GetValue(item, selected, sizeof(selected));
} else {
ac.Cancel();
return;
}
ac.Show(false);
listSelected = selected;
SCNotification scn = {0};
scn.nmhdr.code = listType > 0 ? SCN_USERLISTSELECTION : SCN_AUTOCSELECTION;
scn.message = 0;
scn.wParam = listType;
scn.listType = listType;
Position firstPos = ac.posStart - ac.startLen;
scn.lParam = firstPos;
scn.text = listSelected.c_str();
NotifyParent(scn);
if (!ac.Active())
return;
ac.Cancel();
if (listType > 0)
return;
Position endPos = currentPos;
if (ac.dropRestOfWord)
endPos = pdoc->ExtendWordSelect(endPos, 1, true);
if (endPos < firstPos)
return;
pdoc->BeginUndoAction();
if (endPos != firstPos) {
pdoc->DeleteChars(firstPos, endPos - firstPos);
}
SetEmptySelection(ac.posStart);
if (item != -1) {
SString piece = selected;
pdoc->InsertString(firstPos, piece.c_str());
SetEmptySelection(firstPos + static_cast<int>(piece.length()));
}
pdoc->EndUndoAction();
}
int ScintillaBase::AutoCompleteGetCurrent() {
return ac.lb->GetSelection();
}
void ScintillaBase::CallTipShow(Point pt, const char *defn) {
AutoCompleteCancel();
pt.y += vs.lineHeight;
PRectangle rc = ct.CallTipStart(currentPos, pt,
defn,
vs.styles[STYLE_DEFAULT].fontName,
vs.styles[STYLE_DEFAULT].sizeZoomed,
CodePage(),
vs.styles[STYLE_DEFAULT].characterSet,
wMain);
// If the call-tip window would be out of the client
// space, adjust so it displays above the text.
PRectangle rcClient = GetClientRectangle();
if (rc.bottom > rcClient.bottom) {
int offset = vs.lineHeight + rc.Height();
rc.top -= offset;
rc.bottom -= offset;
}
// Now display the window.
CreateCallTipWindow(rc);
ct.wCallTip.SetPositionRelative(rc, wMain);
ct.wCallTip.Show();
}
void ScintillaBase::CallTipClick() {
SCNotification scn = {0};
scn.nmhdr.code = SCN_CALLTIPCLICK;
scn.position = ct.clickPlace;
NotifyParent(scn);
}
void ScintillaBase::ContextMenu(Point pt) {
// Save any prior highlighting
int tmpPos = currentPos;
int tmpAnchor = anchor;
MovePositionTo(PositionFromLocation(pt));
if (tmpPos != tmpAnchor)
{
SetSelection(tmpAnchor, tmpPos);
}
if (displayPopupMenu) {
bool writable = !WndProc(SCI_GETREADONLY, 0, 0);
popup.CreatePopUp();
AddToPopUp("Undo", idcmdUndo, writable && pdoc->CanUndo());
AddToPopUp("Redo", idcmdRedo, writable && pdoc->CanRedo());
AddToPopUp("");
AddToPopUp("Cut", idcmdCut, writable && currentPos != anchor);
AddToPopUp("Copy", idcmdCopy, currentPos != anchor);
AddToPopUp("Paste", idcmdPaste, writable && WndProc(SCI_CANPASTE, 0, 0));
AddToPopUp("Delete", idcmdDelete, writable && currentPos != anchor);
AddToPopUp("");
AddToPopUp("Select All", idcmdSelectAll);
AddToPopUp("");
AddToPopUp("Search for this phrase in all profiles", APPARMOR_SEARCH_PHRASE_IN_ALL_PROFILES, currentPos != anchor);
AddToPopUp("Insert an include", APPARMOR_INSERT_INCLUDE_MENU_ITEM);
if (pdoc->StyleAt(currentPos) == SCE_APPARMOR_INCLUDE)
AddToPopUp("Open included file in New Window", APPARMOR_OPEN_INCLUDE_MENU_ITEM);
popup.Show(pt, wMain);
}
}
void ScintillaBase::CancelModes() {
AutoCompleteCancel();
ct.CallTipCancel();
Editor::CancelModes();
}
void ScintillaBase::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt) {
CancelModes();
Editor::ButtonDown(pt, curTime, shift, ctrl, alt);
}
#ifdef SCI_LEXER
void ScintillaBase::SetLexer(uptr_t wParam) {
lexLanguage = wParam;
lexCurrent = LexerModule::Find(lexLanguage);
if (!lexCurrent)
lexCurrent = LexerModule::Find(SCLEX_NULL);
}
void ScintillaBase::SetLexerLanguage(const char *languageName) {
lexLanguage = SCLEX_CONTAINER;
lexCurrent = LexerModule::Find(languageName);
if (!lexCurrent)
lexCurrent = LexerModule::Find(SCLEX_NULL);
if (lexCurrent)
lexLanguage = lexCurrent->GetLanguage();
}
void ScintillaBase::Colourise(int start, int end) {
if (!performingStyle) {
// Protect against reentrance, which may occur, for example, when
// fold points are discovered while performing styling and the folding
// code looks for child lines which may trigger styling.
performingStyle = true;
int lengthDoc = pdoc->Length();
if (end == -1)
end = lengthDoc;
int len = end - start;
PLATFORM_ASSERT(len >= 0);
PLATFORM_ASSERT(start + len <= lengthDoc);
//WindowAccessor styler(wMain.GetID(), props);
DocumentAccessor styler(pdoc, props, wMain.GetID());
int styleStart = 0;
if (start > 0)
styleStart = styler.StyleAt(start - 1);
styler.SetCodePage(pdoc->dbcsCodePage);
if (lexCurrent && (len > 0)) { // Should always succeed as null lexer should always be available
lexCurrent->Lex(start, len, styleStart, keyWordLists, styler);
styler.Flush();
if (styler.GetPropertyInt("fold")) {
lexCurrent->Fold(start, len, styleStart, keyWordLists, styler);
styler.Flush();
}
}
performingStyle = false;
}
}
#endif
void ScintillaBase::NotifyStyleToNeeded(int endStyleNeeded) {
#ifdef SCI_LEXER
if (lexLanguage != SCLEX_CONTAINER) {
int endStyled = WndProc(SCI_GETENDSTYLED, 0, 0);
int lineEndStyled = WndProc(SCI_LINEFROMPOSITION, endStyled, 0);
endStyled = WndProc(SCI_POSITIONFROMLINE, lineEndStyled, 0);
Colourise(endStyled, endStyleNeeded);
return;
}
#endif
Editor::NotifyStyleToNeeded(endStyleNeeded);
}
sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
switch (iMessage) {
case SCI_AUTOCSHOW:
listType = 0;
AutoCompleteStart(wParam, reinterpret_cast<const char *>(lParam));
break;
case SCI_AUTOCCANCEL:
AutoCompleteCancel();
break;
case SCI_AUTOCACTIVE:
return ac.Active();
case SCI_AUTOCPOSSTART:
return ac.posStart;
case SCI_AUTOCCOMPLETE:
AutoCompleteCompleted();
break;
case SCI_AUTOCSETSEPARATOR:
ac.SetSeparator(static_cast<char>(wParam));
break;
case SCI_AUTOCGETSEPARATOR:
return ac.GetSeparator();
case SCI_AUTOCSTOPS:
ac.SetStopChars(reinterpret_cast<char *>(lParam));
break;
case SCI_AUTOCSELECT:
ac.Select(reinterpret_cast<char *>(lParam));
break;
case SCI_AUTOCGETCURRENT:
return AutoCompleteGetCurrent();
case SCI_AUTOCSETCANCELATSTART:
ac.cancelAtStartPos = wParam != 0;
break;
case SCI_AUTOCGETCANCELATSTART:
return ac.cancelAtStartPos;
case SCI_AUTOCSETFILLUPS:
ac.SetFillUpChars(reinterpret_cast<char *>(lParam));
break;
case SCI_AUTOCSETCHOOSESINGLE:
ac.chooseSingle = wParam != 0;
break;
case SCI_AUTOCGETCHOOSESINGLE:
return ac.chooseSingle;
case SCI_AUTOCSETIGNORECASE:
ac.ignoreCase = wParam != 0;
break;
case SCI_AUTOCGETIGNORECASE:
return ac.ignoreCase;
case SCI_USERLISTSHOW:
listType = wParam;
AutoCompleteStart(0, reinterpret_cast<const char *>(lParam));
break;
case SCI_AUTOCSETAUTOHIDE:
ac.autoHide = wParam != 0;
break;
case SCI_AUTOCGETAUTOHIDE:
return ac.autoHide;
case SCI_AUTOCSETDROPRESTOFWORD:
ac.dropRestOfWord = wParam != 0;
break;
case SCI_AUTOCGETDROPRESTOFWORD:
return ac.dropRestOfWord;
case SCI_AUTOCSETMAXHEIGHT:
ac.lb->SetVisibleRows(wParam);
break;
case SCI_AUTOCGETMAXHEIGHT:
return ac.lb->GetVisibleRows();
case SCI_AUTOCSETMAXWIDTH:
maxListWidth = wParam;
break;
case SCI_AUTOCGETMAXWIDTH:
return maxListWidth;
case SCI_REGISTERIMAGE:
ac.lb->RegisterImage(wParam, reinterpret_cast<const char *>(lParam));
break;
case SCI_CLEARREGISTEREDIMAGES:
ac.lb->ClearRegisteredImages();
break;
case SCI_AUTOCSETTYPESEPARATOR:
ac.SetTypesep(static_cast<char>(wParam));
break;
case SCI_AUTOCGETTYPESEPARATOR:
return ac.GetTypesep();
case SCI_CALLTIPSHOW:
CallTipShow(LocationFromPosition(wParam),
reinterpret_cast<const char *>(lParam));
break;
case SCI_CALLTIPCANCEL:
ct.CallTipCancel();
break;
case SCI_CALLTIPACTIVE:
return ct.inCallTipMode;
case SCI_CALLTIPPOSSTART:
return ct.posStartCallTip;
case SCI_CALLTIPSETHLT:
ct.SetHighlight(wParam, lParam);
break;
case SCI_CALLTIPSETBACK:
ct.colourBG = ColourDesired(wParam);
InvalidateStyleRedraw();
break;
case SCI_CALLTIPSETFORE:
ct.colourUnSel = ColourDesired(wParam);
InvalidateStyleRedraw();
break;
case SCI_CALLTIPSETFOREHLT:
ct.colourSel = ColourDesired(wParam);
InvalidateStyleRedraw();
break;
case SCI_USEPOPUP:
displayPopupMenu = wParam != 0;
break;
#ifdef SCI_LEXER
case SCI_SETLEXER:
SetLexer(wParam);
lexLanguage = wParam;
break;
case SCI_GETLEXER:
return lexLanguage;
case SCI_COLOURISE:
if (lexLanguage == SCLEX_CONTAINER) {
pdoc->ModifiedAt(wParam);
NotifyStyleToNeeded((lParam == -1) ? pdoc->Length() : lParam);
} else {
Colourise(wParam, lParam);
}
Redraw();
break;
case SCI_SETPROPERTY:
props.Set(reinterpret_cast<const char *>(wParam),
reinterpret_cast<const char *>(lParam));
break;
case SCI_GETPROPERTY: {
SString val = props.Get(reinterpret_cast<const char *>(wParam));
const int n = val.length();
if (lParam != 0) {
char *ptr = reinterpret_cast<char *>(lParam);
memcpy(ptr, val.c_str(), n);
ptr[n] = '\0'; // terminate
}
return n; // Not including NUL
}
case SCI_GETPROPERTYEXPANDED: {
SString val = props.GetExpanded(reinterpret_cast<const char *>(wParam));
const int n = val.length();
if (lParam != 0) {
char *ptr = reinterpret_cast<char *>(lParam);
memcpy(ptr, val.c_str(), n);
ptr[n] = '\0'; // terminate
}
return n; // Not including NUL
}
case SCI_GETPROPERTYINT:
return props.GetInt(reinterpret_cast<const char *>(wParam), lParam);
case SCI_SETKEYWORDS:
if (wParam < numWordLists) {
keyWordLists[wParam]->Clear();
keyWordLists[wParam]->Set(reinterpret_cast<const char *>(lParam));
}
break;
case SCI_SETLEXERLANGUAGE:
SetLexerLanguage(reinterpret_cast<const char *>(lParam));
break;
case SCI_GETSTYLEBITSNEEDED:
return lexCurrent ? lexCurrent->GetStyleBitsNeeded() : 5;
#endif
default:
return Editor::WndProc(iMessage, wParam, lParam);
}
return 0l;
}

View File

@@ -0,0 +1,95 @@
// Scintilla source code edit control
/** @file ScintillaBase.h
** Defines an enhanced subclass of Editor with calltips, autocomplete and context menu.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef SCINTILLABASE_H
#define SCINTILLABASE_H
#define APPARMOR_OPEN_INCLUDE_MENU_ITEM 4891
#define APPARMOR_INSERT_INCLUDE_MENU_ITEM 4892
#define APPARMOR_SEARCH_PHRASE_IN_ALL_PROFILES 4893
/**
*/
class ScintillaBase : public Editor {
// Private so ScintillaBase objects can not be copied
ScintillaBase(const ScintillaBase &) : Editor() {}
ScintillaBase &operator=(const ScintillaBase &) { return *this; }
protected:
/** Enumeration of commands and child windows. */
enum {
idCallTip=1,
idAutoComplete=2,
idcmdUndo=10,
idcmdRedo=11,
idcmdCut=12,
idcmdCopy=13,
idcmdPaste=14,
idcmdDelete=15,
idcmdSelectAll=16,
};
bool displayPopupMenu;
Menu popup;
AutoComplete ac;
CallTip ct;
int listType; ///< 0 is an autocomplete list
SString listSelected; ///< Receives listbox selected string
int maxListWidth; /// Maximum width of list, in average character widths
bool performingStyle; ///< Prevent reentrance
#ifdef SCI_LEXER
int lexLanguage;
const LexerModule *lexCurrent;
PropSet props;
enum {numWordLists=KEYWORDSET_MAX+1};
WordList *keyWordLists[numWordLists+1];
void SetLexer(uptr_t wParam);
void SetLexerLanguage(const char *languageName);
void Colourise(int start, int end);
#endif
ScintillaBase();
virtual ~ScintillaBase();
virtual void Initialise() = 0;
virtual void Finalise() = 0;
virtual void RefreshColourPalette(Palette &pal, bool want);
virtual void AddCharUTF(char *s, unsigned int len, bool treatAsDBCS=false);
void Command(int cmdId);
virtual void CancelModes();
virtual int KeyCommand(unsigned int iMessage);
void AutoCompleteStart(int lenEntered, const char *list);
void AutoCompleteCancel();
void AutoCompleteMove(int delta);
int AutoCompleteGetCurrent();
void AutoCompleteCharacterAdded(char ch);
void AutoCompleteCharacterDeleted();
void AutoCompleteCompleted();
void AutoCompleteMoveToCurrentWord();
static void AutoCompleteDoubleClick(void* p);
void CallTipClick();
void CallTipShow(Point pt, const char *defn);
virtual void CreateCallTipWindow(PRectangle rc) = 0;
virtual void AddToPopUp(const char *label, int cmd=0, bool enabled=true) = 0;
void ContextMenu(Point pt);
virtual void ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt);
virtual void NotifyStyleToNeeded(int endStyleNeeded);
public:
// Public so scintilla_send_message can use it
virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
};
#endif

Some files were not shown because too many files have changed in this diff Show More