repo
string | commit
string | message
string | diff
string |
---|---|---|---|
onyxfish/nostaples
|
1b105b8f638b102a05ff003b89d853cf8861fd16
|
Added more detail to exception messages.
|
diff --git a/sane/saneme.py b/sane/saneme.py
index ad347c4..2a7e379 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,939 +1,963 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method,
# including those that could bubble up
from array import *
import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the application
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SaneMe(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object, perform setup, and register
the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
self._setup()
atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
"""
version_code = SANE_Int()
auth_callback = SANE_Auth_Callback(self._sane_auth_callback)
- status = sane_init(byref(version_code), auth_callback)
+ status = sane_init(byref(version_code), auth_callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
- 'sane_init returned an invalid status.')
+ 'sane_init returned an invalid status: %i.' % status)
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def _sane_auth_callback(self, resource, username, password):
"""
TODO
"""
raise NotImplementedError(
'sane_auth_callback requested, but not yet implemented.')
def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. To
ensure this method is called it is registered with atexit.
"""
for device in self._devices:
if device.is_open():
device.close()
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
# Public Methods
def get_device_list(self):
"""
Poll for connected devices. This method may take several
seconds to return.
Note that SANE is exited and re-inited before querying for
devices to workaround a limitation in SANE's USB driver
which causes the device list to only be updated on init.
This means that all settings applied to all devices will be
B{lost} and must be restored by the calling application.
This was found documented here:
U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html}
"""
if not self._version:
raise AssertionError('version was None')
# See docstring for details on this voodoo
self._shutdown()
self._setup()
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
- 'sane_get_devices returned an invalid status.')
+ 'sane_get_devices returned an invalid status: %i.' % status)
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
return self._devices
def get_device_by_name(self, name):
"""
Retrieve a L{Device} by name.
Must be preceded by a call to L{get_device_list}.
"""
for device in self._devices:
if device.name == name:
return device
- raise SaneNoSuchDeviceError()
+ raise SaneNoSuchDeviceError(
+ 'The requested device does not exist.')
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_display_name = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
- if type(ctypes_device.name) is not StringType:
- raise AssertionError('device name was not of StringType')
- if type(ctypes_device.vendor) is not StringType:
- raise AssertionError('device vendor was not of StringType')
- if type(ctypes_device.model) is not StringType:
- raise AssertionError('device model was not of StringType')
- if type(ctypes_device.type) is not StringType:
- raise AssertionError('device type was not of StringType')
+ if type(ctypes_device.name) is not str:
+ raise AssertionError(
+ 'device name was %s, expected StringType' % type(ctypes_device.name))
+ if type(ctypes_device.vendor) is not str:
+ raise AssertionError(
+ 'device vendor was %s, expected StringType' % type(ctypes_device.vendor))
+ if type(ctypes_device.model) is not str:
+ raise AssertionError(
+ 'device model was %s, expected StringType' % type(ctypes_device.model))
+ if type(ctypes_device.type) is not str:
+ raise AssertionError(
+ 'device type was %s, expected StringType' % type(ctypes_device.type))
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
self._display_name = ' '.join([self._vendor, self._model])
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_display_name(self):
"""
Get an appropriate name to use for displaying this device
to a user, e.g. 'Lexmark X1100/rev. B2'."""
return self._display_name
display_name = property(__get_display_name)
def __get_options(self):
"""Get the dictionary of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
raise SaneUnsupportedOperationError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
- raise AssertionError(
+ raise SaneInvalidParameterError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
- 'sane_open returned an invalid status.')
+ 'sane_open returned an invalid status: %i.' % status)
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
- """
- raise SaneDeviceBusyError('FIXME FIXME FIXME', device=self)
-
+ """
if self._handle:
raise AssertionError('device handle already exists.')
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
# If and exception will be thrown, nullify device handle
# so is_open() will return false for the device.
if status != SANE_STATUS_GOOD.value:
self._handle = None
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
raise SaneInvalidParameterError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
- 'sane_open returned an invalid status.')
+ 'sane_open returned an invalid status: %i.' % status)
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
TODO: handle ADF scans
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
- 'sane_start returned an invalid status.')
+ 'sane_start returned an invalid status: %i.' % status)
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
- raise SaneUnknownError()
+ raise SaneUnknownError(
+ 'sane_get_parameters returned an invalid status: %i.' % status)
scan_info = ScanInfo(sane_parameters)
# This is the size used for the scan buffer in SANE's scanimage
# utility. The precise reasoning for using 32kb is unclear.
bytes_per_read = 32768
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
cancel = False
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
- 'sane_read returned an invalid status.')
+ 'sane_read returned an invalid status: %i.' % status)
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
return None
if cancel:
raise AssertionError('cancel was true after scan completed.')
sane_cancel(self._handle)
if scan_info.total_bytes != len(data_array):
- raise AssertionError('length of scanned data did not match expected length.')
+ raise AssertionError(
+ 'length of scanned data did not match expected length.')
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'RGB', 0, 1)
else:
# TODO
raise NotImplementedError(
'Individual color frame scanned, but not yet supported.')
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint = None
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
if type(ctypes_option.name) is not StringType:
- raise AssertionError('option name was not of StringType.')
+ raise AssertionError(
+ 'option name was %s, expected StringType.' % type(ctypes_option.name))
if type(ctypes_option.title) is not StringType:
- raise AssertionError('option title was not of StringType.')
+ raise AssertionError(
+ 'option title was %s, expected StringType.' % type(ctypes_option.title))
if type(ctypes_option.desc) is not StringType:
- raise AssertionError('option description was not of StringType.')
+ raise AssertionError(
+ 'option description was %s, expected StringType.' % type(ctypes_option.desc))
if type(ctypes_option.type) is not IntType:
- raise AssertionError('option type was not of IntType.')
+ raise AssertionError(
+ 'option type was %s, expected IntType.' % type(ctypes_option.type))
if type(ctypes_option.unit) is not IntType:
- raise AssertionError('option unit was not of IntType.')
+ raise AssertionError(
+ 'option unit was %s, expected IntType.' % type(ctypes_option.unit))
if type(ctypes_option.size) is not IntType:
- raise AssertionError('option size was not of IntType.')
+ raise AssertionError(
+ 'option size was %s, expected IntType.' % type(ctypes_option.size))
if type(ctypes_option.cap) is not IntType:
- raise AssertionError('option capabilities was not of IntType.')
+ raise AssertionError(
+ 'option cap was %s, expected IntType.' % type(ctypes_option.cap))
if type(ctypes_option.constraint_type) is not IntType:
- raise AssertionError('option constraint_type was not of IntType.')
+ raise AssertionError(
+ 'option constraint_type was %s, expected IntType.' % type(ctypes_option.constraint_type))
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
if type(ctypes_option.constraint.range) is not POINTER(SANE_Range):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_Range.')
if type(ctypes_option.constraint.range.contents.min) is not IntType:
raise AssertionError('option\'s constraint range min was not of IntType.')
if type(ctypes_option.constraint.range.contents.max) is not IntType:
raise AssertionError('option\'s constraint range max was not of IntType.')
if type(ctypes_option.constraint.range.contents.quant) is not IntType:
raise AssertionError('option\'s constraint range quant was not of IntType.')
self._constraint = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
if type(ctypes_option.constraint.word_list) is not POINTER(SANE_Word):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_Word.')
word_count = ctypes_option.constraint.word_list[0]
self._constraint = []
i = 1
while(i < word_count):
self._constraint.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
if type(ctypes_option.constraint.string_list) is not POINTER(SANE_String_Const):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_String_Const.')
string_count = 0
self._constraint = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
return self._type
type = property(__get_type)
def __get_unit(self):
return self._unit
unit = property(__get_unit)
def __get_capability(self):
# TODO: break out into individual capabilities, rather than a bitset
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint(self):
"""
Get the constraint for this option.
If constraint_type is OPTION_CONSTRAINT_RANGE then
this is a tuple containing the (minimum, maximum, step)
for valid values.
If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then
this is a list of integers which are valid values.
If constraint_type is OPTION_CONSTRAINT_STRING_LIST then
this is a list of strings which are valid values.
"""
return self._constraint
constraint = property(__get_constraint)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# Constraint checking ensures this should never happen
raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
- 'sane_control_option reported a value was invalid, but no values was being set.')
+ 'sane_control_option reported a value was invalid, but no value was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
- 'sane_control_option returned an invalid status.')
+ 'sane_control_option returned an invalid status: %i.' % status)
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
- self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
+ self._log.debug(
+ 'Option %s queried, its current value is %s.',
+ self._name,
+ option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
if type(value) is not BooleanType:
- raise AssertionError('option expected BooleanType')
+ raise AssertionError(
+ 'option set with %s, expected BooleanType' % type(value))
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
if type(value) is not IntType:
- raise AssertionError('option expected IntType')
+ raise AssertionError(
+ 'option set with %s, expected IntType' % type(value))
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
if type(value) is not IntType:
- raise AssertionError('option expected IntType')
+ raise AssertionError(
+ 'option set with %s, expected IntType' % type(value))
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
if type(value) is not StringType:
- raise AssertionError('option expected StringType')
+ raise AssertionError(
+ 'optionset with %s, expected StringType' % type(value))
if len(value) + 1 > self._size:
- raise AssertionError('value for option is longer than max string size')
+ raise AssertionError(
+ 'value for option is longer than max string size')
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
if value < self._constraint[0]:
raise AssertionError('value for option is less than min.')
if value > self._constraint[1]:
raise AssertionError('value for option is greater than max.')
if value % self._constraint[2] != 0:
- raise AssertionError('value for option is not divisible by quant.')
+ raise AssertionError(
+ 'value for option is not divisible by quant.')
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
if value not in self._constraint:
- raise AssertionError('value for option not in list of valid values.')
+ raise AssertionError(
+ 'value for option not in list of valid values.')
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
if value not in self._constraint:
- raise AssertionError('value for option not in list of valid strings.')
+ raise AssertionError(
+ 'value for option not in list of valid strings.')
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# Constraint checking ensures this should never happen
raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
- 'sane_control_option returned an invalid status.')
+ 'sane_control_option returned an invalid status: %i .' % status)
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
def progress_callback(sane_info, bytes_read):
#print float(bytes_read) / sane_info.total_bytes
pass
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
sane = SaneMe(logging.getLogger())
devices = sane.get_device_list()
for dev in devices:
print dev.name
devices[0].open()
print devices[0].options.keys()
try:
devices[0].options['mode'].value = 'Gray'
except SaneReloadOptionsError:
pass
try:
devices[0].options['resolution'].value = 75
except SaneReloadOptionsError:
pass
try:
devices[0].options['preview'].value = False
except SaneReloadOptionsError:
pass
devices[0].scan(progress_callback).save('out.bmp')
devices[0].close()
\ No newline at end of file
|
onyxfish/nostaples
|
5ce32d8a8087dccf569219c5c3afe838e9e6d936
|
Removing debug code that was accidentally committed.
|
diff --git a/gui/preferences_dialog.glade b/gui/preferences_dialog.glade
index 81845ba..f2a945b 100644
--- a/gui/preferences_dialog.glade
+++ b/gui/preferences_dialog.glade
@@ -1,283 +1,283 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--Generated with glade3 3.4.5 on Sat Feb 21 21:35:09 2009 -->
+<!--Generated with glade3 3.4.5 on Sat Feb 21 22:48:17 2009 -->
<glade-interface>
<widget class="GtkDialog" id="preferences_dialog">
<property name="border_width">5</property>
- <property name="title" translatable="yes">Preferences</property>
+ <property name="title" translatable="yes">NoStaples Preferences</property>
<property name="resizable">False</property>
<property name="modal">True</property>
<property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property>
<property name="destroy_with_parent">True</property>
<property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property>
<property name="skip_taskbar_hint">True</property>
<property name="skip_pager_hint">True</property>
<property name="has_separator">False</property>
<signal name="response" handler="on_preferences_dialog_response"/>
<child internal-child="vbox">
<widget class="GtkVBox" id="dialog-vbox5">
<property name="visible">True</property>
<property name="spacing">12</property>
<signal name="add" handler="on_preferences_dialog_close"/>
<child>
<widget class="GtkNotebook" id="notebook1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<child>
<widget class="GtkAlignment" id="alignment6">
<property name="visible">True</property>
<property name="top_padding">12</property>
<property name="bottom_padding">12</property>
<property name="left_padding">12</property>
<property name="right_padding">12</property>
<child>
<widget class="GtkVBox" id="vbox3">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="spacing">6</property>
<child>
<widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
<property name="spacing">12</property>
<child>
<widget class="GtkLabel" id="label4">
<property name="visible">True</property>
<property name="label" translatable="yes">Preview Mode:</property>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkComboBox" id="preview_mode_combobox">
<property name="visible">True</property>
<property name="items" translatable="yes"></property>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
<property name="spacing">12</property>
<child>
<widget class="GtkLabel" id="label5">
<property name="visible">True</property>
<property name="label" translatable="yes">Thumbnail Size:</property>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkComboBox" id="thumbnail_size_combobox">
<property name="visible">True</property>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="label" translatable="yes">View</property>
</widget>
<packing>
<property name="type">tab</property>
<property name="tab_fill">False</property>
</packing>
</child>
<child>
<widget class="GtkAlignment" id="alignment1">
<property name="visible">True</property>
<property name="top_padding">12</property>
<property name="bottom_padding">12</property>
<property name="left_padding">12</property>
<property name="right_padding">12</property>
<child>
<widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<property name="spacing">6</property>
<child>
<widget class="GtkLabel" id="label7">
<property name="visible">True</property>
<property name="xalign">0</property>
<property name="label" translatable="yes">Blacklisted devices:</property>
<property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property>
</widget>
</child>
<child>
<widget class="GtkScrolledWindow" id="blacklist_scrolled_window">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property>
<property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property>
<property name="shadow_type">GTK_SHADOW_IN</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="remove_from_blacklist_button">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="label" translatable="yes">Remove</property>
<property name="response_id">0</property>
<signal name="clicked" handler="on_remove_from_blacklist_button_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">2</property>
</packing>
</child>
</widget>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label3">
<property name="visible">True</property>
<property name="label" translatable="yes">Devices</property>
</widget>
<packing>
<property name="type">tab</property>
<property name="position">1</property>
<property name="tab_fill">False</property>
</packing>
</child>
<child>
<widget class="GtkAlignment" id="alignment2">
<property name="visible">True</property>
<property name="top_padding">12</property>
<property name="bottom_padding">12</property>
<property name="left_padding">12</property>
<property name="right_padding">12</property>
<child>
<widget class="GtkVBox" id="vbox2">
<property name="visible">True</property>
<property name="spacing">6</property>
<child>
<widget class="GtkLabel" id="label6">
<property name="visible">True</property>
<property name="xalign">0</property>
<property name="label" translatable="yes">Keywords for autocompletion:</property>
<property name="use_markup">True</property>
<property name="wrap">True</property>
</widget>
</child>
<child>
<widget class="GtkScrolledWindow" id="keywords_scrolled_window">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property>
<property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property>
<property name="shadow_type">GTK_SHADOW_IN</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkAlignment" id="alignment3">
<property name="visible">True</property>
<child>
<widget class="GtkButton" id="remove_from_keywords_button">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="label" translatable="yes">Remove</property>
<property name="response_id">0</property>
<signal name="clicked" handler="on_remove_from_keywords_button_clicked"/>
</widget>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">2</property>
</packing>
</child>
</widget>
</child>
</widget>
<packing>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label2">
<property name="visible">True</property>
<property name="label" translatable="yes">Documents</property>
</widget>
<packing>
<property name="type">tab</property>
<property name="position">2</property>
<property name="tab_fill">False</property>
</packing>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child internal-child="action_area">
<widget class="GtkHButtonBox" id="dialog-action_area5">
<property name="visible">True</property>
<property name="layout_style">GTK_BUTTONBOX_END</property>
<child>
<placeholder/>
</child>
<child>
<widget class="GtkButton" id="preferences_close_button">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">gtk-close</property>
<property name="use_stock">True</property>
<property name="response_id">0</property>
<signal name="clicked" handler="on_preferences_close_button_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">GTK_PACK_END</property>
<property name="position">1</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">GTK_PACK_END</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
|
onyxfish/nostaples
|
87f055da70a44f888fb6becb6376787755853634
|
Modified SaneError to include the malfunctioning device as an attribute.
|
diff --git a/sane/errors.py b/sane/errors.py
index 029a9b2..1cb1380 100644
--- a/sane/errors.py
+++ b/sane/errors.py
@@ -1,144 +1,146 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Python exceptions which take the place
of SANE's status codes in the Pythonic reimplementation of the API.
These are the errors that users will need to handle.
"""
class SaneError(Exception):
"""
Base class for all SANE Errors.
"""
- pass
+ def __init__(self, message='', device=None):
+ self.message = message
+ self.device = device
class SaneUnknownError(SaneError):
"""
Exception denoting an error within the SANE library that could
not be categorized.
"""
pass
class SaneNoSuchDeviceError(SaneError):
"""
Exception denoting that a device requested by name did not
exist.
"""
pass
class SaneUnsupportedOperationError(SaneError):
"""
Exception denoting an unsupported operation was requested.
Corresponds to SANE status code SANE_STATUS_UNSUPPORTED.
"""
pass
class SaneDeviceBusyError(SaneError):
"""
Exception denoting that the requested device is being
accessed by another process.
Corresponds to SANE status code SANE_STATUS_DEVICE_BUSY.
"""
pass
class SaneInvalidParameterError(SaneError):
"""
Exception denoting that SANE received an invalid parameter
to a function call.
Corresponds to SANE status code SANE_STATUS_INVAL.
"""
pass
class SaneInvalidDataError(SaneError):
"""
Exception denoting that some data or argument was not
valid.
Corresponds to SANE status code SANE_STATUS_INVAL.
"""
pass
class SaneEndOfFileError(SaneError):
"""
TODO: Should the user ever see this? probably handled internally
Corresponds to SANE status code SANE_STATUS_EOF.
"""
pass
class SaneDeviceJammedError(SaneError):
"""
Exception denoting that the device is jammed.
Corresponds to SANE status code SANE_STATUS_JAMMED.
"""
pass
class SaneNoDocumentsError(SaneError):
"""
Exception denoting that there are pages in the document
feeder of the device.
Corresponds to SANE status code SANE_STATUS_NO_DOCS.
"""
pass
class SaneCoverOpenError(SaneError):
"""
Exception denoting that the cover of the device is open.
Corresponds to SANE status code SANE_STATUS_COVER_OPEN.
"""
pass
class SaneIOError(SaneError):
"""
Exception denoting that an IO error occurred while
communicating wtih the device.
Corresponds to the SANE status code SANE_STATUS_IO_ERROR.
"""
pass
class SaneOutOfMemoryError(SaneError):
"""
Exception denoting that SANE ran out of memory during an
operation.
Corresponds to the SANE status code SANE_STATUS_NO_MEM.
"""
pass
class SaneAccessDeniedError(SaneError):
"""
TODO: should this be handled in a special way?
Corresponds to the SANE status code SANE_STATUS_ACCESS_DENIED.
"""
pass
class SaneReloadOptionsError(SaneError):
"""
Exception denoting that a change to a SANE option has had
a cascade effect on other options and thus that they should
be read again to get the most up to date values.
"""
pass
\ No newline at end of file
diff --git a/sane/saneme.py b/sane/saneme.py
index 52b2bf3..ad347c4 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,937 +1,939 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method,
# including those that could bubble up
from array import *
import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the application
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SaneMe(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object, perform setup, and register
the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
self._setup()
atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
"""
version_code = SANE_Int()
auth_callback = SANE_Auth_Callback(self._sane_auth_callback)
status = sane_init(byref(version_code), auth_callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def _sane_auth_callback(self, resource, username, password):
"""
TODO
"""
raise NotImplementedError(
'sane_auth_callback requested, but not yet implemented.')
def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. To
ensure this method is called it is registered with atexit.
"""
for device in self._devices:
if device.is_open():
device.close()
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
# Public Methods
def get_device_list(self):
"""
Poll for connected devices. This method may take several
seconds to return.
Note that SANE is exited and re-inited before querying for
devices to workaround a limitation in SANE's USB driver
which causes the device list to only be updated on init.
This means that all settings applied to all devices will be
B{lost} and must be restored by the calling application.
This was found documented here:
U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html}
"""
if not self._version:
raise AssertionError('version was None')
# See docstring for details on this voodoo
self._shutdown()
self._setup()
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
return self._devices
def get_device_by_name(self, name):
"""
Retrieve a L{Device} by name.
Must be preceded by a call to L{get_device_list}.
"""
for device in self._devices:
if device.name == name:
return device
raise SaneNoSuchDeviceError()
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_display_name = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
if type(ctypes_device.name) is not StringType:
raise AssertionError('device name was not of StringType')
if type(ctypes_device.vendor) is not StringType:
raise AssertionError('device vendor was not of StringType')
if type(ctypes_device.model) is not StringType:
raise AssertionError('device model was not of StringType')
if type(ctypes_device.type) is not StringType:
raise AssertionError('device type was not of StringType')
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
self._display_name = ' '.join([self._vendor, self._model])
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_display_name(self):
"""
Get an appropriate name to use for displaying this device
to a user, e.g. 'Lexmark X1100/rev. B2'."""
return self._display_name
display_name = property(__get_display_name)
def __get_options(self):
"""Get the dictionary of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
raise SaneUnsupportedOperationError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
+ raise SaneDeviceBusyError('FIXME FIXME FIXME', device=self)
+
if self._handle:
raise AssertionError('device handle already exists.')
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
# If and exception will be thrown, nullify device handle
# so is_open() will return false for the device.
if status != SANE_STATUS_GOOD.value:
self._handle = None
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
raise SaneInvalidParameterError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
TODO: handle ADF scans
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
-
+
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
# This is the size used for the scan buffer in SANE's scanimage
# utility. The precise reasoning for using 32kb is unclear.
bytes_per_read = 32768
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
cancel = False
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
return None
if cancel:
raise AssertionError('cancel was true after scan completed.')
sane_cancel(self._handle)
if scan_info.total_bytes != len(data_array):
raise AssertionError('length of scanned data did not match expected length.')
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'RGB', 0, 1)
else:
# TODO
raise NotImplementedError(
'Individual color frame scanned, but not yet supported.')
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint = None
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
if type(ctypes_option.name) is not StringType:
raise AssertionError('option name was not of StringType.')
if type(ctypes_option.title) is not StringType:
raise AssertionError('option title was not of StringType.')
if type(ctypes_option.desc) is not StringType:
raise AssertionError('option description was not of StringType.')
if type(ctypes_option.type) is not IntType:
raise AssertionError('option type was not of IntType.')
if type(ctypes_option.unit) is not IntType:
raise AssertionError('option unit was not of IntType.')
if type(ctypes_option.size) is not IntType:
raise AssertionError('option size was not of IntType.')
if type(ctypes_option.cap) is not IntType:
raise AssertionError('option capabilities was not of IntType.')
if type(ctypes_option.constraint_type) is not IntType:
raise AssertionError('option constraint_type was not of IntType.')
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
if type(ctypes_option.constraint.range) is not POINTER(SANE_Range):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_Range.')
if type(ctypes_option.constraint.range.contents.min) is not IntType:
raise AssertionError('option\'s constraint range min was not of IntType.')
if type(ctypes_option.constraint.range.contents.max) is not IntType:
raise AssertionError('option\'s constraint range max was not of IntType.')
if type(ctypes_option.constraint.range.contents.quant) is not IntType:
raise AssertionError('option\'s constraint range quant was not of IntType.')
self._constraint = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
if type(ctypes_option.constraint.word_list) is not POINTER(SANE_Word):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_Word.')
word_count = ctypes_option.constraint.word_list[0]
self._constraint = []
i = 1
while(i < word_count):
self._constraint.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
if type(ctypes_option.constraint.string_list) is not POINTER(SANE_String_Const):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_String_Const.')
string_count = 0
self._constraint = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
return self._type
type = property(__get_type)
def __get_unit(self):
return self._unit
unit = property(__get_unit)
def __get_capability(self):
# TODO: break out into individual capabilities, rather than a bitset
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint(self):
"""
Get the constraint for this option.
If constraint_type is OPTION_CONSTRAINT_RANGE then
this is a tuple containing the (minimum, maximum, step)
for valid values.
If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then
this is a list of integers which are valid values.
If constraint_type is OPTION_CONSTRAINT_STRING_LIST then
this is a list of strings which are valid values.
"""
return self._constraint
constraint = property(__get_constraint)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# Constraint checking ensures this should never happen
raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported a value was invalid, but no values was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
if type(value) is not BooleanType:
raise AssertionError('option expected BooleanType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
if type(value) is not IntType:
raise AssertionError('option expected IntType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
if type(value) is not IntType:
raise AssertionError('option expected IntType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
if type(value) is not StringType:
raise AssertionError('option expected StringType')
if len(value) + 1 > self._size:
raise AssertionError('value for option is longer than max string size')
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
if value < self._constraint[0]:
raise AssertionError('value for option is less than min.')
if value > self._constraint[1]:
raise AssertionError('value for option is greater than max.')
if value % self._constraint[2] != 0:
raise AssertionError('value for option is not divisible by quant.')
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
if value not in self._constraint:
raise AssertionError('value for option not in list of valid values.')
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
if value not in self._constraint:
raise AssertionError('value for option not in list of valid strings.')
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# Constraint checking ensures this should never happen
raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
def progress_callback(sane_info, bytes_read):
#print float(bytes_read) / sane_info.total_bytes
pass
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
sane = SaneMe(logging.getLogger())
devices = sane.get_device_list()
for dev in devices:
print dev.name
devices[0].open()
print devices[0].options.keys()
try:
devices[0].options['mode'].value = 'Gray'
except SaneReloadOptionsError:
pass
try:
devices[0].options['resolution'].value = 75
except SaneReloadOptionsError:
pass
try:
devices[0].options['preview'].value = False
except SaneReloadOptionsError:
pass
devices[0].scan(progress_callback).save('out.bmp')
devices[0].close()
\ No newline at end of file
|
onyxfish/nostaples
|
6cd67b802d07021c0d88ed53a1d8504c095f4d38
|
Implemented multiple new preferences.
|
diff --git a/constants.py b/constants.py
index 2ebc999..3af88b6 100644
--- a/constants.py
+++ b/constants.py
@@ -1,98 +1,101 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
'''
This module contains global configuration constants that are not likely to
change often as well as enumeration-like state constants.
'''
import os
import gtk
import Image
from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \
B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN
PAGESIZES = {'A0' : A0,
'A1' : A1,
'A2' : A2,
'A3' : A3,
'A4' : A4,
'A5' : A5,
'A6' : A6,
'B0' : B0,
'B1' : B1,
'B2' : B2,
'B3' : B3,
'B4' : B4,
'B5' : B5,
'B6' : B6,
'LETTER' : LETTER,
'LEGAL' : LEGAL,
'ELEVENSEVENTEEN' : ELEVENSEVENTEEN}
DEFAULT_SHOW_TOOLBAR = True
DEFAULT_SHOW_STATUSBAR = True
DEFAULT_SHOW_THUMBNAILS = True
DEFAULT_SHOW_ADJUSTMENTS = False
DEFAULT_ROTATE_ALL_PAGES = False
DEFAULT_ACTIVE_SCANNER = ''
DEFAULT_SCAN_MODE = 'Color'
DEFAULT_SCAN_RESOLUTION = '75'
DEFAULT_SAVE_PATH = ''
DEFAULT_AUTHOR = os.getenv('LOGNAME')
DEFAULT_SAVED_KEYWORDS = []
DEFAULT_PREVIEW_MODE = 'Bilinear (Default)'
DEFAULT_THUMBNAIL_SIZE = 128
DEFAULT_SHOW_DOCUMENT_METADATA = True
+DEFAULT_BLACKLISTED_SCANNERS = []
SCAN_CANCELLED = -1
SCAN_FAILURE = 0
SCAN_SUCCESS = 1
+RESPONSE_BLACKLIST_DEVICE = 1
+
GCONF_DIRECTORY = '/apps/nostaples'
GCONF_TUPLE_SEPARATOR = '|'
GCONF_LIST_SEPARATOR = '^'
# TODO: rename to CONFIG_DIRECTORY
TEMP_IMAGES_DIRECTORY = os.path.expanduser('~/.nostaples')
LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config')
GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui')
PREVIEW_MODES = \
{
'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST,
'Tiles': gtk.gdk.INTERP_TILES,
'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR,
'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER
}
PREVIEW_MODES_LIST = \
[
'Nearest (Fastest)',
'Tiles',
'Bilinear (Default)',
'Antialias (Smoothest)'
]
THUMBNAIL_SIZE_LIST = \
[
32,
64,
128,
256
]
\ No newline at end of file
diff --git a/controllers/main.py b/controllers/main.py
index 78138ca..2253f53 100644
--- a/controllers/main.py
+++ b/controllers/main.py
@@ -34,755 +34,753 @@ from nostaples.models.page import PageModel
from nostaples.utils.scanning import *
import saneme
class MainController(Controller):
"""
Manages interaction between the L{MainModel} and L{MainView}.
"""
# SETUP METHODS
def __init__(self, application):
"""
Constructs the MainController, as well as necessary sub-controllers
and services.
"""
self.application = application
Controller.__init__(self, application.get_main_model())
application.get_document_model().register_observer(self)
status_controller = application.get_status_controller()
self.status_context = \
status_controller.get_context_id(self.__class__.__name__)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def register_view(self, view):
"""
Registers this controller with a view.
"""
Controller.register_view(self, view)
self.log.debug('%s registered.', view.__class__.__name__)
def register_adapters(self):
"""
Registers adapters for property/widget pairs that do not require
complex processing.
"""
self.adapt('show_toolbar', 'show_toolbar_menu_item')
self.adapt('show_statusbar', 'show_statusbar_menu_item')
self.adapt('show_thumbnails', 'show_thumbnails_menu_item')
self.adapt('show_adjustments', 'show_adjustments_menu_item')
self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item')
self.log.debug('Adapters registered.')
# USER INTERFACE CALLBACKS
# Menu Items
def on_scan_window_destroy(self, window):
"""Exits the application."""
self.quit()
def on_scan_menu_item_activate(self, menu_item):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_menu_item_activate(self, menu_item):
"""Refresh the list of connected scanners from SANE."""
self._update_available_scanners()
def on_save_as_menu_item_activate(self, menu_item):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_delete_menu_item_activate(self, menu_item):
self.application.get_document_controller().delete_selected()
def on_preferences_menu_item_activate(self, menu_item):
"""Creates and displays a preferences dialog."""
self.application.show_preferences_dialog()
def on_quit_menu_item_activate(self, menu_item):
"""Exits the application."""
self.quit()
def on_zoom_in_menu_item_activate(self, menu_item):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_menu_item_activate(self, menu_item):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_menu_item_activate(self, menu_item):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_menu_item_activate(self, menu_item):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_available_scanner_menu_item_toggled(self, menu_item):
"""
Set the active scanner.
TODO: Need a second scanner to properly test this...
"""
main_model = self.application.get_main_model()
if menu_item.get_active():
for scanner in main_model.available_scanners:
if scanner.display_name == menu_item.get_children()[0].get_text():
main_model.active_scanner = scanner
return
def on_valid_mode_menu_item_toggled(self, menu_item):
"""Sets the active scan mode."""
if menu_item.get_active():
self.application.get_main_model().active_mode = \
menu_item.get_children()[0].get_text()
def on_valid_resolution_menu_item_toggled(self, menu_item):
"""Sets the active scan resolution."""
if menu_item.get_active():
self.application.get_main_model().active_resolution = \
menu_item.get_children()[0].get_text()
def on_go_first_menu_item_activate(self, menu_item):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_menu_item_activate(self, menu_item):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_menu_item_activate(self, menu_item):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_menu_item_activate(self, menu_item):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
def on_contents_menu_item_clicked(self, menu_item):
"""TODO"""
pass
def on_about_menu_item_activate(self, menu_item):
"""Show the about dialog."""
self.application.show_about_dialog()
# Toolbar Buttons
def on_scan_button_clicked(self, button):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_button_clicked(self, button):
self._update_available_scanners()
def on_save_as_button_clicked(self, button):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_zoom_in_button_clicked(self, button):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_button_clicked(self, button):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_button_clicked(self, button):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_button_clicked(self, button):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_go_first_button_clicked(self, button):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_button_clicked(self, button):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_button_clicked(self, button):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_button_clicked(self, button):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
# Progress Window INTERFACE CALLBACKS
def on_progress_window_delete_event(self, window, event):
"""
Emulate clicking of the cancel/close button and then
hide the window.
"""
main_view = self.application.get_main_view()
self.on_scan_cancel_button_clicked(None)
main_view['progress_window'].hide()
return True
def on_scan_cancel_button_clicked(self, button):
"""
Cancel the current scan or, if the scan is finished,
close the progress window.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress:
assert self.cancel_event
self.cancel_event.set()
else:
main_view['progress_window'].hide()
def on_scan_again_button_clicked(self, button):
"""Initiate a new scan from the progress window."""
self._scan()
def on_quick_save_button_clicked(self, button):
"""
Show the save dialog. If the user completes a save
then disable the quick save button until another
page is scanned.
"""
main_view = self.application.get_main_view()
document_model = self.application.get_document_model()
self.application.show_save_dialog()
if document_model.count == 0:
main_view['quick_save_button'].set_sensitive(False)
# MainModel PROPERTY CALLBACKS
def property_show_toolbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the toolbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_toolbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['main_toolbar'].show()
else:
main_view['main_toolbar'].hide()
def property_show_statusbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the statusbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_statusbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['status_view_docking_viewport'].show()
else:
main_view['status_view_docking_viewport'].hide()
def property_show_thumbnails_value_change(self, model, old_value, new_value):
"""Update the visibility of the thumbnails."""
main_view = self.application.get_main_view()
menu_item = main_view['show_thumbnails_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_thumbnails_visible(new_value)
def property_show_adjustments_value_change(self, model, old_value, new_value):
"""Update the visibility of the adjustments controls."""
main_view = self.application.get_main_view()
menu_item = main_view['show_adjustments_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_adjustments_visible(new_value)
def property_active_scanner_value_change(self, model, old_value, new_value):
"""
Update the menu and valid scanner options to match the new device.
"""
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
for menu_item in main_view['scanner_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value.display_name:
menu_item.set_active(True)
break
self._update_scanner_options()
def property_active_mode_value_change(self, model, old_value, new_value):
"""Select the active mode from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_mode_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_active_resolution_value_change(self, model, old_value, new_value):
"""Select the active resolution from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_resolution_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_available_scanners_value_change(self, model, old_value, new_value):
"""
Update the menu of available scanners.
"""
main_view = self.application.get_main_view()
self._clear_available_scanners_sub_menu()
# Generate the new menu
if len(new_value) == 0:
menu_item = gtk.MenuItem('No Scanners Connected')
menu_item.set_sensitive(False)
main_view['scanner_sub_menu'].append(menu_item)
else:
first_item = None
for i in range(len(new_value)):
# The first menu item defines the group
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i].display_name)
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i].display_name)
main_view['scanner_sub_menu'].append(menu_item)
main_view['scanner_sub_menu'].show_all()
def property_valid_modes_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan modes for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_modes_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Modes")
menu_item.set_sensitive(False)
main_view['scan_mode_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled)
main_view['scan_mode_sub_menu'].append(menu_item)
main_view['scan_mode_sub_menu'].show_all()
def property_valid_resolutions_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan resolutions for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_resolutions_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Resolutions")
menu_item.set_sensitive(False)
main_view['scan_resolution_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled)
main_view['scan_resolution_sub_menu'].append(menu_item)
main_view['scan_resolution_sub_menu'].show_all()
def property_scan_in_progress_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_available_scanners_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_scan_options_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
# DocumentModel PROPERTY CALLBACKS
def property_count_value_change(self, model, old_value, new_value):
"""Toggle available controls."""
self._toggle_document_controls()
# THREAD CALLBACKS
def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned):
main_view = self.application.get_main_view()
short_bytes_scanned = float(bytes_scanned) / 1000
short_total_bytes = float(scan_info.total_bytes) / 1000
main_view['scan_progressbar'].set_fraction(
float(bytes_scanned) / scan_info.total_bytes)
main_view['scan_progressbar'].set_text(
'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes))
# TODO: multi page scans
main_view['progress_secondary_label'].set_markup(
'<i>Scanning page.</i>')
def on_scan_succeeded(self, scanning_thread, pil_image):
"""
Append the new page to the current document.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
main_view['scan_progressbar'].set_fraction(1)
main_view['scan_progressbar'].set_text('Scan complete')
main_view['progress_secondary_label'].set_markup(
'<i>Adding page to document.</i>')
gtk.gdk.flush()
new_page = PageModel(self.application, pil_image, int(main_model.active_resolution))
self.application.get_document_model().append(new_page)
main_view['progress_secondary_label'].set_markup(
'<i>Page added.</i>')
main_view['scan_again_button'].set_sensitive(True)
main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
def on_scan_failed(self, scanning_thread, reason):
"""
Set that scan is complete.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
main_view['progress_secondary_label'].set_markup(
'<i>%s</i>' % reason)
main_view['scan_again_button'].set_sensitive(True)
if self.application.get_document_model().count > 0:
main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
def on_scan_aborted(self, scanning_thread, exc_info):
"""
Change display to indicate that scanning failed and
convey the to the user the reason why the thread aborted.
If the failure was from a SANE exception then give the
user the option to blacklist the device. If not, then
reraise the error and let the sys.excepthook deal with it.
"""
self.on_scan_failed(scanning_thread, 'An error occurred.')
if isinstance(exc_info[1], saneme.SaneError):
- self.display_device_exception_dialog(exc_info)
+ self.run_device_exception_dialog(exc_info)
else:
raise exc_info[0], exc_info[1], exc_info[2]
def on_update_available_scanners_thread_finished(self, update_thread, scanner_list):
"""Set the new list of available scanners."""
main_model = self.application.get_main_model()
+ preferences_model = self.application.get_preferences_model()
status_controller = self.application.get_status_controller()
+ # Remove blacklisted scanners
+ scanner_list = \
+ [scanner for scanner in scanner_list if not \
+ scanner.display_name in preferences_model.blacklisted_scanners]
+
main_model.available_scanners = scanner_list
main_model.updating_available_scanners = False
def on_update_available_scanners_thread_aborted(self, update_thread, exc_info):
"""
Change the display to indicate that no scanners are available and
reraise the exception so that it can be caught by the sys.excepthook.
There is no reason to handle these cases with a special dialog,
if the application failed to even enumerate the available devices then
no other action will be possible.
This should be fantastically rare.
"""
self.on_update_available_scanners_thread_finished(update_thread, [])
raise exc_info[0], exc_info[1], exc_info[2]
def on_update_scanner_options_thread_finished(self, update_thread, mode_list, resolution_list):
"""
Update the mode and resolution lists and rark that
the scanner is no longer in use.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.valid_modes = mode_list
main_model.valid_resolutions = resolution_list
main_model.updating_scan_options = False
def on_update_scanner_options_thread_aborted(self, update_thread, exc_info):
"""
Change display to indicate that updating the options failed and
convey the to the user the reason why the thread aborted.
If the failure was from a SANE exception then give the
user the option to blacklist the device. If not, then
reraise the error and let the sys.excepthook deal with it.
"""
# TODO: If this fails the scanner icon will still stay lit,
# and when the user clicks it the app will error again since it
# will not have a valid mode/resolution.
self.on_update_scanner_options_thread_finished(update_thread, [], [])
if isinstance(exc_info[1], saneme.SaneError):
- self.display_device_exception_dialog(exc_info)
+ self.run_device_exception_dialog(exc_info)
else:
raise exc_info[0], exc_info[1], exc_info[2]
# PUBLIC METHODS
def quit(self):
"""Exits the application."""
self.log.debug('Quit.')
gtk.main_quit()
+
+ def run_device_exception_dialog(self, exc_info):
+ """
+ Display an error dialog that provides the user with the option of
+ blacklisting the device which caused the error.
+
+ TODO: Move into MainView.
+ """
+ main_model = self.application.get_main_model()
+ main_view = self.application.get_main_view()
+ preferences_model = self.application.get_preferences_model()
+
+ response = main_view.run_device_exception_dialog(exc_info)
+
+ if response == constants.RESPONSE_BLACKLIST_DEVICE:
+ temp_blacklist = list(preferences_model.blacklisted_scanners)
+ temp_blacklist.append(exc_info[1].device.display_name)
+ temp_blacklist.sort()
+ preferences_model.blacklisted_scanners = temp_blacklist
# PRIVATE METHODS
def _clear_available_scanners_sub_menu(self):
"""Clear the menu of available scanners."""
main_view = self.application.get_main_view()
for child in main_view['scanner_sub_menu'].get_children():
main_view['scanner_sub_menu'].remove(child)
def _clear_scan_modes_sub_menu(self):
"""Clear the menu of valid scan modes."""
main_view = self.application.get_main_view()
for child in main_view['scan_mode_sub_menu'].get_children():
main_view['scan_mode_sub_menu'].remove(child)
def _clear_scan_resolutions_sub_menu(self):
"""Clear the menu of valid scan resolutions."""
main_view = self.application.get_main_view()
for child in main_view['scan_resolution_sub_menu'].get_children():
main_view['scan_resolution_sub_menu'].remove(child)
def _toggle_scan_controls(self):
"""Toggle whether or not the scan controls or accessible."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_scan_controls_sensitive(False)
main_view.set_refresh_scanner_controls_sensitive(False)
else:
if main_model.active_scanner != None:
main_view.set_scan_controls_sensitive(True)
main_view.set_refresh_scanner_controls_sensitive(True)
def _toggle_document_controls(self):
"""
Toggle available document controls based on the current scanner
status and the number of scanned pages.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
# Disable all controls when the scanner is in use
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
count = self.application.get_document_model().count
# Disable all controls if no pages are scanned
if count == 0:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
# Enable most controls if any pages scanned
main_view.set_file_controls_sensitive(True)
main_view.set_delete_controls_sensitive(True)
main_view.set_zoom_controls_sensitive(True)
main_view.set_adjustment_controls_sensitive(True)
# Only enable navigation if more than one page scanned
if count > 1:
main_view.set_navigation_controls_sensitive(True)
else:
main_view.set_navigation_controls_sensitive(False)
def _update_status(self):
"""
Update the text of the statusbar based on the current state
of the application.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
status_controller.pop(self.status_context)
if main_model.scan_in_progress:
status_controller.push(self.status_context, 'Scanning...')
elif main_model.updating_available_scanners:
status_controller.push(self.status_context, 'Querying hardware...')
elif main_model.updating_scan_options:
status_controller.push(self.status_context, 'Querying options...')
else:
if main_model.active_scanner:
status_controller.push(self.status_context,
'Ready with %s.' % main_model.active_scanner.display_name)
else:
status_controller.push(self.status_context, 'No scanner available.')
def _scan(self):
"""Begin a scan."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
main_model.scan_in_progress = True
scanning_thread = ScanningThread(
main_model.active_scanner, main_model.active_mode, main_model.active_resolution)
scanning_thread.connect("progress", self.on_scan_progress)
scanning_thread.connect("succeeded", self.on_scan_succeeded)
scanning_thread.connect("failed", self.on_scan_failed)
scanning_thread.connect("aborted", self.on_scan_aborted)
self.cancel_event = scanning_thread.cancel_event
main_view['progress_primary_label'].set_markup(
'<big><b>%s</b></big>' % main_model.active_scanner.display_name)
main_view['scan_progressbar'].set_fraction(0)
main_view['scan_progressbar'].set_text('Waiting for data')
main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>')
mode = main_model.active_mode if main_model.active_mode else 'Not set'
main_view['progress_mode_label'].set_markup(mode)
dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set'
main_view['progress_resolution_label'].set_markup(dpi)
main_view['scan_again_button'].set_sensitive(False)
main_view['quick_save_button'].set_sensitive(False)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL)
main_view['progress_window'].show_all()
scanning_thread.start()
def _update_available_scanners(self):
"""
Start a new update thread to query for available scanners.
"""
sane = self.application.get_sane()
main_model = self.application.get_main_model()
main_model.updating_available_scanners = True
update_thread = UpdateAvailableScannersThread(sane)
update_thread.connect("finished", self.on_update_available_scanners_thread_finished)
update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted)
update_thread.start()
def _update_scanner_options(self):
"""Determine the valid options for the current scanner."""
main_model = self.application.get_main_model()
main_model.updating_scan_options = True
update_thread = UpdateScannerOptionsThread(main_model.active_scanner)
update_thread.connect("finished", self.on_update_scanner_options_thread_finished)
update_thread.connect("aborted", self.on_update_scanner_options_thread_aborted)
- update_thread.start()
-
- def display_device_exception_dialog(self, exc_info):
- """
- Display an error dialog that provides the user with the option of
- blacklisting the device which caused the error.
- """
- dialog = gtk.MessageDialog(
- parent=None, flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_NONE)
- dialog.set_title("")
-
- # TODO: is this needed?
- if gtk.check_version (2, 4, 0) is not None:
- dialog.set_has_separator (False)
-
- primary = "<big><b>A hardware exception has been logged.</b></big>"
- secondary = '%s\n\n%s' % (exc_info[1].message, 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.')
-
- dialog.set_markup(primary)
- dialog.format_secondary_markup(secondary)
-
- dialog.add_button('Blacklist Device', 1)
- dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
-
- response = dialog.run()
- dialog.destroy()
-
- # TODO: handle blacklisting
\ No newline at end of file
+ update_thread.start()
\ No newline at end of file
diff --git a/controllers/preferences.py b/controllers/preferences.py
index b72ea3f..f1bfe08 100644
--- a/controllers/preferences.py
+++ b/controllers/preferences.py
@@ -1,85 +1,147 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the L{PreferencesController}, which manages interaction
between the L{PreferencesModel} and L{PreferencesView}.
"""
import logging
import gtk
from gtkmvc.controller import Controller
from nostaples import constants
from nostaples.utils.gui import read_combobox
class PreferencesController(Controller):
"""
Manages interaction between the L{PreferencesModel} and
L{PreferencesView}.
"""
# SETUP METHODS
def __init__(self, application):
"""
Constructs the PreferencesController.
"""
self.application = application
Controller.__init__(self, application.get_preferences_model())
-
+
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def register_view(self, view):
"""
Registers this controller with a view.
"""
Controller.register_view(self, view)
self.log.debug('%s registered.', view.__class__.__name__)
def register_adapters(self):
"""
Registers adapters for property/widget pairs that do not require
complex processing.
"""
pass
- # PUBLIC METHODS
+ # USER INTERFACE CALLBACKS
- def run(self):
- """Run the preferences dialog."""
+ def on_preview_mode_combobox_changed(self, combobox):
+ preferences_model = self.application.get_preferences_model()
preferences_view = self.application.get_preferences_view()
- preferences_view.run()
+ preferences_model.preview_mode = \
+ read_combobox(preferences_view['preview_mode_combobox'])
- # USER INTERFACE CALLBACKS
+ def on_thumbnail_size_combobox_changed(self, combobox):
+ preferences_model = self.application.get_preferences_model()
+ preferences_view = self.application.get_preferences_view()
+
+ preferences_model.thumbnail_size = \
+ int(read_combobox(preferences_view['thumbnail_size_combobox']))
+
+ def on_remove_from_blacklist_button_clicked(self, button):
+ """
+ Remove the currently selected blacklist device from the list.
+ """
+ preferences_model = self.application.get_preferences_model()
+ preferences_view = self.application.get_preferences_view()
+
+ model, selection_iter = \
+ preferences_view['blacklist_tree_view'].get_selection().get_selected()
+
+ if not selection_iter:
+ return
+
+ selection_text = model.get_value(selection_iter, 0)
+ model.remove(selection_iter)
+
+ temp_blacklist = list(preferences_model.blacklisted_scanners)
+ temp_blacklist.remove(selection_text)
+ preferences_model.blacklisted_scanners = temp_blacklist
+
+ def on_remove_from_keywords_button_clicked(self, button):
+ """
+ Remove the currently selected keyword from the list.
+ """
+ preferences_model = self.application.get_preferences_model()
+ preferences_view = self.application.get_preferences_view()
+
+ model, selection_iter = \
+ preferences_view['keywords_tree_view'].get_selection().get_selected()
+
+ if not selection_iter:
+ return
+
+ selection_text = model.get_value(selection_iter, 0)
+ model.remove(selection_iter)
+
+ temp_keywords = list(preferences_model.saved_keywords)
+ temp_keywords.remove(selection_text)
+ preferences_model.saved_keywords = temp_keywords
def on_preferences_dialog_response(self, dialog, response):
"""Close the preferences dialog."""
+ preferences_view = self.application.get_preferences_view()
+
+ preferences_view['preferences_dialog'].hide()
+
+ # PUBLIC METHODS
+
+ def run(self):
+ """Run the preferences dialog."""
preferences_model = self.application.get_preferences_model()
preferences_view = self.application.get_preferences_view()
- preferences_model.preview_mode = \
- read_combobox(preferences_view['preview_mode_combobox'])
+ # Refresh blacklist
+ blacklist_liststore = preferences_view['blacklist_tree_view'].get_model()
+ blacklist_liststore.clear()
- preferences_model.thumbnail_size = \
- int(read_combobox(preferences_view['thumbnail_size_combobox']))
+ for blacklist_item in preferences_model.blacklisted_scanners:
+ blacklist_liststore.append([blacklist_item])
+
+ # Refresh keywords
+ keywords_liststore = preferences_view['keywords_tree_view'].get_model()
+ keywords_liststore.clear()
+
+ for keyword in preferences_model.saved_keywords:
+ keywords_liststore.append([keyword])
- preferences_view['preferences_dialog'].hide()
\ No newline at end of file
+ preferences_view.run()
\ No newline at end of file
diff --git a/controllers/save.py b/controllers/save.py
index 70e2a35..df78d0e 100644
--- a/controllers/save.py
+++ b/controllers/save.py
@@ -1,306 +1,309 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the L{SaveController}, which manages interaction
between the L{SaveModel} and L{SaveView}.
"""
import logging
import os
import sys
import tempfile
import gtk
from gtkmvc.controller import Controller
import Image, ImageEnhance
from reportlab.pdfgen.canvas import Canvas as PdfCanvas
from reportlab.lib.pagesizes import landscape, portrait
from reportlab.lib.units import inch as points_per_inch
from nostaples import constants
import nostaples.utils.gui
class SaveController(Controller):
"""
Manages interaction between the L{SaveModel} and
L{SaveView}.
"""
# SETUP METHODS
def __init__(self, application):
"""
Constructs the SaveController.
"""
self.application = application
Controller.__init__(self, application.get_save_model())
status_controller = application.get_status_controller()
self.status_context = \
status_controller.get_context_id(self.__class__.__name__)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def register_view(self, view):
"""
Registers this controller with a view.
"""
Controller.register_view(self, view)
+ preferences_model = self.application.get_preferences_model()
save_model = self.application.get_save_model()
# Force refresh of keyword list
keywords_liststore = view['keywords_entry'].get_liststore()
keywords_liststore.clear()
- for keyword in save_model.saved_keywords:
+ for keyword in preferences_model.saved_keywords:
keywords_liststore.append([keyword])
self.log.debug('%s registered.', view.__class__.__name__)
def register_adapters(self):
"""
Registers adapters for property/widget pairs that do not require
complex processing.
"""
self.adapt('title', 'title_entry')
self.adapt('author', 'author_entry')
self.adapt('keywords', 'keywords_entry')
self.adapt('show_document_metadata', 'document_metadata_expander')
self.log.debug('Adapters registered.')
# USER INTERFACE CALLBACKS
def on_title_from_filename_button_clicked(self, button):
"""
Copy the selected filename to the pdf title property.
"""
save_view = self.application.get_save_view()
title = save_view['save_dialog'].get_filename()
if not title:
save_view['title_entry'].set_text('')
return
title = title.split('/')[-1]
if title[-4:] == '.pdf':
title = title[:-4]
save_view['title_entry'].set_text(title)
def on_clear_title_button_clicked(self, button):
"""Clear the title."""
self.application.get_save_model().title = ''
def on_clear_author_button_clicked(self, button):
"""Clear the author."""
self.application.get_save_model().author = ''
def on_clear_keywords_button_clicked(self, button):
"""Clear the keywords."""
self.application.get_save_model().keywords = ''
def on_save_dialog_response(self, dialog, response):
"""
Determine the selected file type and invoke the method
that saves that file type.
"""
save_model = self.application.get_save_model()
save_view = self.application.get_save_view()
main_view = self.application.get_main_view()
save_view['save_dialog'].hide()
if response != gtk.RESPONSE_ACCEPT:
return
main_view['scan_window'].window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
nostaples.utils.gui.flush_pending_events()
save_model.filename = save_view['save_dialog'].get_filename()
filename_filter = save_view['save_dialog'].get_filter()
if filename_filter.get_name() == 'PDF Files':
if save_model.filename[-4:] != '.pdf':
save_model.filename = ''.join([save_model.filename, '.pdf'])
self._save_pdf()
else:
self.log.error('Unknown file type: %s.' % save_model.filename)
self._update_saved_keywords()
main_view['scan_window'].window.set_cursor(None)
save_model.save_path = save_view['save_dialog'].get_current_folder()
# PROPERTY CALLBACKS
def property_saved_keywords_value_change(self, model, old_value, new_value):
"""
Update the keywords auto-completion control with the new
keywords.
"""
save_view = self.application.get_save_view()
keywords_liststore = save_view['keywords_entry'].get_liststore()
keywords_liststore.clear()
for keyword in new_value:
keywords_liststore.append([keyword])
# PRIVATE METHODS
def _save_pdf(self):
"""
Output the current document to a PDF file using ReportLab.
"""
save_model = self.application.get_save_model()
save_view = self.application.get_save_view()
document_model = self.application.get_document_model()
# TODO: seperate saving code into its own thread?
# Setup output pdf
pdf = PdfCanvas(save_model.filename)
pdf.setTitle(save_model.title)
pdf.setAuthor(save_model.author)
pdf.setKeywords(save_model.keywords)
# Generate pages
page_iter = document_model.get_iter_first()
while page_iter:
current_page = document_model.get_value(page_iter, 0)
# Write transformed image
temp_file_path = ''.join([tempfile.mktemp(), '.bmp'])
current_page.pil_image.save(temp_file_path)
assert os.path.exists(temp_file_path), \
'Temporary bitmap file was not created by PIL.'
width_in_inches = \
int(current_page.width / current_page.resolution)
height_in_inches = \
int(current_page.height / current_page.resolution)
# NB: Because not all SANE backends support specifying the size
# of the scan area, the best we can do is scan at the default
# setting and then convert that to an appropriate PDF. For the
# vast majority of scanners we hope that this would be either
# letter or A4.
pdf_width, pdf_height = self._determine_best_fitting_pagesize(
width_in_inches, height_in_inches)
pdf.setPageSize((pdf_width, pdf_height))
pdf.drawImage(
temp_file_path,
0, 0, width=pdf_width, height=pdf_height,
preserveAspectRatio=True)
pdf.showPage()
os.remove(temp_file_path)
page_iter = document_model.iter_next(page_iter)
# Save complete PDF
pdf.save()
assert os.path.exists(save_model.filename), \
'Final PDF file was not created by ReportLab.'
document_model.clear()
def _determine_best_fitting_pagesize(self, width_in_inches, height_in_inches):
"""
Searches through the possible page sizes and finds the smallest one that
will contain the image without cropping.
"""
image_width_in_points = width_in_inches * points_per_inch
image_height_in_points = height_in_inches * points_per_inch
nearest_size = None
nearest_distance = sys.maxint
for size in constants.PAGESIZES.values():
# Orient the size to match the page
if image_width_in_points > image_height_in_points:
size = landscape(size)
else:
size = portrait(size)
# Only compare the size if its large enough to contain the entire
# image
if size[0] < image_width_in_points or \
size[1] < image_height_in_points:
continue
# Compute distance for comparison
distance = \
size[0] - image_width_in_points + \
size[1] - image_height_in_points
# Save if closer than prior nearest distance
if distance < nearest_distance:
nearest_distance = distance
nearest_size = size
# Stop searching if a perfect match is found
if nearest_distance == 0:
break
assert nearest_size != None, 'No nearest size found.'
return nearest_size
def _update_saved_keywords(self):
"""
Update the saved keywords with any new keywords that
have been used.
"""
+ preferences_model = self.application.get_preferences_model()
save_model = self.application.get_save_model()
new_keywords = []
for keyword in save_model.keywords.split():
- if keyword not in save_model.saved_keywords:
+ if keyword not in preferences_model.saved_keywords:
new_keywords.append(keyword)
if new_keywords:
temp_list = []
- temp_list.extend(save_model.saved_keywords)
+ temp_list.extend(preferences_model.saved_keywords)
temp_list.extend(new_keywords)
- save_model.saved_keywords = temp_list
+ temp_list.sort()
+ preferences_model.saved_keywords = temp_list
# PUBLIC METHODS
def run(self):
"""Run the save dialog."""
save_model = self.application.get_save_model()
save_view = self.application.get_save_view()
status_controller = self.application.get_status_controller()
save_view['save_dialog'].set_current_folder(save_model.save_path)
save_view['save_dialog'].set_current_name('')
status_controller.push(self.status_context, 'Saving...')
save_view.run()
status_controller.pop(self.status_context)
\ No newline at end of file
diff --git a/gui/preferences_dialog.glade b/gui/preferences_dialog.glade
index ed16874..81845ba 100644
--- a/gui/preferences_dialog.glade
+++ b/gui/preferences_dialog.glade
@@ -1,127 +1,283 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--Generated with glade3 3.4.5 on Mon Jan 5 17:47:07 2009 -->
+<!--Generated with glade3 3.4.5 on Sat Feb 21 21:35:09 2009 -->
<glade-interface>
<widget class="GtkDialog" id="preferences_dialog">
<property name="border_width">5</property>
<property name="title" translatable="yes">Preferences</property>
<property name="resizable">False</property>
<property name="modal">True</property>
<property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property>
<property name="destroy_with_parent">True</property>
<property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property>
<property name="skip_taskbar_hint">True</property>
<property name="skip_pager_hint">True</property>
<property name="has_separator">False</property>
<signal name="response" handler="on_preferences_dialog_response"/>
<child internal-child="vbox">
<widget class="GtkVBox" id="dialog-vbox5">
<property name="visible">True</property>
- <property name="spacing">24</property>
+ <property name="spacing">12</property>
<signal name="add" handler="on_preferences_dialog_close"/>
<child>
- <widget class="GtkAlignment" id="alignment6">
+ <widget class="GtkNotebook" id="notebook1">
<property name="visible">True</property>
- <property name="top_padding">6</property>
- <property name="bottom_padding">6</property>
- <property name="left_padding">6</property>
- <property name="right_padding">6</property>
+ <property name="can_focus">True</property>
<child>
- <widget class="GtkVBox" id="vbox3">
+ <widget class="GtkAlignment" id="alignment6">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- <property name="spacing">6</property>
+ <property name="top_padding">12</property>
+ <property name="bottom_padding">12</property>
+ <property name="left_padding">12</property>
+ <property name="right_padding">12</property>
<child>
- <widget class="GtkHBox" id="hbox2">
+ <widget class="GtkVBox" id="vbox3">
<property name="visible">True</property>
- <property name="spacing">12</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="spacing">6</property>
<child>
- <widget class="GtkLabel" id="label4">
+ <widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
- <property name="label" translatable="yes">Preview Mode:</property>
+ <property name="spacing">12</property>
+ <child>
+ <widget class="GtkLabel" id="label4">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Preview Mode:</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkComboBox" id="preview_mode_combobox">
+ <property name="visible">True</property>
+ <property name="items" translatable="yes"></property>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
- <widget class="GtkComboBox" id="preview_mode_combobox">
+ <widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
- <property name="items" translatable="yes"></property>
+ <property name="spacing">12</property>
+ <child>
+ <widget class="GtkLabel" id="label5">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Thumbnail Size:</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkComboBox" id="thumbnail_size_combobox">
+ <property name="visible">True</property>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
</widget>
- <packing>
- <property name="expand">False</property>
- </packing>
</child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="label1">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">View</property>
+ </widget>
+ <packing>
+ <property name="type">tab</property>
+ <property name="tab_fill">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkAlignment" id="alignment1">
+ <property name="visible">True</property>
+ <property name="top_padding">12</property>
+ <property name="bottom_padding">12</property>
+ <property name="left_padding">12</property>
+ <property name="right_padding">12</property>
<child>
- <widget class="GtkHBox" id="hbox1">
+ <widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
- <property name="spacing">12</property>
+ <property name="spacing">6</property>
+ <child>
+ <widget class="GtkLabel" id="label7">
+ <property name="visible">True</property>
+ <property name="xalign">0</property>
+ <property name="label" translatable="yes">Blacklisted devices:</property>
+ <property name="wrap_mode">PANGO_WRAP_WORD_CHAR</property>
+ </widget>
+ </child>
<child>
- <widget class="GtkLabel" id="label1">
+ <widget class="GtkScrolledWindow" id="blacklist_scrolled_window">
<property name="visible">True</property>
- <property name="label" translatable="yes">Thumbnail Size:</property>
+ <property name="can_focus">True</property>
+ <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property>
+ <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property>
+ <property name="shadow_type">GTK_SHADOW_IN</property>
+ <child>
+ <placeholder/>
+ </child>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkButton" id="remove_from_blacklist_button">
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <property name="label" translatable="yes">Remove</property>
+ <property name="response_id">0</property>
+ <signal name="clicked" handler="on_remove_from_blacklist_button_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="position">2</property>
</packing>
</child>
+ </widget>
+ </child>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="label3">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Devices</property>
+ </widget>
+ <packing>
+ <property name="type">tab</property>
+ <property name="position">1</property>
+ <property name="tab_fill">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkAlignment" id="alignment2">
+ <property name="visible">True</property>
+ <property name="top_padding">12</property>
+ <property name="bottom_padding">12</property>
+ <property name="left_padding">12</property>
+ <property name="right_padding">12</property>
+ <child>
+ <widget class="GtkVBox" id="vbox2">
+ <property name="visible">True</property>
+ <property name="spacing">6</property>
+ <child>
+ <widget class="GtkLabel" id="label6">
+ <property name="visible">True</property>
+ <property name="xalign">0</property>
+ <property name="label" translatable="yes">Keywords for autocompletion:</property>
+ <property name="use_markup">True</property>
+ <property name="wrap">True</property>
+ </widget>
+ </child>
<child>
- <widget class="GtkComboBox" id="thumbnail_size_combobox">
+ <widget class="GtkScrolledWindow" id="keywords_scrolled_window">
<property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property>
+ <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property>
+ <property name="shadow_type">GTK_SHADOW_IN</property>
+ <child>
+ <placeholder/>
+ </child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
+ <child>
+ <widget class="GtkAlignment" id="alignment3">
+ <property name="visible">True</property>
+ <child>
+ <widget class="GtkButton" id="remove_from_keywords_button">
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <property name="label" translatable="yes">Remove</property>
+ <property name="response_id">0</property>
+ <signal name="clicked" handler="on_remove_from_keywords_button_clicked"/>
+ </widget>
+ </child>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="position">2</property>
+ </packing>
+ </child>
</widget>
- <packing>
- <property name="position">1</property>
- </packing>
</child>
</widget>
+ <packing>
+ <property name="position">2</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="label2">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Documents</property>
+ </widget>
+ <packing>
+ <property name="type">tab</property>
+ <property name="position">2</property>
+ <property name="tab_fill">False</property>
+ </packing>
</child>
</widget>
<packing>
- <property name="expand">False</property>
<property name="position">1</property>
</packing>
</child>
<child internal-child="action_area">
<widget class="GtkHButtonBox" id="dialog-action_area5">
<property name="visible">True</property>
<property name="layout_style">GTK_BUTTONBOX_END</property>
<child>
<placeholder/>
</child>
<child>
<widget class="GtkButton" id="preferences_close_button">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- <property name="label" translatable="yes">Close</property>
+ <property name="label" translatable="yes">gtk-close</property>
+ <property name="use_stock">True</property>
<property name="response_id">0</property>
<signal name="clicked" handler="on_preferences_close_button_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">GTK_PACK_END</property>
<property name="position">1</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">GTK_PACK_END</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
diff --git a/models/main.py b/models/main.py
index 55e47b1..8f51438 100644
--- a/models/main.py
+++ b/models/main.py
@@ -1,324 +1,323 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the MainModel, which manages general application
data.
"""
import logging
+import sys
from gtkmvc.model import Model
from nostaples import constants
import nostaples.utils.properties
import saneme
class MainModel(Model):
"""
Handles data all data not specifically handled by another Model
(e.g. the state of the main application window).
Note: active_scanner is a tuple in the format (display_name,
sane_name). available_scanners is a list of such tuples.
"""
__properties__ = \
{
'show_toolbar' : True,
'show_statusbar' : True,
'show_thumbnails' : True,
'show_adjustments' : False,
'rotate_all_pages' : False,
'active_scanner' : None, # saneme.Device
'active_mode' : None,
'active_resolution' : None,
'available_scanners' : [], # [] of saneme.Device
'valid_modes' : [],
'valid_resolutions' : [],
'scan_in_progress' : False,
'updating_available_scanners' : False,
'updating_scan_options' : False,
}
def __init__(self, application):
"""
Constructs the MainModel, as well as necessary sub-models.
"""
self.application = application
Model.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def load_state(self):
"""
Load persisted state from the self.state_manager.
"""
state_manager = self.application.get_state_manager()
sane = self.application.get_sane()
self.show_toolbar = state_manager.init_state(
'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR,
- nostaples.utils.properties.GenericStateCallback(self, 'show_toolbar'))
+ nostaples.utils.properties.PropertyStateCallback(self, 'show_toolbar'))
self.show_statusbar = state_manager.init_state(
'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR,
- nostaples.utils.properties.GenericStateCallback(self, 'show_statusbar'))
+ nostaples.utils.properties.PropertyStateCallback(self, 'show_statusbar'))
self.show_thumbnails = state_manager.init_state(
'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS,
- nostaples.utils.properties.GenericStateCallback(self, 'show_thumbnails'))
+ nostaples.utils.properties.PropertyStateCallback(self, 'show_thumbnails'))
self.show_adjustments = state_manager.init_state(
'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS,
- nostaples.utils.properties.GenericStateCallback(self, 'show_adjustments'))
+ nostaples.utils.properties.PropertyStateCallback(self, 'show_adjustments'))
self.rotate_all_pages = state_manager.init_state(
'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES,
- nostaples.utils.properties.GenericStateCallback(self, 'rotate_all_pages'))
+ nostaples.utils.properties.PropertyStateCallback(self, 'rotate_all_pages'))
# The local representation of active_scanner is a
# saneme.Device, but it is persisted by its name attribute only.
try:
self.active_scanner = sane.get_device_by_name(
state_manager.init_state(
'active_scanner', constants.DEFAULT_ACTIVE_SCANNER,
self.state_active_scanner_change))
except saneme.SaneNoSuchDeviceError:
self.active_scanner = None
self.active_mode = state_manager.init_state(
'scan_mode', constants.DEFAULT_SCAN_MODE,
self.state_scan_mode_change)
self.active_resolution = state_manager.init_state(
'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION,
self.state_scan_resolution_change)
# PROPERTY SETTERS
- set_prop_show_toolbar = nostaples.utils.properties.GenericPropertySetter(
+ set_prop_show_toolbar = nostaples.utils.properties.StatefulPropertySetter(
'show_toolbar')
- set_prop_show_statusbar = nostaples.utils.properties.GenericPropertySetter(
+ set_prop_show_statusbar = nostaples.utils.properties.StatefulPropertySetter(
'show_statusbar')
- set_prop_show_thumbnails = nostaples.utils.properties.GenericPropertySetter(
+ set_prop_show_thumbnails = nostaples.utils.properties.StatefulPropertySetter(
'show_thumbnails')
- set_prop_show_adjustments = nostaples.utils.properties.GenericPropertySetter(
+ set_prop_show_adjustments = nostaples.utils.properties.StatefulPropertySetter(
'show_adjustments')
- set_prop_rotate_all_pages = nostaples.utils.properties.GenericPropertySetter(
+ set_prop_rotate_all_pages = nostaples.utils.properties.StatefulPropertySetter(
'rotate_all_pages')
def set_prop_active_scanner(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
main_controller = self.application.get_main_controller()
# Ignore spurious updates
old_value = self._prop_active_scanner
if old_value == value:
return
# Close the old scanner
old_value.close()
if value is not None:
assert isinstance(value, saneme.Device)
# Update the internal property variable
self._prop_active_scanner = value
# Only persist the state if the new value is not None
# and it can be opened without error.
# This prevents problems with trying to store a Null
# value in the state backend and also allows for smooth
# transitions if a scanner is disconnected and reconnected.
if value is not None:
- # TODO: handle exceptions
try:
value.open()
- except saneme.SaneError, e:
- main_controller.display_device_exception_dialog(e)
+ except saneme.SaneError:
+ exc_info = sys.exc_info()
+ main_controller.run_device_exception_dialog(exc_info)
self.application.get_state_manager()['active_scanner'] = value.name
# Emit the property change notification to all observers.
self.notify_property_value_change(
'active_scanner', old_value, value)
def set_prop_active_mode(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_active_mode
if old_value == value:
return
self._prop_active_mode = value
if value is not None:
self.application.get_state_manager()['scan_mode'] = value
self.notify_property_value_change(
'active_mode', old_value, value)
def set_prop_active_resolution(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_active_resolution
if old_value == value:
return
self._prop_active_resolution = value
if value is not None:
self.application.get_state_manager()['scan_resolution'] = value
self.notify_property_value_change(
'active_resolution', old_value, value)
def set_prop_available_scanners(self, value):
"""
Set the list of available scanners, updating the active_scanner
if it is no longer in the list.
"""
main_controller = self.application.get_main_controller()
old_value = self._prop_available_scanners
if len(value) == 0:
self._prop_active_scanner = None
else:
# Select the first available scanner if the previously
# selected scanner is not in the new list
# We avoid the active_scanner property setter so that
# The property notification callbacks will not be fired
# until after the menu has been updated.
if self._prop_active_scanner not in value:
try:
value[0].open()
self._prop_active_scanner = value[0]
self.application.get_state_manager()['active_scanner'] = \
value[0].name
- except saneme.SaneError, e:
- main_controller.display_device_exception_dialog(e)
+ except saneme.SaneError:
+ exc_info = sys.exc_info()
+ main_controller.run_device_exception_dialog(exc_info)
# Otherwise maintain current selection
else:
pass
self._prop_available_scanners = value
# This will only actually cause an update if
# old_value != value
self.notify_property_value_change(
'available_scanners', old_value, value)
# Force the scanner options to update, even if the active
# scanner did not change. This is necessary in case the
# current value was loaded from state, in which case the
# options will not yet have been loaded).
self.notify_property_value_change(
'active_scanner', None, self._prop_active_scanner)
def set_prop_valid_modes(self, value):
"""
Set the list of valid scan modes, updating the active_mode
if it is no longer in the list.
See L{set_prop_available_scanners} for detailed comments.
"""
old_value = self._prop_valid_modes
if len(value) == 0:
self._prop_active_mode = None
else:
if self._prop_active_mode not in value:
self._prop_active_mode = value[0]
self.application.get_state_manager()['scan_mode'] = value[0]
else:
pass
self._prop_valid_modes = value
self.notify_property_value_change(
'valid_modes', old_value, value)
self.notify_property_value_change(
'active_mode', None, self._prop_active_mode)
def set_prop_valid_resolutions(self, value):
"""
Set the list of valid scan resolutions, updating the
active_resolution if it is no longer in the list.
See L{set_prop_available_scanners} for detailed comments.
"""
old_value = self._prop_valid_resolutions
if len(value) == 0:
self._prop_active_resolution = None
else:
if self._prop_active_resolution not in value:
self._prop_active_resolution = value[0]
self.application.get_state_manager()['scan_resolution'] = \
value[0]
else:
pass
self._prop_valid_resolutions = value
self.notify_property_value_change(
'valid_resolutions', old_value, value)
self.notify_property_value_change(
'active_resolution', None, self._prop_active_resolution)
# STATE CALLBACKS
def state_active_scanner_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
sane = self.application.get_sane()
if state_manager['active_scanner'] in self.available_scanners:
- try:
- self.active_scanner = sane.get_device_by_name(state_manager['active_scanner'])
- except SaneNoSuchDeviceError:
- raise
+ self.active_scanner = sane.get_device_by_name(state_manager['active_scanner'])
else:
state_manager['active_scanner'] = self.active_scanner.name
def state_scan_mode_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
if state_manager['scan_mode'] in self.valid_modes:
self.active_mode = state_manager['scan_mode']
else:
state_manager['scan_mode'] = self.active_mode
def state_scan_resolution_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
if state_manager['scan_resolution'] in self.valid_resolutions:
self.active_resolution = state_manager['scan_resolution']
else:
state_manager['scan_resolution'] = self.active_resolution
\ No newline at end of file
diff --git a/models/preferences.py b/models/preferences.py
index dc70747..51ba663 100644
--- a/models/preferences.py
+++ b/models/preferences.py
@@ -1,102 +1,85 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the PreferencesModel, which manages user settings.
"""
import logging
from gtkmvc.model import Model
from nostaples import constants
+import nostaples.utils.properties
class PreferencesModel(Model):
"""
Manages user settings.
"""
__properties__ = \
{
'preview_mode' : constants.DEFAULT_PREVIEW_MODE,
- 'thumbnail_size' : constants.DEFAULT_THUMBNAIL_SIZE
+ 'thumbnail_size' : constants.DEFAULT_THUMBNAIL_SIZE,
+
+ 'blacklisted_scanners' : [], # List of scanner display names
+
+ 'saved_keywords' : '',
}
def __init__(self, application):
"""
Constructs the PreferencesModel.
"""
Model.__init__(self)
self.application = application
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def load_state(self):
"""
Load persisted state from the self.state_manager.
"""
state_manager = self.application.get_state_manager()
self.preview_mode = state_manager.init_state(
'preview_mode', constants.DEFAULT_PREVIEW_MODE,
- self.state_preview_mode_change)
+ nostaples.utils.properties.PropertyStateCallback(self, 'preview_mode'))
self.thumbnail_size = state_manager.init_state(
'thumbnail_size', constants.DEFAULT_THUMBNAIL_SIZE,
- self.state_thumbnail_size_change)
+ nostaples.utils.properties.PropertyStateCallback(self, 'thumbnail_size'))
- # Property setters
- # (see gtkmvc.support.metaclass_base.py for the origin of these accessors)
+ self.blacklisted_scanners = state_manager.init_state(
+ 'blacklisted_scanners', constants.DEFAULT_BLACKLISTED_SCANNERS,
+ nostaples.utils.properties.PropertyStateCallback(self, 'blacklisted_scanners'))
- def set_prop_preview_mode(self, value):
- """
- Write state.
- See L{MainModel.set_prop_active_scanner} for detailed comments.
- """
- old_value = self._prop_preview_mode
- if old_value == value:
- return
- self._prop_preview_mode = value
- self.application.get_state_manager()['preview_mode'] = value
- self.notify_property_value_change(
- 'preview_mode', old_value, value)
+ self.saved_keywords = state_manager.init_state(
+ 'saved_keywords', constants.DEFAULT_SAVED_KEYWORDS,
+ nostaples.utils.properties.PropertyStateCallback(self, 'saved_keywords'))
- def set_prop_thumbnail_size(self, value):
- """
- Write state.
- See L{MainModel.set_prop_active_scanner} for detailed comments.
- """
- old_value = self._prop_thumbnail_size
- if old_value == value:
- return
- self._prop_thumbnail_size = value
- self.application.get_state_manager()['thumbnail_size'] = value
- self.notify_property_value_change(
- 'thumbnail_size', old_value, value)
+ # PROPERTY SETTERS
- # STATE CALLBACKS
-
- def state_preview_mode_change(self):
- """Read state."""
- self.preview_mode = \
- self.application.get_state_manager()['preview_mode']
-
- def state_thumbnail_size_change(self):
- """Read state."""
- self.thumbnail_size = \
- self.application.get_state_manager()['thumbnail_size']
\ No newline at end of file
+ set_prop_preview_mode = nostaples.utils.properties.StatefulPropertySetter(
+ 'preview_mode')
+ set_prop_thumbnail_size = nostaples.utils.properties.StatefulPropertySetter(
+ 'thumbnail_size')
+ set_prop_blacklisted_scanners = nostaples.utils.properties.StatefulPropertySetter(
+ 'blacklisted_scanners')
+ set_prop_saved_keywords = nostaples.utils.properties.StatefulPropertySetter(
+ 'saved_keywords')
\ No newline at end of file
diff --git a/models/save.py b/models/save.py
index 8e15c5e..05d361f 100644
--- a/models/save.py
+++ b/models/save.py
@@ -1,90 +1,82 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the SaveModel, which manages data related to
saving documents.
"""
import logging
from gtkmvc.model import Model
from nostaples import constants
import nostaples.utils.properties
class SaveModel(Model):
"""
Handles data the metadata associated with saving documents.
"""
__properties__ = \
{
'save_path' : '',
'title' : '',
'author' : '',
'keywords' : '',
- 'saved_keywords' : '',
-
'show_document_metadata' : True,
'filename' : '',
}
def __init__(self, application):
"""
Constructs the SaveModel.
"""
self.application = application
Model.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def load_state(self):
"""
Load persisted state from the self.state_manager.
"""
state_manager = self.application.get_state_manager()
self.save_path = state_manager.init_state(
'save_path', constants.DEFAULT_SAVE_PATH,
- nostaples.utils.properties.GenericStateCallback(self, 'save_path'))
+ nostaples.utils.properties.PropertyStateCallback(self, 'save_path'))
self.author = state_manager.init_state(
'author', constants.DEFAULT_AUTHOR,
- nostaples.utils.properties.GenericStateCallback(self, 'author'))
-
- self.saved_keywords = state_manager.init_state(
- 'saved_keywords', constants.DEFAULT_SAVED_KEYWORDS,
- nostaples.utils.properties.GenericStateCallback(self, 'saved_keywords'))
+ nostaples.utils.properties.PropertyStateCallback(self, 'author'))
self.show_document_metadata = state_manager.init_state(
'show_document_metadata', constants.DEFAULT_SHOW_DOCUMENT_METADATA,
- nostaples.utils.properties.GenericStateCallback(self, 'show_document_metadata'))
+ nostaples.utils.properties.PropertyStateCallback(self, 'show_document_metadata'))
# PROPERTY SETTERS
- set_prop_save_path = nostaples.utils.properties.GenericPropertySetter(
+ set_prop_save_path = nostaples.utils.properties.StatefulPropertySetter(
'save_path')
- set_prop_author = nostaples.utils.properties.GenericPropertySetter(
+ set_prop_author = nostaples.utils.properties.StatefulPropertySetter(
'author')
- set_prop_saved_keywords = nostaples.utils.properties.GenericPropertySetter(
- 'saved_keywords')
- set_prop_show_document_metadata = nostaples.utils.properties.GenericPropertySetter(
+ set_prop_show_document_metadata = nostaples.utils.properties.StatefulPropertySetter(
'show_document_metadata')
\ No newline at end of file
diff --git a/utils/properties.py b/utils/properties.py
index b3131ff..8a0b697 100644
--- a/utils/properties.py
+++ b/utils/properties.py
@@ -1,76 +1,77 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the utilities that ease the burden of working with
python-gtkmvc properties.
"""
-class GenericPropertySetter(object):
+class StatefulPropertySetter(object):
"""
- This callable object overrides the python-gtkmvc
- accessors established in gtkmvc.support.metaclass_base.py.
+ This callable object can override the python-gtkmvc
+ accessor functions created for properties in
+ gtkmvc.support.metaclass_base.py.
It handles not only notifying observers of changes in the
property, but also persist changes to the state backend.
"""
def __init__(self, property_name):
"""
Store the property name which is visible to the
application as well as its attribute name.
"""
self.property_name = property_name
self.property_attr_name = '_prop_%s' % self.property_name
def __call__(self, cls, value):
"""
Write state and notify observers of changes.
For more details on how this works see
L{set_prop_active_scanner}.
"""
old_value = getattr(cls, self.property_attr_name)
if old_value == value:
return
setattr(cls, self.property_attr_name, value)
cls.application.get_state_manager()[self.property_name] = value
cls.notify_property_value_change(
self.property_name, old_value, value)
-class GenericStateCallback(object):
+class PropertyStateCallback(object):
"""
This callable object encasuplates the most common reaction to
a state callback: setting the attribute on the model
(which in turn causes property notifications, etc).
"""
def __init__(self, model, property_name):
"""
Store property a name as well as the model
that owns this property.
"""
self.model = model
self.property_name = property_name
def __call__(self):
"""
Set the property attribute on the model, initiating
observer callbacks, etc.
"""
setattr(
self.model,
self.property_name,
self.model.application.get_state_manager()[self.property_name])
\ No newline at end of file
diff --git a/views/document.py b/views/document.py
index 13bb236..06bfec4 100644
--- a/views/document.py
+++ b/views/document.py
@@ -1,142 +1,145 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the DocumentView which exposes the document being
scanned as a thumbnail list.
"""
import logging
import os
import cairo
import gtk
from gtkmvc.view import View
import pango
import pangocairo
from nostaples import constants
class DocumentView(View):
"""
Exposes the document being scanned as a thumbnail list.
"""
def __init__(self, application):
"""
Constructs the DocumentView, including setting up controls that could
not be configured in Glade and constructing sub-views.
"""
self.application = application
document_view_glade = os.path.join(
constants.GUI_DIRECTORY, 'document_view.glade')
View.__init__(
self, application.get_document_controller(),
document_view_glade, 'dummy_document_view_window',
None, False)
self.log = logging.getLogger(self.__class__.__name__)
# Setup controls that could not be configured in Glade
self['thumbnails_tree_view'] = gtk.TreeView()
self['thumbnails_column'] = gtk.TreeViewColumn(None)
self['thumbnails_cell'] = gtk.CellRendererPixbuf()
self['thumbnails_column'].set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
- self['thumbnails_column'].set_fixed_width(constants.DEFAULT_THUMBNAIL_SIZE)
+ self['thumbnails_column'].set_fixed_width(
+ constants.DEFAULT_THUMBNAIL_SIZE)
self['thumbnails_tree_view'].append_column(self['thumbnails_column'])
self['thumbnails_column'].pack_start(self['thumbnails_cell'], True)
self['thumbnails_column'].set_cell_data_func(
self['thumbnails_cell'], self.thumbnails_column_cell_data_func)
self['thumbnails_tree_view'].get_selection().set_mode(
gtk.SELECTION_SINGLE)
self['thumbnails_tree_view'].set_headers_visible(False)
self['thumbnails_tree_view'].set_property('can-focus', False)
self['thumbnails_tree_view'].set_reorderable(True)
self['thumbnails_scrolled_window'].add(self['thumbnails_tree_view'])
self['thumbnails_context_menu'] = gtk.Menu()
self['delete_menu_item'] = gtk.MenuItem('Delete')
self['thumbnails_context_menu'].append(self['delete_menu_item'])
self['thumbnails_context_menu'].show_all()
# Dock sub-views
page_view = self.application.get_page_view()
page_view['page_view_table'].reparent(
self['page_view_docking_viewport'])
application.get_document_controller().register_view(self)
self.log.debug('Created.')
- def thumbnails_column_cell_data_func(self, column, cell_renderer, document_model, iter):
+ def thumbnails_column_cell_data_func(
+ self, column, cell_renderer, document_model, iter):
"""
Extract the thumbnail pixbuf from the PageModel stored in the
DocumentModel ListStore, composite a page number into that image,
and set the resulting pixbuf to the cell renderer.
"""
page_model = document_model.get_value(iter, 0)
page_number = document_model.get_path(iter)[0] + 1
# Copy thumbnail pixbuf, get pixmap of image, and create cairo context
pixbuf = page_model.thumbnail_pixbuf.copy()
pixmap, mask = pixbuf.render_pixmap_and_mask()
context = pangocairo.CairoContext(pixmap.cairo_create())
context.set_antialias(cairo.ANTIALIAS_NONE)
# Setup layout to render page number
layout = context.create_layout()
layout.set_text(str(page_number))
layout.set_font_description(pango.FontDescription('Sans 10'))
# Compute text area
text_extents = layout.get_pixel_size()
x_margin = 2
y_margin = 1
x = 0
width = x_margin + text_extents[0] + x_margin
height = y_margin + text_extents[1] + y_margin
y = pixbuf.get_height() - height
# Render background for page number
text_width, text_height = layout.get_pixel_size()
context.rectangle(x, y, width, height - 1)
context.set_source_rgb(255, 255, 255)
context.fill_preserve()
# Render page number layout
context.set_source_rgb(0, 0, 0)
context.move_to(x + x_margin, y + y_margin)
context.show_layout(layout)
# Get pixbuf back from pixmap and set to cell renderer
- pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, -1, -1)
+ pixbuf.get_from_drawable(
+ pixmap, pixmap.get_colormap(), 0, 0, 0, 0, -1, -1)
cell_renderer.set_property('pixbuf', pixbuf)
def set_adjustments_sensitive(self, sensitive):
"""
Set all adjustment controls sensitive or insensitive
to user input.
"""
self['brightness_label'].set_sensitive(sensitive)
self['brightness_scale'].set_sensitive(sensitive)
self['contrast_label'].set_sensitive(sensitive)
self['contrast_scale'].set_sensitive(sensitive)
self['sharpness_label'].set_sensitive(sensitive)
self['sharpness_scale'].set_sensitive(sensitive)
self['adjust_all_pages_check'].set_sensitive(sensitive)
\ No newline at end of file
diff --git a/views/main.py b/views/main.py
index 7e40368..cfa8f26 100644
--- a/views/main.py
+++ b/views/main.py
@@ -1,150 +1,182 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the MainView which exposes the application's main
window.
"""
import logging
import os
import gtk
from gtkmvc.view import View
from nostaples import constants
class MainView(View):
"""
Exposes the application's main window.
"""
def __init__(self, application):
"""
Constructs the MainView, including setting up controls that could
not be configured in Glade and constructing sub-views.
"""
self.application = application
scan_window_glade = os.path.join(
constants.GUI_DIRECTORY, 'scan_window.glade')
View.__init__(
self, application.get_main_controller(),
scan_window_glade, ['scan_window', 'progress_window'],
None, False)
self.log = logging.getLogger(self.__class__.__name__)
# Setup controls which can not be configured in Glade
self['scan_window'].set_geometry_hints(min_width=600, min_height=400)
# Setup sub views
document_view = self.application.get_document_view()
document_view['document_view_horizontal_box'].reparent(
self['document_view_docking_viewport'])
self['document_view_docking_viewport'].show_all()
status_view = self.application.get_status_view()
status_view['statusbar'].reparent(
self['status_view_docking_viewport'])
self['status_view_docking_viewport'].show_all()
# All controls are disabled by default, they become
# avaiable when an event indicates that they should be.
self.set_scan_controls_sensitive(False)
self.set_file_controls_sensitive(False)
self.set_delete_controls_sensitive(False)
self.set_zoom_controls_sensitive(False)
self.set_adjustment_controls_sensitive(False)
self.set_navigation_controls_sensitive(False)
document_view.set_adjustments_sensitive(False)
application.get_main_controller().register_view(self)
self.log.debug('Created.')
def set_file_controls_sensitive(self, sensitive):
"""
Enables or disables all gui widgets related to saving.
"""
self['save_as_menu_item'].set_sensitive(sensitive)
self['save_as_button'].set_sensitive(sensitive)
def set_scan_controls_sensitive(self, sensitive):
"""
Enables or disables all gui widgets related to scanning and
setting of scanner options.
"""
self['scan_menu_item'].set_sensitive(sensitive)
self['scan_button'].set_sensitive(sensitive)
self['scanner_menu_item'].set_sensitive(sensitive)
self['scan_mode_menu_item'].set_sensitive(sensitive)
self['scan_resolution_menu_item'].set_sensitive(sensitive)
def set_refresh_scanner_controls_sensitive(self, sensitive):
"""
Enable or disable all gui widgets related to refreshing the
available hardware for scanning.
"""
self['refresh_available_scanners_menu_item'].set_sensitive(sensitive)
self['refresh_available_scanners_button'].set_sensitive(sensitive)
def set_delete_controls_sensitive(self, sensitive):
"""
Enables or disables all gui widgets related to deleting or reordering
pages.
"""
self['delete_menu_item'].set_sensitive(sensitive)
def set_zoom_controls_sensitive(self, sensitive):
"""
Enables or disables all gui widgets related to zooming.
"""
self['zoom_in_menu_item'].set_sensitive(sensitive)
self['zoom_out_menu_item'].set_sensitive(sensitive)
self['zoom_one_to_one_menu_item'].set_sensitive(sensitive)
self['zoom_best_fit_menu_item'].set_sensitive(sensitive)
self['zoom_in_button'].set_sensitive(sensitive)
self['zoom_out_button'].set_sensitive(sensitive)
self['zoom_one_to_one_button'].set_sensitive(sensitive)
self['zoom_best_fit_button'].set_sensitive(sensitive)
def set_adjustment_controls_sensitive(self, sensitive):
"""
Enables or disables all gui widgets related to making adjustments to
the current page.
"""
self['rotate_counter_clockwise_menu_item'].set_sensitive(sensitive)
self['rotate_clockwise_menu_item'].set_sensitive(sensitive)
self['rotate_all_pages_menu_item'].set_sensitive(sensitive)
self['rotate_counter_clockwise_button'].set_sensitive(sensitive)
self['rotate_clockwise_button'].set_sensitive(sensitive)
self.application.get_document_view().set_adjustments_sensitive(sensitive)
def set_navigation_controls_sensitive(self, sensitive):
"""
Enables or disables all gui widgets related to navigation.
"""
self['go_first_menu_item'].set_sensitive(sensitive)
self['go_previous_menu_item'].set_sensitive(sensitive)
self['go_next_menu_item'].set_sensitive(sensitive)
self['go_last_menu_item'].set_sensitive(sensitive)
self['go_first_button'].set_sensitive(sensitive)
self['go_previous_button'].set_sensitive(sensitive)
self['go_next_button'].set_sensitive(sensitive)
- self['go_last_button'].set_sensitive(sensitive)
\ No newline at end of file
+ self['go_last_button'].set_sensitive(sensitive)
+
+ def run_device_exception_dialog(self, exc_info):
+ """
+ Display an error dialog that provides the user with the option of
+ blacklisting the device which caused the error.
+
+ TODO: Rebuild dialog in Glade.
+ """
+ dialog = gtk.MessageDialog(
+ parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_NONE)
+ dialog.set_title('')
+
+ # TODO: is this needed?
+ if gtk.check_version (2, 4, 0) is not None:
+ dialog.set_has_separator (False)
+
+ primary = "<big><b>A hardware exception has been logged.</b></big>"
+ secondary = '<b>Device:</b> %s\n<b>Exception:</b> %s\n\n%s' % (
+ exc_info[1].device.display_name,
+ exc_info[1].message,
+ 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.')
+
+ dialog.set_markup(primary)
+ dialog.format_secondary_markup(secondary)
+
+ dialog.add_button('Blacklist Device', constants.RESPONSE_BLACKLIST_DEVICE)
+ dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
+
+ response = dialog.run()
+ dialog.destroy()
+
+ return response
\ No newline at end of file
diff --git a/views/preferences.py b/views/preferences.py
index d228f41..21a6f60 100644
--- a/views/preferences.py
+++ b/views/preferences.py
@@ -1,72 +1,120 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the PreferencesView which exposes user settings
through a dialog seperate from the main application window.
"""
import logging
import os
import gtk
from gtkmvc.view import View
from nostaples import constants
from nostaples.utils.gui import read_combobox, setup_combobox
class PreferencesView(View):
"""
Exposes user settings through a dialog seperate from the main
application window.
"""
def __init__(self, application):
"""
Constructs the PreferencesView, including setting up controls that
could not be configured in Glade.
"""
self.application = application
+ preferences_controller = application.get_preferences_controller()
+
preferences_dialog_glade = os.path.join(
constants.GUI_DIRECTORY, 'preferences_dialog.glade')
View.__init__(
- self, application.get_preferences_controller(),
+ self, preferences_controller,
preferences_dialog_glade, 'preferences_dialog',
None, False)
self.log = logging.getLogger(self.__class__.__name__)
# Can not configure this via constructor do to the multiple
# root windows in the Main View.
- self['preferences_dialog'].set_transient_for(application.get_main_view()['scan_window'])
+ self['preferences_dialog'].set_transient_for(
+ application.get_main_view()['scan_window'])
+ # These two combobox's are setup dynamically. Because of this they
+ # must have their signal handlers connected manually. Otherwise
+ # their signals will fire before the view creation is finished.
setup_combobox(
self['preview_mode_combobox'],
constants.PREVIEW_MODES_LIST,
application.get_preferences_model().preview_mode)
+ self['preview_mode_combobox'].connect(
+ 'changed',
+ preferences_controller.on_preview_mode_combobox_changed)
+
setup_combobox(
self['thumbnail_size_combobox'],
constants.THUMBNAIL_SIZE_LIST,
application.get_preferences_model().thumbnail_size)
+ self['thumbnail_size_combobox'].connect(
+ 'changed',
+ preferences_controller.on_thumbnail_size_combobox_changed)
+
+ # Setup the blacklist tree view
+ blacklist_liststore = gtk.ListStore(str)
+ self['blacklist_tree_view'] = gtk.TreeView()
+ self['blacklist_tree_view'].set_model(blacklist_liststore)
+ self['blacklist_column'] = gtk.TreeViewColumn(None)
+ self['blacklist_cell'] = gtk.CellRendererText()
+ self['blacklist_tree_view'].append_column(self['blacklist_column'])
+ self['blacklist_column'].pack_start(self['blacklist_cell'], True)
+ self['blacklist_column'].add_attribute(self['blacklist_cell'], 'text', 0)
+ self['blacklist_tree_view'].get_selection().set_mode(
+ gtk.SELECTION_SINGLE)
+ self['blacklist_tree_view'].set_headers_visible(False)
+ self['blacklist_tree_view'].set_property('can-focus', False)
+
+ self['blacklist_scrolled_window'].add(self['blacklist_tree_view'])
+ self['blacklist_scrolled_window'].show_all()
+
+ # Setup the keywords tree view
+ keywords_liststore = gtk.ListStore(str)
+ self['keywords_tree_view'] = gtk.TreeView()
+ self['keywords_tree_view'].set_model(keywords_liststore)
+ self['keywords_column'] = gtk.TreeViewColumn(None)
+ self['keywords_cell'] = gtk.CellRendererText()
+ self['keywords_tree_view'].append_column(self['keywords_column'])
+ self['keywords_column'].pack_start(self['keywords_cell'], True)
+ self['keywords_column'].add_attribute(self['keywords_cell'], 'text', 0)
+ self['keywords_tree_view'].get_selection().set_mode(
+ gtk.SELECTION_SINGLE)
+ self['keywords_tree_view'].set_headers_visible(False)
+ self['keywords_tree_view'].set_property('can-focus', False)
+
+ self['keywords_scrolled_window'].add(self['keywords_tree_view'])
+ self['keywords_scrolled_window'].show_all()
+
application.get_preferences_controller().register_view(self)
self.log.debug('Created.')
def run(self):
"""Run the modal preferences dialog."""
self['preferences_dialog'].run()
\ No newline at end of file
|
onyxfish/nostaples
|
99c25be4b18a3098971e6ca4880db71c5795ef52
|
Extracted generic versions of property setters and state callbacks into utility classes.
|
diff --git a/constants.py b/constants.py
index 1432a0e..2ebc999 100644
--- a/constants.py
+++ b/constants.py
@@ -1,97 +1,98 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
'''
This module contains global configuration constants that are not likely to
change often as well as enumeration-like state constants.
'''
import os
import gtk
import Image
from reportlab.lib.pagesizes import A0, A1, A2, A3, A4, A5, A6, \
B0, B1, B2, B3, B4, B5, B6, LETTER, LEGAL, ELEVENSEVENTEEN
PAGESIZES = {'A0' : A0,
'A1' : A1,
'A2' : A2,
'A3' : A3,
'A4' : A4,
'A5' : A5,
'A6' : A6,
'B0' : B0,
'B1' : B1,
'B2' : B2,
'B3' : B3,
'B4' : B4,
'B5' : B5,
'B6' : B6,
'LETTER' : LETTER,
'LEGAL' : LEGAL,
'ELEVENSEVENTEEN' : ELEVENSEVENTEEN}
DEFAULT_SHOW_TOOLBAR = True
DEFAULT_SHOW_STATUSBAR = True
DEFAULT_SHOW_THUMBNAILS = True
DEFAULT_SHOW_ADJUSTMENTS = False
DEFAULT_ROTATE_ALL_PAGES = False
DEFAULT_ACTIVE_SCANNER = ''
DEFAULT_SCAN_MODE = 'Color'
DEFAULT_SCAN_RESOLUTION = '75'
DEFAULT_SAVE_PATH = ''
DEFAULT_AUTHOR = os.getenv('LOGNAME')
DEFAULT_SAVED_KEYWORDS = []
DEFAULT_PREVIEW_MODE = 'Bilinear (Default)'
DEFAULT_THUMBNAIL_SIZE = 128
+DEFAULT_SHOW_DOCUMENT_METADATA = True
SCAN_CANCELLED = -1
SCAN_FAILURE = 0
SCAN_SUCCESS = 1
GCONF_DIRECTORY = '/apps/nostaples'
GCONF_TUPLE_SEPARATOR = '|'
GCONF_LIST_SEPARATOR = '^'
# TODO: rename to CONFIG_DIRECTORY
TEMP_IMAGES_DIRECTORY = os.path.expanduser('~/.nostaples')
LOGGING_CONFIG = os.path.join(os.path.dirname(__file__), 'logging.config')
GUI_DIRECTORY = os.path.join(os.path.dirname(__file__), 'gui')
PREVIEW_MODES = \
{
'Nearest (Fastest)': gtk.gdk.INTERP_NEAREST,
'Tiles': gtk.gdk.INTERP_TILES,
'Bilinear (Default)': gtk.gdk.INTERP_BILINEAR,
'Antialias (Smoothest)': gtk.gdk.INTERP_HYPER
}
PREVIEW_MODES_LIST = \
[
'Nearest (Fastest)',
'Tiles',
'Bilinear (Default)',
'Antialias (Smoothest)'
]
THUMBNAIL_SIZE_LIST = \
[
32,
64,
128,
256
]
\ No newline at end of file
diff --git a/controllers/save.py b/controllers/save.py
index fc473a0..70e2a35 100644
--- a/controllers/save.py
+++ b/controllers/save.py
@@ -1,305 +1,306 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the L{SaveController}, which manages interaction
between the L{SaveModel} and L{SaveView}.
"""
import logging
import os
import sys
import tempfile
import gtk
from gtkmvc.controller import Controller
import Image, ImageEnhance
from reportlab.pdfgen.canvas import Canvas as PdfCanvas
from reportlab.lib.pagesizes import landscape, portrait
from reportlab.lib.units import inch as points_per_inch
from nostaples import constants
import nostaples.utils.gui
class SaveController(Controller):
"""
Manages interaction between the L{SaveModel} and
L{SaveView}.
"""
# SETUP METHODS
def __init__(self, application):
"""
Constructs the SaveController.
"""
self.application = application
Controller.__init__(self, application.get_save_model())
status_controller = application.get_status_controller()
self.status_context = \
status_controller.get_context_id(self.__class__.__name__)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def register_view(self, view):
"""
Registers this controller with a view.
"""
Controller.register_view(self, view)
save_model = self.application.get_save_model()
# Force refresh of keyword list
keywords_liststore = view['keywords_entry'].get_liststore()
keywords_liststore.clear()
for keyword in save_model.saved_keywords:
keywords_liststore.append([keyword])
self.log.debug('%s registered.', view.__class__.__name__)
def register_adapters(self):
"""
Registers adapters for property/widget pairs that do not require
complex processing.
"""
self.adapt('title', 'title_entry')
self.adapt('author', 'author_entry')
self.adapt('keywords', 'keywords_entry')
+ self.adapt('show_document_metadata', 'document_metadata_expander')
self.log.debug('Adapters registered.')
# USER INTERFACE CALLBACKS
def on_title_from_filename_button_clicked(self, button):
"""
Copy the selected filename to the pdf title property.
"""
save_view = self.application.get_save_view()
title = save_view['save_dialog'].get_filename()
if not title:
save_view['title_entry'].set_text('')
return
title = title.split('/')[-1]
if title[-4:] == '.pdf':
title = title[:-4]
save_view['title_entry'].set_text(title)
def on_clear_title_button_clicked(self, button):
"""Clear the title."""
self.application.get_save_model().title = ''
def on_clear_author_button_clicked(self, button):
"""Clear the author."""
self.application.get_save_model().author = ''
def on_clear_keywords_button_clicked(self, button):
"""Clear the keywords."""
self.application.get_save_model().keywords = ''
def on_save_dialog_response(self, dialog, response):
"""
Determine the selected file type and invoke the method
that saves that file type.
"""
save_model = self.application.get_save_model()
save_view = self.application.get_save_view()
main_view = self.application.get_main_view()
save_view['save_dialog'].hide()
if response != gtk.RESPONSE_ACCEPT:
return
main_view['scan_window'].window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
nostaples.utils.gui.flush_pending_events()
save_model.filename = save_view['save_dialog'].get_filename()
filename_filter = save_view['save_dialog'].get_filter()
if filename_filter.get_name() == 'PDF Files':
if save_model.filename[-4:] != '.pdf':
save_model.filename = ''.join([save_model.filename, '.pdf'])
self._save_pdf()
else:
self.log.error('Unknown file type: %s.' % save_model.filename)
self._update_saved_keywords()
main_view['scan_window'].window.set_cursor(None)
save_model.save_path = save_view['save_dialog'].get_current_folder()
# PROPERTY CALLBACKS
def property_saved_keywords_value_change(self, model, old_value, new_value):
"""
Update the keywords auto-completion control with the new
keywords.
"""
save_view = self.application.get_save_view()
keywords_liststore = save_view['keywords_entry'].get_liststore()
keywords_liststore.clear()
for keyword in new_value:
keywords_liststore.append([keyword])
# PRIVATE METHODS
def _save_pdf(self):
"""
Output the current document to a PDF file using ReportLab.
"""
save_model = self.application.get_save_model()
save_view = self.application.get_save_view()
document_model = self.application.get_document_model()
# TODO: seperate saving code into its own thread?
# Setup output pdf
pdf = PdfCanvas(save_model.filename)
pdf.setTitle(save_model.title)
pdf.setAuthor(save_model.author)
pdf.setKeywords(save_model.keywords)
# Generate pages
page_iter = document_model.get_iter_first()
while page_iter:
current_page = document_model.get_value(page_iter, 0)
# Write transformed image
temp_file_path = ''.join([tempfile.mktemp(), '.bmp'])
current_page.pil_image.save(temp_file_path)
assert os.path.exists(temp_file_path), \
'Temporary bitmap file was not created by PIL.'
width_in_inches = \
int(current_page.width / current_page.resolution)
height_in_inches = \
int(current_page.height / current_page.resolution)
# NB: Because not all SANE backends support specifying the size
# of the scan area, the best we can do is scan at the default
# setting and then convert that to an appropriate PDF. For the
# vast majority of scanners we hope that this would be either
# letter or A4.
pdf_width, pdf_height = self._determine_best_fitting_pagesize(
width_in_inches, height_in_inches)
pdf.setPageSize((pdf_width, pdf_height))
pdf.drawImage(
temp_file_path,
0, 0, width=pdf_width, height=pdf_height,
preserveAspectRatio=True)
pdf.showPage()
os.remove(temp_file_path)
page_iter = document_model.iter_next(page_iter)
# Save complete PDF
pdf.save()
assert os.path.exists(save_model.filename), \
'Final PDF file was not created by ReportLab.'
document_model.clear()
def _determine_best_fitting_pagesize(self, width_in_inches, height_in_inches):
"""
Searches through the possible page sizes and finds the smallest one that
will contain the image without cropping.
"""
image_width_in_points = width_in_inches * points_per_inch
image_height_in_points = height_in_inches * points_per_inch
nearest_size = None
nearest_distance = sys.maxint
for size in constants.PAGESIZES.values():
# Orient the size to match the page
if image_width_in_points > image_height_in_points:
size = landscape(size)
else:
size = portrait(size)
# Only compare the size if its large enough to contain the entire
# image
if size[0] < image_width_in_points or \
size[1] < image_height_in_points:
continue
# Compute distance for comparison
distance = \
size[0] - image_width_in_points + \
size[1] - image_height_in_points
# Save if closer than prior nearest distance
if distance < nearest_distance:
nearest_distance = distance
nearest_size = size
# Stop searching if a perfect match is found
if nearest_distance == 0:
break
assert nearest_size != None, 'No nearest size found.'
return nearest_size
def _update_saved_keywords(self):
"""
Update the saved keywords with any new keywords that
have been used.
"""
save_model = self.application.get_save_model()
new_keywords = []
for keyword in save_model.keywords.split():
if keyword not in save_model.saved_keywords:
new_keywords.append(keyword)
if new_keywords:
temp_list = []
temp_list.extend(save_model.saved_keywords)
temp_list.extend(new_keywords)
save_model.saved_keywords = temp_list
# PUBLIC METHODS
def run(self):
"""Run the save dialog."""
save_model = self.application.get_save_model()
save_view = self.application.get_save_view()
status_controller = self.application.get_status_controller()
save_view['save_dialog'].set_current_folder(save_model.save_path)
save_view['save_dialog'].set_current_name('')
status_controller.push(self.status_context, 'Saving...')
save_view.run()
status_controller.pop(self.status_context)
\ No newline at end of file
diff --git a/gui/save_dialog.glade b/gui/save_dialog.glade
index e5a4d6e..82e66e2 100644
--- a/gui/save_dialog.glade
+++ b/gui/save_dialog.glade
@@ -1,261 +1,261 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--Generated with glade3 3.4.5 on Sat Jan 24 20:29:32 2009 -->
+<!--Generated with glade3 3.4.5 on Fri Feb 20 20:29:18 2009 -->
<glade-interface>
<widget class="GtkFileChooserDialog" id="save_dialog">
<property name="border_width">5</property>
<property name="title" translatable="yes">Save</property>
<property name="modal">True</property>
<property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property>
<property name="destroy_with_parent">True</property>
<property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property>
<property name="skip_taskbar_hint">True</property>
<property name="skip_pager_hint">True</property>
<property name="has_separator">False</property>
- <property name="preview_widget_active">False</property>
- <property name="do_overwrite_confirmation">True</property>
<property name="use_preview_label">False</property>
+ <property name="do_overwrite_confirmation">True</property>
+ <property name="preview_widget_active">False</property>
<property name="action">GTK_FILE_CHOOSER_ACTION_SAVE</property>
<signal name="response" handler="on_save_dialog_response"/>
<child internal-child="vbox">
<widget class="GtkVBox" id="dialog-vbox6">
<property name="visible">True</property>
<property name="spacing">2</property>
<child>
- <widget class="GtkExpander" id="pdf_properties_expander">
+ <widget class="GtkExpander" id="document_metadata_expander">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="expanded">True</property>
<child>
<widget class="GtkAlignment" id="alignment1">
<property name="visible">True</property>
<property name="top_padding">12</property>
<property name="bottom_padding">6</property>
<child>
<widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<property name="spacing">6</property>
<child>
<widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
<property name="spacing">6</property>
<child>
<widget class="GtkLabel" id="label2">
<property name="width_request">80</property>
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes"><b>Title:</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="title_entry">
<property name="visible">True</property>
<property name="can_focus">True</property>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="title_from_filename_button">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="tooltip" translatable="yes">Copy from filename</property>
<property name="response_id">0</property>
<signal name="clicked" handler="on_title_from_filename_button_clicked"/>
<child>
<widget class="GtkImage" id="image1">
<property name="visible">True</property>
<property name="stock">gtk-copy</property>
<property name="icon_size">1</property>
</widget>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="clear_title_button">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="tooltip" translatable="yes">Clear</property>
<property name="response_id">0</property>
<signal name="clicked" handler="on_clear_title_button_clicked"/>
<child>
<widget class="GtkImage" id="image2">
<property name="visible">True</property>
<property name="stock">gtk-clear</property>
<property name="icon_size">1</property>
</widget>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">3</property>
</packing>
</child>
</widget>
</child>
<child>
<widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
<property name="spacing">6</property>
<child>
<widget class="GtkLabel" id="label3">
<property name="width_request">80</property>
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes"><b>Author:</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="author_entry">
<property name="visible">True</property>
<property name="can_focus">True</property>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="clear_author_button">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="tooltip" translatable="yes">Clear</property>
<property name="response_id">0</property>
<signal name="clicked" handler="on_clear_author_button_clicked"/>
<child>
<widget class="GtkImage" id="image3">
<property name="visible">True</property>
<property name="stock">gtk-clear</property>
<property name="icon_size">1</property>
</widget>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkHBox" id="keywords_hbox">
<property name="visible">True</property>
<property name="spacing">6</property>
<child>
<widget class="GtkLabel" id="label4">
<property name="width_request">80</property>
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes"><b>Keywords:</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<widget class="GtkButton" id="clear_keywords_button">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="tooltip" translatable="yes">Clear</property>
<property name="response_id">0</property>
<signal name="clicked" handler="on_clear_keywords_button_clicked"/>
<child>
<widget class="GtkImage" id="image4">
<property name="visible">True</property>
<property name="stock">gtk-clear</property>
<property name="icon_size">1</property>
</widget>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">GTK_PACK_END</property>
<property name="position">2</property>
</packing>
</child>
</widget>
<packing>
<property name="position">2</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label1">
<property name="visible">True</property>
- <property name="label" translatable="yes">PDF Properties</property>
+ <property name="label" translatable="yes">Document Metadata</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
<child internal-child="action_area">
<widget class="GtkHButtonBox" id="dialog-action_area6">
<property name="visible">True</property>
<property name="layout_style">GTK_BUTTONBOX_END</property>
<child>
<widget class="GtkButton" id="button2">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="label" translatable="yes">gtk-cancel</property>
<property name="use_stock">True</property>
<property name="response_id">-6</property>
</widget>
</child>
<child>
<widget class="GtkButton" id="button1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="can_default">True</property>
<property name="has_default">True</property>
<property name="receives_default">True</property>
<property name="label" translatable="yes">gtk-save</property>
<property name="use_stock">True</property>
<property name="response_id">-3</property>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">GTK_PACK_END</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
diff --git a/models/main.py b/models/main.py
index 6842673..55e47b1 100644
--- a/models/main.py
+++ b/models/main.py
@@ -1,376 +1,324 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the MainModel, which manages general application
data.
"""
import logging
from gtkmvc.model import Model
from nostaples import constants
+import nostaples.utils.properties
import saneme
class MainModel(Model):
"""
Handles data all data not specifically handled by another Model
(e.g. the state of the main application window).
Note: active_scanner is a tuple in the format (display_name,
sane_name). available_scanners is a list of such tuples.
"""
__properties__ = \
{
'show_toolbar' : True,
'show_statusbar' : True,
'show_thumbnails' : True,
'show_adjustments' : False,
'rotate_all_pages' : False,
'active_scanner' : None, # saneme.Device
'active_mode' : None,
'active_resolution' : None,
'available_scanners' : [], # [] of saneme.Device
'valid_modes' : [],
'valid_resolutions' : [],
'scan_in_progress' : False,
'updating_available_scanners' : False,
'updating_scan_options' : False,
}
def __init__(self, application):
"""
Constructs the MainModel, as well as necessary sub-models.
"""
self.application = application
Model.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def load_state(self):
"""
Load persisted state from the self.state_manager.
"""
state_manager = self.application.get_state_manager()
sane = self.application.get_sane()
self.show_toolbar = state_manager.init_state(
'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR,
- self.state_show_toolbar_change)
+ nostaples.utils.properties.GenericStateCallback(self, 'show_toolbar'))
self.show_statusbar = state_manager.init_state(
'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR,
- self.state_show_statusbar_change)
+ nostaples.utils.properties.GenericStateCallback(self, 'show_statusbar'))
self.show_thumbnails = state_manager.init_state(
'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS,
- self.state_show_thumbnails_change)
+ nostaples.utils.properties.GenericStateCallback(self, 'show_thumbnails'))
self.show_adjustments = state_manager.init_state(
'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS,
- self.state_show_adjustments_change)
+ nostaples.utils.properties.GenericStateCallback(self, 'show_adjustments'))
self.rotate_all_pages = state_manager.init_state(
'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES,
- self.state_rotate_all_pages_change)
+ nostaples.utils.properties.GenericStateCallback(self, 'rotate_all_pages'))
# The local representation of active_scanner is a
# saneme.Device, but it is persisted by its name attribute only.
try:
self.active_scanner = sane.get_device_by_name(
state_manager.init_state(
'active_scanner', constants.DEFAULT_ACTIVE_SCANNER,
self.state_active_scanner_change))
except saneme.SaneNoSuchDeviceError:
self.active_scanner = None
self.active_mode = state_manager.init_state(
'scan_mode', constants.DEFAULT_SCAN_MODE,
self.state_scan_mode_change)
self.active_resolution = state_manager.init_state(
'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION,
self.state_scan_resolution_change)
- # Property setters
- # (see gtkmvc.support.metaclass_base.py for the origin of these accessors)
+ # PROPERTY SETTERS
- class GenericPropertySetter(object):
- """
- This callable object overrides the python-gtkmvc
- accessors established in gtkmvc.support.metaclass_base.py.
-
- It handles not only notifying observers of changes in the
- property, but also persist changes to the state backend.
- """
- def __init__(self, property_name, state_name):
- """
- Store the property name which is visible to the
- application as well as its attribute name.
- """
- self.property_name = property_name
- self.state_name = state_name
- self.property_attr_name = '_prop_%s' % self.property_name
-
- def __call__(self, cls, value):
- """
- Write state to gconf and notify observers of changes.
-
- For more details on how this works see
- L{set_prop_active_scanner}.
- """
- old_value = getattr(cls, self.property_attr_name)
- if old_value == value:
- return
- setattr(cls, self.property_attr_name, value)
- cls.application.get_state_manager()[self.state_name] = value
- cls.notify_property_value_change(
- self.property_name, old_value, value)
-
- set_prop_show_toolbar = GenericPropertySetter('show_toolbar', 'show_toolbar')
- set_prop_show_statusbar = GenericPropertySetter('show_statusbar', 'show_statusbar')
- set_prop_show_thumbnails = GenericPropertySetter('show_thumbnails', 'show_thumbnails')
- set_prop_show_adjustments = GenericPropertySetter('show_adjustments', 'show_adjustments')
- set_prop_rotate_all_pages = GenericPropertySetter('rotate_all_pages', 'rotate_all_pages')
+ set_prop_show_toolbar = nostaples.utils.properties.GenericPropertySetter(
+ 'show_toolbar')
+ set_prop_show_statusbar = nostaples.utils.properties.GenericPropertySetter(
+ 'show_statusbar')
+ set_prop_show_thumbnails = nostaples.utils.properties.GenericPropertySetter(
+ 'show_thumbnails')
+ set_prop_show_adjustments = nostaples.utils.properties.GenericPropertySetter(
+ 'show_adjustments')
+ set_prop_rotate_all_pages = nostaples.utils.properties.GenericPropertySetter(
+ 'rotate_all_pages')
def set_prop_active_scanner(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
main_controller = self.application.get_main_controller()
# Ignore spurious updates
old_value = self._prop_active_scanner
if old_value == value:
return
# Close the old scanner
old_value.close()
if value is not None:
assert isinstance(value, saneme.Device)
# Update the internal property variable
self._prop_active_scanner = value
# Only persist the state if the new value is not None
# and it can be opened without error.
# This prevents problems with trying to store a Null
# value in the state backend and also allows for smooth
# transitions if a scanner is disconnected and reconnected.
if value is not None:
# TODO: handle exceptions
try:
value.open()
except saneme.SaneError, e:
main_controller.display_device_exception_dialog(e)
self.application.get_state_manager()['active_scanner'] = value.name
# Emit the property change notification to all observers.
self.notify_property_value_change(
'active_scanner', old_value, value)
def set_prop_active_mode(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_active_mode
if old_value == value:
return
self._prop_active_mode = value
if value is not None:
self.application.get_state_manager()['scan_mode'] = value
self.notify_property_value_change(
'active_mode', old_value, value)
def set_prop_active_resolution(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_active_resolution
if old_value == value:
return
self._prop_active_resolution = value
if value is not None:
self.application.get_state_manager()['scan_resolution'] = value
self.notify_property_value_change(
'active_resolution', old_value, value)
def set_prop_available_scanners(self, value):
"""
Set the list of available scanners, updating the active_scanner
if it is no longer in the list.
"""
main_controller = self.application.get_main_controller()
old_value = self._prop_available_scanners
if len(value) == 0:
self._prop_active_scanner = None
else:
# Select the first available scanner if the previously
# selected scanner is not in the new list
# We avoid the active_scanner property setter so that
# The property notification callbacks will not be fired
# until after the menu has been updated.
if self._prop_active_scanner not in value:
try:
value[0].open()
self._prop_active_scanner = value[0]
self.application.get_state_manager()['active_scanner'] = \
value[0].name
except saneme.SaneError, e:
main_controller.display_device_exception_dialog(e)
# Otherwise maintain current selection
else:
pass
self._prop_available_scanners = value
# This will only actually cause an update if
# old_value != value
self.notify_property_value_change(
'available_scanners', old_value, value)
# Force the scanner options to update, even if the active
# scanner did not change. This is necessary in case the
# current value was loaded from state, in which case the
# options will not yet have been loaded).
self.notify_property_value_change(
'active_scanner', None, self._prop_active_scanner)
def set_prop_valid_modes(self, value):
"""
Set the list of valid scan modes, updating the active_mode
if it is no longer in the list.
See L{set_prop_available_scanners} for detailed comments.
"""
old_value = self._prop_valid_modes
if len(value) == 0:
self._prop_active_mode = None
else:
if self._prop_active_mode not in value:
self._prop_active_mode = value[0]
self.application.get_state_manager()['scan_mode'] = value[0]
else:
pass
self._prop_valid_modes = value
self.notify_property_value_change(
'valid_modes', old_value, value)
self.notify_property_value_change(
'active_mode', None, self._prop_active_mode)
def set_prop_valid_resolutions(self, value):
"""
Set the list of valid scan resolutions, updating the
active_resolution if it is no longer in the list.
See L{set_prop_available_scanners} for detailed comments.
"""
old_value = self._prop_valid_resolutions
if len(value) == 0:
self._prop_active_resolution = None
else:
if self._prop_active_resolution not in value:
self._prop_active_resolution = value[0]
self.application.get_state_manager()['scan_resolution'] = \
value[0]
else:
pass
self._prop_valid_resolutions = value
self.notify_property_value_change(
'valid_resolutions', old_value, value)
self.notify_property_value_change(
'active_resolution', None, self._prop_active_resolution)
# STATE CALLBACKS
-
- def state_show_toolbar_change(self):
- """Read state."""
- self.show_toolbar = \
- self.application.get_state_manager()['show_toolbar']
-
- def state_show_statusbar_change(self):
- """Read state."""
- self.show_statusbar = \
- self.application.get_state_manager()['show_statusbar']
-
- def state_show_thumbnails_change(self):
- """Read state."""
- self.show_thumbnails = \
- self.application.get_state_manager()['show_thumbnails']
-
- def state_show_adjustments_change(self):
- """Read state."""
- self.show_adjustments = \
- self.application.get_state_manager()['show_adjustments']
-
- def state_rotate_all_pages_change(self):
- """Read state."""
- self.rotate_all_pages = \
- self.application.get_state_manager()['rotate_all_pages']
def state_active_scanner_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
sane = self.application.get_sane()
if state_manager['active_scanner'] in self.available_scanners:
try:
self.active_scanner = sane.get_device_by_name(state_manager['active_scanner'])
except SaneNoSuchDeviceError:
raise
else:
state_manager['active_scanner'] = self.active_scanner.name
def state_scan_mode_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
if state_manager['scan_mode'] in self.valid_modes:
self.active_mode = state_manager['scan_mode']
else:
state_manager['scan_mode'] = self.active_mode
def state_scan_resolution_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
if state_manager['scan_resolution'] in self.valid_resolutions:
self.active_resolution = state_manager['scan_resolution']
else:
state_manager['scan_resolution'] = self.active_resolution
\ No newline at end of file
diff --git a/models/save.py b/models/save.py
index c85bc98..8e15c5e 100644
--- a/models/save.py
+++ b/models/save.py
@@ -1,131 +1,90 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the SaveModel, which manages data related to
saving documents.
"""
import logging
from gtkmvc.model import Model
from nostaples import constants
+import nostaples.utils.properties
class SaveModel(Model):
"""
Handles data the metadata associated with saving documents.
"""
__properties__ = \
{
'save_path' : '',
'title' : '',
'author' : '',
'keywords' : '',
'saved_keywords' : '',
+ 'show_document_metadata' : True,
+
'filename' : '',
}
def __init__(self, application):
"""
Constructs the SaveModel.
"""
self.application = application
Model.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def load_state(self):
"""
Load persisted state from the self.state_manager.
"""
state_manager = self.application.get_state_manager()
self.save_path = state_manager.init_state(
'save_path', constants.DEFAULT_SAVE_PATH,
- self.state_save_path_change)
+ nostaples.utils.properties.GenericStateCallback(self, 'save_path'))
self.author = state_manager.init_state(
'author', constants.DEFAULT_AUTHOR,
- self.state_author_change)
+ nostaples.utils.properties.GenericStateCallback(self, 'author'))
self.saved_keywords = state_manager.init_state(
'saved_keywords', constants.DEFAULT_SAVED_KEYWORDS,
- self.state_saved_keywords_change)
-
- # Property setters
- # (see gtkmvc.support.metaclass_base.py for the origin of these accessors)
-
- def set_prop_save_path(self, value):
- """
- Write state.
- See L{MainModel.set_prop_active_scanner} for detailed comments.
- """
- old_value = self._prop_save_path
- if old_value == value:
- return
- self._prop_save_path = value
- self.application.get_state_manager()['save_path'] = value
- self.notify_property_value_change(
- 'save_path', old_value, value)
-
- def set_prop_author(self, value):
- """
- Write state.
- See L{MainModel.set_prop_active_scanner} for detailed comments.
- """
- old_value = self._prop_author
- if old_value == value:
- return
- self._prop_author = value
- self.application.get_state_manager()['author'] = value
- self.notify_property_value_change(
- 'author', old_value, value)
+ nostaples.utils.properties.GenericStateCallback(self, 'saved_keywords'))
- def set_prop_saved_keywords(self, value):
- """
- Write state.
- See L{MainModel.set_prop_active_scanner} for detailed comments.
- """
- old_value = self._prop_saved_keywords
- if old_value == value:
- return
- self._prop_saved_keywords = value
- self.application.get_state_manager()['saved_keywords'] = value
- self.notify_property_value_change(
- 'saved_keywords', old_value, value)
+ self.show_document_metadata = state_manager.init_state(
+ 'show_document_metadata', constants.DEFAULT_SHOW_DOCUMENT_METADATA,
+ nostaples.utils.properties.GenericStateCallback(self, 'show_document_metadata'))
- # STATE CALLBACKS
-
- def state_save_path_change(self):
- """Read state."""
- self.save_path = \
- self.application.get_state_manager()['save_path']
-
- def state_author_change(self):
- """Read state."""
- self.author = \
- self.application.get_state_manager()['author']
+ # PROPERTY SETTERS
- def state_saved_keywords_change(self):
- """Read state."""
- self.saved_keywords = \
- self.application.get_state_manager()['saved_keywords']
\ No newline at end of file
+ set_prop_save_path = nostaples.utils.properties.GenericPropertySetter(
+ 'save_path')
+ set_prop_author = nostaples.utils.properties.GenericPropertySetter(
+ 'author')
+ set_prop_saved_keywords = nostaples.utils.properties.GenericPropertySetter(
+ 'saved_keywords')
+ set_prop_show_document_metadata = nostaples.utils.properties.GenericPropertySetter(
+ 'show_document_metadata')
\ No newline at end of file
diff --git a/utils/properties.py b/utils/properties.py
new file mode 100644
index 0000000..b3131ff
--- /dev/null
+++ b/utils/properties.py
@@ -0,0 +1,76 @@
+#!/usr/bin/python
+
+#~ This file is part of NoStaples.
+
+#~ NoStaples is free software: you can redistribute it and/or modify
+#~ it under the terms of the GNU General Public License as published by
+#~ the Free Software Foundation, either version 3 of the License, or
+#~ (at your option) any later version.
+
+#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
+
+"""
+This module holds the utilities that ease the burden of working with
+python-gtkmvc properties.
+"""
+
+class GenericPropertySetter(object):
+ """
+ This callable object overrides the python-gtkmvc
+ accessors established in gtkmvc.support.metaclass_base.py.
+
+ It handles not only notifying observers of changes in the
+ property, but also persist changes to the state backend.
+ """
+ def __init__(self, property_name):
+ """
+ Store the property name which is visible to the
+ application as well as its attribute name.
+ """
+ self.property_name = property_name
+ self.property_attr_name = '_prop_%s' % self.property_name
+
+ def __call__(self, cls, value):
+ """
+ Write state and notify observers of changes.
+
+ For more details on how this works see
+ L{set_prop_active_scanner}.
+ """
+ old_value = getattr(cls, self.property_attr_name)
+ if old_value == value:
+ return
+ setattr(cls, self.property_attr_name, value)
+ cls.application.get_state_manager()[self.property_name] = value
+ cls.notify_property_value_change(
+ self.property_name, old_value, value)
+
+class GenericStateCallback(object):
+ """
+ This callable object encasuplates the most common reaction to
+ a state callback: setting the attribute on the model
+ (which in turn causes property notifications, etc).
+ """
+ def __init__(self, model, property_name):
+ """
+ Store property a name as well as the model
+ that owns this property.
+ """
+ self.model = model
+ self.property_name = property_name
+
+ def __call__(self):
+ """
+ Set the property attribute on the model, initiating
+ observer callbacks, etc.
+ """
+ setattr(
+ self.model,
+ self.property_name,
+ self.model.application.get_state_manager()[self.property_name])
\ No newline at end of file
|
onyxfish/nostaples
|
5439d663247cfa2bad5858460cad2a8140bdd580
|
Fixed crash when launching About dialog.
|
diff --git a/controllers/main.py b/controllers/main.py
index 9c158fd..78138ca 100644
--- a/controllers/main.py
+++ b/controllers/main.py
@@ -86,703 +86,703 @@ class MainController(Controller):
"""Exits the application."""
self.quit()
def on_scan_menu_item_activate(self, menu_item):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_menu_item_activate(self, menu_item):
"""Refresh the list of connected scanners from SANE."""
self._update_available_scanners()
def on_save_as_menu_item_activate(self, menu_item):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_delete_menu_item_activate(self, menu_item):
self.application.get_document_controller().delete_selected()
def on_preferences_menu_item_activate(self, menu_item):
"""Creates and displays a preferences dialog."""
self.application.show_preferences_dialog()
def on_quit_menu_item_activate(self, menu_item):
"""Exits the application."""
self.quit()
def on_zoom_in_menu_item_activate(self, menu_item):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_menu_item_activate(self, menu_item):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_menu_item_activate(self, menu_item):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_menu_item_activate(self, menu_item):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_available_scanner_menu_item_toggled(self, menu_item):
"""
Set the active scanner.
TODO: Need a second scanner to properly test this...
"""
main_model = self.application.get_main_model()
if menu_item.get_active():
for scanner in main_model.available_scanners:
if scanner.display_name == menu_item.get_children()[0].get_text():
main_model.active_scanner = scanner
return
def on_valid_mode_menu_item_toggled(self, menu_item):
"""Sets the active scan mode."""
if menu_item.get_active():
self.application.get_main_model().active_mode = \
menu_item.get_children()[0].get_text()
def on_valid_resolution_menu_item_toggled(self, menu_item):
"""Sets the active scan resolution."""
if menu_item.get_active():
self.application.get_main_model().active_resolution = \
menu_item.get_children()[0].get_text()
def on_go_first_menu_item_activate(self, menu_item):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_menu_item_activate(self, menu_item):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_menu_item_activate(self, menu_item):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_menu_item_activate(self, menu_item):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
def on_contents_menu_item_clicked(self, menu_item):
"""TODO"""
pass
def on_about_menu_item_activate(self, menu_item):
"""Show the about dialog."""
self.application.show_about_dialog()
# Toolbar Buttons
def on_scan_button_clicked(self, button):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_button_clicked(self, button):
self._update_available_scanners()
def on_save_as_button_clicked(self, button):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_zoom_in_button_clicked(self, button):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_button_clicked(self, button):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_button_clicked(self, button):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_button_clicked(self, button):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_go_first_button_clicked(self, button):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_button_clicked(self, button):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_button_clicked(self, button):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_button_clicked(self, button):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
# Progress Window INTERFACE CALLBACKS
def on_progress_window_delete_event(self, window, event):
"""
Emulate clicking of the cancel/close button and then
hide the window.
"""
main_view = self.application.get_main_view()
self.on_scan_cancel_button_clicked(None)
main_view['progress_window'].hide()
return True
def on_scan_cancel_button_clicked(self, button):
"""
Cancel the current scan or, if the scan is finished,
close the progress window.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress:
assert self.cancel_event
self.cancel_event.set()
else:
main_view['progress_window'].hide()
def on_scan_again_button_clicked(self, button):
"""Initiate a new scan from the progress window."""
self._scan()
def on_quick_save_button_clicked(self, button):
"""
Show the save dialog. If the user completes a save
then disable the quick save button until another
page is scanned.
"""
main_view = self.application.get_main_view()
document_model = self.application.get_document_model()
self.application.show_save_dialog()
if document_model.count == 0:
main_view['quick_save_button'].set_sensitive(False)
# MainModel PROPERTY CALLBACKS
def property_show_toolbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the toolbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_toolbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['main_toolbar'].show()
else:
main_view['main_toolbar'].hide()
def property_show_statusbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the statusbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_statusbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['status_view_docking_viewport'].show()
else:
main_view['status_view_docking_viewport'].hide()
def property_show_thumbnails_value_change(self, model, old_value, new_value):
"""Update the visibility of the thumbnails."""
main_view = self.application.get_main_view()
menu_item = main_view['show_thumbnails_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_thumbnails_visible(new_value)
def property_show_adjustments_value_change(self, model, old_value, new_value):
"""Update the visibility of the adjustments controls."""
main_view = self.application.get_main_view()
menu_item = main_view['show_adjustments_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_adjustments_visible(new_value)
def property_active_scanner_value_change(self, model, old_value, new_value):
"""
Update the menu and valid scanner options to match the new device.
"""
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
for menu_item in main_view['scanner_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value.display_name:
menu_item.set_active(True)
break
self._update_scanner_options()
def property_active_mode_value_change(self, model, old_value, new_value):
"""Select the active mode from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_mode_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_active_resolution_value_change(self, model, old_value, new_value):
"""Select the active resolution from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_resolution_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_available_scanners_value_change(self, model, old_value, new_value):
"""
Update the menu of available scanners.
"""
main_view = self.application.get_main_view()
self._clear_available_scanners_sub_menu()
# Generate the new menu
if len(new_value) == 0:
menu_item = gtk.MenuItem('No Scanners Connected')
menu_item.set_sensitive(False)
main_view['scanner_sub_menu'].append(menu_item)
else:
first_item = None
for i in range(len(new_value)):
# The first menu item defines the group
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i].display_name)
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i].display_name)
main_view['scanner_sub_menu'].append(menu_item)
main_view['scanner_sub_menu'].show_all()
def property_valid_modes_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan modes for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_modes_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Modes")
menu_item.set_sensitive(False)
main_view['scan_mode_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled)
main_view['scan_mode_sub_menu'].append(menu_item)
main_view['scan_mode_sub_menu'].show_all()
def property_valid_resolutions_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan resolutions for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_resolutions_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Resolutions")
menu_item.set_sensitive(False)
main_view['scan_resolution_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled)
main_view['scan_resolution_sub_menu'].append(menu_item)
main_view['scan_resolution_sub_menu'].show_all()
def property_scan_in_progress_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_available_scanners_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_scan_options_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
# DocumentModel PROPERTY CALLBACKS
def property_count_value_change(self, model, old_value, new_value):
"""Toggle available controls."""
self._toggle_document_controls()
# THREAD CALLBACKS
def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned):
main_view = self.application.get_main_view()
short_bytes_scanned = float(bytes_scanned) / 1000
short_total_bytes = float(scan_info.total_bytes) / 1000
main_view['scan_progressbar'].set_fraction(
float(bytes_scanned) / scan_info.total_bytes)
main_view['scan_progressbar'].set_text(
'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes))
# TODO: multi page scans
main_view['progress_secondary_label'].set_markup(
'<i>Scanning page.</i>')
def on_scan_succeeded(self, scanning_thread, pil_image):
"""
Append the new page to the current document.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
main_view['scan_progressbar'].set_fraction(1)
main_view['scan_progressbar'].set_text('Scan complete')
main_view['progress_secondary_label'].set_markup(
'<i>Adding page to document.</i>')
gtk.gdk.flush()
new_page = PageModel(self.application, pil_image, int(main_model.active_resolution))
self.application.get_document_model().append(new_page)
main_view['progress_secondary_label'].set_markup(
'<i>Page added.</i>')
main_view['scan_again_button'].set_sensitive(True)
main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
def on_scan_failed(self, scanning_thread, reason):
"""
Set that scan is complete.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
main_view['progress_secondary_label'].set_markup(
'<i>%s</i>' % reason)
main_view['scan_again_button'].set_sensitive(True)
if self.application.get_document_model().count > 0:
main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
def on_scan_aborted(self, scanning_thread, exc_info):
"""
Change display to indicate that scanning failed and
convey the to the user the reason why the thread aborted.
If the failure was from a SANE exception then give the
user the option to blacklist the device. If not, then
reraise the error and let the sys.excepthook deal with it.
"""
self.on_scan_failed(scanning_thread, 'An error occurred.')
if isinstance(exc_info[1], saneme.SaneError):
self.display_device_exception_dialog(exc_info)
else:
raise exc_info[0], exc_info[1], exc_info[2]
def on_update_available_scanners_thread_finished(self, update_thread, scanner_list):
"""Set the new list of available scanners."""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.available_scanners = scanner_list
main_model.updating_available_scanners = False
def on_update_available_scanners_thread_aborted(self, update_thread, exc_info):
"""
Change the display to indicate that no scanners are available and
reraise the exception so that it can be caught by the sys.excepthook.
There is no reason to handle these cases with a special dialog,
if the application failed to even enumerate the available devices then
no other action will be possible.
This should be fantastically rare.
"""
self.on_update_available_scanners_thread_finished(update_thread, [])
raise exc_info[0], exc_info[1], exc_info[2]
def on_update_scanner_options_thread_finished(self, update_thread, mode_list, resolution_list):
"""
Update the mode and resolution lists and rark that
the scanner is no longer in use.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.valid_modes = mode_list
main_model.valid_resolutions = resolution_list
main_model.updating_scan_options = False
def on_update_scanner_options_thread_aborted(self, update_thread, exc_info):
"""
Change display to indicate that updating the options failed and
convey the to the user the reason why the thread aborted.
If the failure was from a SANE exception then give the
user the option to blacklist the device. If not, then
reraise the error and let the sys.excepthook deal with it.
"""
# TODO: If this fails the scanner icon will still stay lit,
# and when the user clicks it the app will error again since it
# will not have a valid mode/resolution.
self.on_update_scanner_options_thread_finished(update_thread, [], [])
- if isinstance(e, saneme.SaneError):
+ if isinstance(exc_info[1], saneme.SaneError):
self.display_device_exception_dialog(exc_info)
else:
raise exc_info[0], exc_info[1], exc_info[2]
# PUBLIC METHODS
def quit(self):
"""Exits the application."""
self.log.debug('Quit.')
gtk.main_quit()
# PRIVATE METHODS
def _clear_available_scanners_sub_menu(self):
"""Clear the menu of available scanners."""
main_view = self.application.get_main_view()
for child in main_view['scanner_sub_menu'].get_children():
main_view['scanner_sub_menu'].remove(child)
def _clear_scan_modes_sub_menu(self):
"""Clear the menu of valid scan modes."""
main_view = self.application.get_main_view()
for child in main_view['scan_mode_sub_menu'].get_children():
main_view['scan_mode_sub_menu'].remove(child)
def _clear_scan_resolutions_sub_menu(self):
"""Clear the menu of valid scan resolutions."""
main_view = self.application.get_main_view()
for child in main_view['scan_resolution_sub_menu'].get_children():
main_view['scan_resolution_sub_menu'].remove(child)
def _toggle_scan_controls(self):
"""Toggle whether or not the scan controls or accessible."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_scan_controls_sensitive(False)
main_view.set_refresh_scanner_controls_sensitive(False)
else:
if main_model.active_scanner != None:
main_view.set_scan_controls_sensitive(True)
main_view.set_refresh_scanner_controls_sensitive(True)
def _toggle_document_controls(self):
"""
Toggle available document controls based on the current scanner
status and the number of scanned pages.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
# Disable all controls when the scanner is in use
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
count = self.application.get_document_model().count
# Disable all controls if no pages are scanned
if count == 0:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
# Enable most controls if any pages scanned
main_view.set_file_controls_sensitive(True)
main_view.set_delete_controls_sensitive(True)
main_view.set_zoom_controls_sensitive(True)
main_view.set_adjustment_controls_sensitive(True)
# Only enable navigation if more than one page scanned
if count > 1:
main_view.set_navigation_controls_sensitive(True)
else:
main_view.set_navigation_controls_sensitive(False)
def _update_status(self):
"""
Update the text of the statusbar based on the current state
of the application.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
status_controller.pop(self.status_context)
if main_model.scan_in_progress:
status_controller.push(self.status_context, 'Scanning...')
elif main_model.updating_available_scanners:
status_controller.push(self.status_context, 'Querying hardware...')
elif main_model.updating_scan_options:
status_controller.push(self.status_context, 'Querying options...')
else:
if main_model.active_scanner:
status_controller.push(self.status_context,
'Ready with %s.' % main_model.active_scanner.display_name)
else:
status_controller.push(self.status_context, 'No scanner available.')
def _scan(self):
"""Begin a scan."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
main_model.scan_in_progress = True
scanning_thread = ScanningThread(
main_model.active_scanner, main_model.active_mode, main_model.active_resolution)
scanning_thread.connect("progress", self.on_scan_progress)
scanning_thread.connect("succeeded", self.on_scan_succeeded)
scanning_thread.connect("failed", self.on_scan_failed)
scanning_thread.connect("aborted", self.on_scan_aborted)
self.cancel_event = scanning_thread.cancel_event
main_view['progress_primary_label'].set_markup(
'<big><b>%s</b></big>' % main_model.active_scanner.display_name)
main_view['scan_progressbar'].set_fraction(0)
main_view['scan_progressbar'].set_text('Waiting for data')
main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>')
mode = main_model.active_mode if main_model.active_mode else 'Not set'
main_view['progress_mode_label'].set_markup(mode)
dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set'
main_view['progress_resolution_label'].set_markup(dpi)
main_view['scan_again_button'].set_sensitive(False)
main_view['quick_save_button'].set_sensitive(False)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL)
main_view['progress_window'].show_all()
scanning_thread.start()
def _update_available_scanners(self):
"""
Start a new update thread to query for available scanners.
"""
sane = self.application.get_sane()
main_model = self.application.get_main_model()
main_model.updating_available_scanners = True
update_thread = UpdateAvailableScannersThread(sane)
update_thread.connect("finished", self.on_update_available_scanners_thread_finished)
update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted)
update_thread.start()
def _update_scanner_options(self):
"""Determine the valid options for the current scanner."""
main_model = self.application.get_main_model()
main_model.updating_scan_options = True
update_thread = UpdateScannerOptionsThread(main_model.active_scanner)
update_thread.connect("finished", self.on_update_scanner_options_thread_finished)
update_thread.connect("aborted", self.on_update_scanner_options_thread_aborted)
update_thread.start()
def display_device_exception_dialog(self, exc_info):
"""
Display an error dialog that provides the user with the option of
blacklisting the device which caused the error.
"""
dialog = gtk.MessageDialog(
parent=None, flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_NONE)
dialog.set_title("")
# TODO: is this needed?
if gtk.check_version (2, 4, 0) is not None:
dialog.set_has_separator (False)
primary = "<big><b>A hardware exception has been logged.</b></big>"
secondary = '%s\n\n%s' % (exc_info[1].message, 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.')
dialog.set_markup(primary)
dialog.format_secondary_markup(secondary)
dialog.add_button('Blacklist Device', 1)
dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
response = dialog.run()
dialog.destroy()
# TODO: handle blacklisting
\ No newline at end of file
diff --git a/utils/scanning.py b/utils/scanning.py
index 782d611..7f5fab6 100644
--- a/utils/scanning.py
+++ b/utils/scanning.py
@@ -1,226 +1,229 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains those functions (in the form of Thread objects)
that interface with scanning hardware via SANE.
"""
import commands
import logging
import os
import re
import sys
import tempfile
import threading
import gobject
from nostaples import constants
import saneme
class IdleObject(gobject.GObject):
"""
Override gobject.GObject to always emit signals in the main thread
by emitting on an idle handler.
This class is based on an example by John Stowers:
U{http://www.johnstowers.co.nz/blog/index.php/tag/pygtk/}
"""
def __init__(self):
gobject.GObject.__init__(self)
def emit(self, *args):
gobject.idle_add(gobject.GObject.emit, self, *args)
def abort_on_exception(func):
"""
This function decorator wraps the run() method of a thread
so that any exceptions in that thread will be logged and
cause the threads 'abort' signal to be emitted with the exception
as an argument. This way all exception handling can occur
on the main thread.
+
+ Note that the entire sys.exc_info() tuple is passed out, this
+ allows the current traceback to be used in the other thread.
"""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception, e:
thread_object = args[0]
exc_info = sys.exc_info()
thread_object.log.error('Exception type %s: %s' % (e.__class__.__name__, e.message))
thread_object.emit('aborted', exc_info)
return wrapper
class UpdateAvailableScannersThread(IdleObject, threading.Thread):
"""
Responsible for getting an updated list of available scanners
and passing it back to the main thread.
"""
__gsignals__ = {
'finished': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
'aborted': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane = sane
self.log.debug('Created.')
@abort_on_exception
def run(self):
"""
Queries SANE for a list of connected scanners and updates
the list of available scanners from the results.
"""
self.log.debug('Updating available scanners.')
devices = self.sane.get_device_list()
# NB: We callback with the lists so that they can updated on the main thread
self.emit('finished', devices)
class ScanningThread(IdleObject, threading.Thread):
"""
Responsible for scanning a page and emitting status
callbacks on the main thread.
This thread should treat its reference to the ScanningModel
as read-only. That way we don't have to worry about making
the Model thread-safe.
"""
__gsignals__ = {
'progress': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)),
'succeeded': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
'failed': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)),
'aborted': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane_device, mode, resolution):
"""
Initialize the thread and get a tempfile name that
will house the scanned image.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.mode = mode
self.resolution = resolution
self.cancel_event = threading.Event()
def progress_callback(self, scan_info, bytes_scanned):
"""
Pass the progress information on the the main thread
and cancel the scan if the cancel event has been set.
"""
self.emit("progress", scan_info, bytes_scanned)
if self.cancel_event.isSet():
return True
else:
return False
@abort_on_exception
def run(self):
"""
Set scanner options, scan a page and emit status callbacks.
"""
if not self.sane_device.is_open():
raise AssertionError('sane_device.is_open() returned false')
self.log.debug('Setting device options.')
try:
self.sane_device.options['mode'].value = self.mode
except saneme.SaneReloadOptionsError:
# TODO
pass
try:
self.sane_device.options['resolution'].value = int(self.resolution)
except saneme.SaneReloadOptionsError:
# TODO
pass
self.log.debug('Beginning scan.')
pil_image = None
pil_image = self.sane_device.scan(self.progress_callback)
if self.cancel_event.isSet():
self.emit("failed", "Scan cancelled")
else:
if not pil_image:
raise AssertionError('sane_device.scan() returned None')
self.emit('succeeded', pil_image)
class UpdateScannerOptionsThread(IdleObject, threading.Thread):
"""
Responsible for getting an up-to-date list of valid scanner options
and passing it back to the main thread.
"""
__gsignals__ = {
'finished': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
'aborted': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane_device):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.log.debug('Created.')
@abort_on_exception
def run(self):
"""
Queries SANE for a list of available options for the specified scanner.
"""
assert self.sane_device.is_open()
self.log.debug('Updating scanner options.')
mode_list = self.sane_device.options['mode'].constraint
resolution_list = [str(i) for i in self.sane_device.options['resolution'].constraint]
# NB: We callback with the lists so that they can updated on the main thread
self.emit('finished', mode_list, resolution_list)
\ No newline at end of file
diff --git a/views/about.py b/views/about.py
index 01e7958..4811a66 100644
--- a/views/about.py
+++ b/views/about.py
@@ -1,54 +1,59 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the AboutView which exposes the application's
about dialog.
"""
import logging
import os
import gtk
from gtkmvc.view import View
from nostaples import constants
class AboutView(View):
"""
Exposes the application's main window.
"""
def __init__(self, application):
"""Constructs the AboutView."""
self.application = application
about_dialog_glade = os.path.join(
constants.GUI_DIRECTORY, 'about_dialog.glade')
View.__init__(
self, self.application.get_about_controller(),
about_dialog_glade, 'about_dialog',
- self.application.get_main_view(), False)
+ None, False)
self.log = logging.getLogger(self.__class__.__name__)
+ # Can't do this in constructor as main_view has multiple
+ # top-level widgets
+ self['about_dialog'].set_transient_for(
+ self.application.get_main_view()['scan_window'])
+
self.application.get_about_controller().register_view(self)
self.log.debug('Created.')
def run(self):
"""Run this modal dialog."""
self['about_dialog'].run()
\ No newline at end of file
diff --git a/views/save.py b/views/save.py
index abea893..1a7f24d 100644
--- a/views/save.py
+++ b/views/save.py
@@ -1,79 +1,79 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the MainView which exposes the application's main
window.
"""
import logging
import os
import gtk
from gtkmvc.view import View
from nostaples import constants
import nostaples.utils.gui
class SaveView(View):
"""
Exposes the application's main window.
"""
def __init__(self, application):
"""
Constructs the MainView, including setting up controls that could
not be configured in Glade and constructing sub-views.
"""
self.application = application
save_dialog_glade = os.path.join(
constants.GUI_DIRECTORY, 'save_dialog.glade')
View.__init__(
self, self.application.get_save_controller(),
save_dialog_glade, 'save_dialog',
None, False)
self.log = logging.getLogger(self.__class__.__name__)
# Can't do this in constructor as main_view has multiple
- # top widgets
+ # top-level widgets
self['save_dialog'].set_transient_for(
self.application.get_main_view()['scan_window'])
# Setup filename filter
filename_filter = gtk.FileFilter()
filename_filter.set_name('PDF Files')
filename_filter.add_mime_type('application/pdf')
filename_filter.add_pattern('*.pdf')
self['save_dialog'].add_filter(filename_filter)
# Setup custom control
self['keywords_entry'] = nostaples.utils.gui.KeywordsCompletionEntry()
self['keywords_hbox'].pack_start(self['keywords_entry'])
self['keywords_entry'].show()
model = self['keywords_entry'].get_liststore()
for word in ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]:
model.append([word])
self.application.get_save_controller().register_view(self)
self.log.debug('Created.')
def run(self):
"""Run the modal save dialog."""
self['save_dialog'].run()
\ No newline at end of file
|
onyxfish/nostaples
|
3f5025af8117734266c1fc0eb9d16d61292719a4
|
Fixed thread exception handling so that tracebacks are passed back to the main thread for handling.
|
diff --git a/controllers/main.py b/controllers/main.py
index a74cf8e..9c158fd 100644
--- a/controllers/main.py
+++ b/controllers/main.py
@@ -22,767 +22,767 @@ between the L{MainModel} and L{MainView}.
import commands
import logging
import os
import re
import threading
import gobject
import gtk
from gtkmvc.controller import Controller
from nostaples.models.page import PageModel
from nostaples.utils.scanning import *
import saneme
class MainController(Controller):
"""
Manages interaction between the L{MainModel} and L{MainView}.
"""
# SETUP METHODS
def __init__(self, application):
"""
Constructs the MainController, as well as necessary sub-controllers
and services.
"""
self.application = application
Controller.__init__(self, application.get_main_model())
application.get_document_model().register_observer(self)
status_controller = application.get_status_controller()
self.status_context = \
status_controller.get_context_id(self.__class__.__name__)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def register_view(self, view):
"""
Registers this controller with a view.
"""
Controller.register_view(self, view)
self.log.debug('%s registered.', view.__class__.__name__)
def register_adapters(self):
"""
Registers adapters for property/widget pairs that do not require
complex processing.
"""
self.adapt('show_toolbar', 'show_toolbar_menu_item')
self.adapt('show_statusbar', 'show_statusbar_menu_item')
self.adapt('show_thumbnails', 'show_thumbnails_menu_item')
self.adapt('show_adjustments', 'show_adjustments_menu_item')
self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item')
self.log.debug('Adapters registered.')
# USER INTERFACE CALLBACKS
# Menu Items
def on_scan_window_destroy(self, window):
"""Exits the application."""
self.quit()
def on_scan_menu_item_activate(self, menu_item):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_menu_item_activate(self, menu_item):
"""Refresh the list of connected scanners from SANE."""
self._update_available_scanners()
def on_save_as_menu_item_activate(self, menu_item):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_delete_menu_item_activate(self, menu_item):
self.application.get_document_controller().delete_selected()
def on_preferences_menu_item_activate(self, menu_item):
"""Creates and displays a preferences dialog."""
self.application.show_preferences_dialog()
def on_quit_menu_item_activate(self, menu_item):
"""Exits the application."""
self.quit()
def on_zoom_in_menu_item_activate(self, menu_item):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_menu_item_activate(self, menu_item):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_menu_item_activate(self, menu_item):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_menu_item_activate(self, menu_item):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_available_scanner_menu_item_toggled(self, menu_item):
"""
Set the active scanner.
TODO: Need a second scanner to properly test this...
"""
main_model = self.application.get_main_model()
if menu_item.get_active():
for scanner in main_model.available_scanners:
if scanner.display_name == menu_item.get_children()[0].get_text():
main_model.active_scanner = scanner
return
def on_valid_mode_menu_item_toggled(self, menu_item):
"""Sets the active scan mode."""
if menu_item.get_active():
self.application.get_main_model().active_mode = \
menu_item.get_children()[0].get_text()
def on_valid_resolution_menu_item_toggled(self, menu_item):
"""Sets the active scan resolution."""
if menu_item.get_active():
self.application.get_main_model().active_resolution = \
menu_item.get_children()[0].get_text()
def on_go_first_menu_item_activate(self, menu_item):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_menu_item_activate(self, menu_item):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_menu_item_activate(self, menu_item):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_menu_item_activate(self, menu_item):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
def on_contents_menu_item_clicked(self, menu_item):
"""TODO"""
pass
def on_about_menu_item_activate(self, menu_item):
"""Show the about dialog."""
self.application.show_about_dialog()
# Toolbar Buttons
def on_scan_button_clicked(self, button):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_button_clicked(self, button):
self._update_available_scanners()
def on_save_as_button_clicked(self, button):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_zoom_in_button_clicked(self, button):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_button_clicked(self, button):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_button_clicked(self, button):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_button_clicked(self, button):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_go_first_button_clicked(self, button):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_button_clicked(self, button):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_button_clicked(self, button):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_button_clicked(self, button):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
# Progress Window INTERFACE CALLBACKS
def on_progress_window_delete_event(self, window, event):
"""
Emulate clicking of the cancel/close button and then
hide the window.
"""
main_view = self.application.get_main_view()
self.on_scan_cancel_button_clicked(None)
main_view['progress_window'].hide()
return True
def on_scan_cancel_button_clicked(self, button):
"""
Cancel the current scan or, if the scan is finished,
close the progress window.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress:
assert self.cancel_event
self.cancel_event.set()
else:
main_view['progress_window'].hide()
def on_scan_again_button_clicked(self, button):
"""Initiate a new scan from the progress window."""
self._scan()
def on_quick_save_button_clicked(self, button):
"""
Show the save dialog. If the user completes a save
then disable the quick save button until another
page is scanned.
"""
main_view = self.application.get_main_view()
document_model = self.application.get_document_model()
self.application.show_save_dialog()
if document_model.count == 0:
main_view['quick_save_button'].set_sensitive(False)
# MainModel PROPERTY CALLBACKS
def property_show_toolbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the toolbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_toolbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['main_toolbar'].show()
else:
main_view['main_toolbar'].hide()
def property_show_statusbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the statusbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_statusbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['status_view_docking_viewport'].show()
else:
main_view['status_view_docking_viewport'].hide()
def property_show_thumbnails_value_change(self, model, old_value, new_value):
"""Update the visibility of the thumbnails."""
main_view = self.application.get_main_view()
menu_item = main_view['show_thumbnails_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_thumbnails_visible(new_value)
def property_show_adjustments_value_change(self, model, old_value, new_value):
"""Update the visibility of the adjustments controls."""
main_view = self.application.get_main_view()
menu_item = main_view['show_adjustments_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_adjustments_visible(new_value)
def property_active_scanner_value_change(self, model, old_value, new_value):
"""
Update the menu and valid scanner options to match the new device.
"""
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
for menu_item in main_view['scanner_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value.display_name:
menu_item.set_active(True)
break
self._update_scanner_options()
def property_active_mode_value_change(self, model, old_value, new_value):
"""Select the active mode from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_mode_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_active_resolution_value_change(self, model, old_value, new_value):
"""Select the active resolution from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_resolution_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_available_scanners_value_change(self, model, old_value, new_value):
"""
Update the menu of available scanners.
"""
main_view = self.application.get_main_view()
self._clear_available_scanners_sub_menu()
# Generate the new menu
if len(new_value) == 0:
menu_item = gtk.MenuItem('No Scanners Connected')
menu_item.set_sensitive(False)
main_view['scanner_sub_menu'].append(menu_item)
else:
first_item = None
for i in range(len(new_value)):
# The first menu item defines the group
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i].display_name)
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i].display_name)
main_view['scanner_sub_menu'].append(menu_item)
main_view['scanner_sub_menu'].show_all()
def property_valid_modes_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan modes for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_modes_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Modes")
menu_item.set_sensitive(False)
main_view['scan_mode_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled)
main_view['scan_mode_sub_menu'].append(menu_item)
main_view['scan_mode_sub_menu'].show_all()
def property_valid_resolutions_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan resolutions for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_resolutions_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Resolutions")
menu_item.set_sensitive(False)
main_view['scan_resolution_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled)
main_view['scan_resolution_sub_menu'].append(menu_item)
main_view['scan_resolution_sub_menu'].show_all()
def property_scan_in_progress_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_available_scanners_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_scan_options_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
# DocumentModel PROPERTY CALLBACKS
def property_count_value_change(self, model, old_value, new_value):
"""Toggle available controls."""
self._toggle_document_controls()
# THREAD CALLBACKS
def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned):
main_view = self.application.get_main_view()
short_bytes_scanned = float(bytes_scanned) / 1000
short_total_bytes = float(scan_info.total_bytes) / 1000
main_view['scan_progressbar'].set_fraction(
float(bytes_scanned) / scan_info.total_bytes)
main_view['scan_progressbar'].set_text(
'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes))
# TODO: multi page scans
main_view['progress_secondary_label'].set_markup(
'<i>Scanning page.</i>')
def on_scan_succeeded(self, scanning_thread, pil_image):
"""
Append the new page to the current document.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
main_view['scan_progressbar'].set_fraction(1)
main_view['scan_progressbar'].set_text('Scan complete')
main_view['progress_secondary_label'].set_markup(
'<i>Adding page to document.</i>')
gtk.gdk.flush()
new_page = PageModel(self.application, pil_image, int(main_model.active_resolution))
self.application.get_document_model().append(new_page)
main_view['progress_secondary_label'].set_markup(
'<i>Page added.</i>')
main_view['scan_again_button'].set_sensitive(True)
main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
def on_scan_failed(self, scanning_thread, reason):
"""
Set that scan is complete.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
main_view['progress_secondary_label'].set_markup(
'<i>%s</i>' % reason)
main_view['scan_again_button'].set_sensitive(True)
if self.application.get_document_model().count > 0:
main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
- def on_scan_aborted(self, scanning_thread, e):
+ def on_scan_aborted(self, scanning_thread, exc_info):
"""
Change display to indicate that scanning failed and
convey the to the user the reason why the thread aborted.
If the failure was from a SANE exception then give the
user the option to blacklist the device. If not, then
reraise the error and let the sys.excepthook deal with it.
"""
self.on_scan_failed(scanning_thread, 'An error occurred.')
-
- if isinstance(e, saneme.SaneError):
- self.display_device_exception_dialog(e)
+
+ if isinstance(exc_info[1], saneme.SaneError):
+ self.display_device_exception_dialog(exc_info)
else:
- raise e
+ raise exc_info[0], exc_info[1], exc_info[2]
def on_update_available_scanners_thread_finished(self, update_thread, scanner_list):
"""Set the new list of available scanners."""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.available_scanners = scanner_list
main_model.updating_available_scanners = False
- def on_update_available_scanners_thread_aborted(self, update_thread, e):
+ def on_update_available_scanners_thread_aborted(self, update_thread, exc_info):
"""
Change the display to indicate that no scanners are available and
reraise the exception so that it can be caught by the sys.excepthook.
There is no reason to handle these cases with a special dialog,
if the application failed to even enumerate the available devices then
no other action will be possible.
This should be fantastically rare.
"""
self.on_update_available_scanners_thread_finished(update_thread, [])
- raise e
+ raise exc_info[0], exc_info[1], exc_info[2]
def on_update_scanner_options_thread_finished(self, update_thread, mode_list, resolution_list):
"""
Update the mode and resolution lists and rark that
the scanner is no longer in use.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.valid_modes = mode_list
main_model.valid_resolutions = resolution_list
main_model.updating_scan_options = False
- def on_update_scanner_options_thread_aborted(self, update_thread, e):
+ def on_update_scanner_options_thread_aborted(self, update_thread, exc_info):
"""
Change display to indicate that updating the options failed and
convey the to the user the reason why the thread aborted.
If the failure was from a SANE exception then give the
user the option to blacklist the device. If not, then
reraise the error and let the sys.excepthook deal with it.
"""
# TODO: If this fails the scanner icon will still stay lit,
# and when the user clicks it the app will error again since it
# will not have a valid mode/resolution.
self.on_update_scanner_options_thread_finished(update_thread, [], [])
if isinstance(e, saneme.SaneError):
- self.display_device_exception_dialog(e)
+ self.display_device_exception_dialog(exc_info)
else:
- raise e
+ raise exc_info[0], exc_info[1], exc_info[2]
# PUBLIC METHODS
def quit(self):
"""Exits the application."""
self.log.debug('Quit.')
gtk.main_quit()
# PRIVATE METHODS
def _clear_available_scanners_sub_menu(self):
"""Clear the menu of available scanners."""
main_view = self.application.get_main_view()
for child in main_view['scanner_sub_menu'].get_children():
main_view['scanner_sub_menu'].remove(child)
def _clear_scan_modes_sub_menu(self):
"""Clear the menu of valid scan modes."""
main_view = self.application.get_main_view()
for child in main_view['scan_mode_sub_menu'].get_children():
main_view['scan_mode_sub_menu'].remove(child)
def _clear_scan_resolutions_sub_menu(self):
"""Clear the menu of valid scan resolutions."""
main_view = self.application.get_main_view()
for child in main_view['scan_resolution_sub_menu'].get_children():
main_view['scan_resolution_sub_menu'].remove(child)
def _toggle_scan_controls(self):
"""Toggle whether or not the scan controls or accessible."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_scan_controls_sensitive(False)
main_view.set_refresh_scanner_controls_sensitive(False)
else:
if main_model.active_scanner != None:
main_view.set_scan_controls_sensitive(True)
main_view.set_refresh_scanner_controls_sensitive(True)
def _toggle_document_controls(self):
"""
Toggle available document controls based on the current scanner
status and the number of scanned pages.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
# Disable all controls when the scanner is in use
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
count = self.application.get_document_model().count
# Disable all controls if no pages are scanned
if count == 0:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
# Enable most controls if any pages scanned
main_view.set_file_controls_sensitive(True)
main_view.set_delete_controls_sensitive(True)
main_view.set_zoom_controls_sensitive(True)
main_view.set_adjustment_controls_sensitive(True)
# Only enable navigation if more than one page scanned
if count > 1:
main_view.set_navigation_controls_sensitive(True)
else:
main_view.set_navigation_controls_sensitive(False)
def _update_status(self):
"""
Update the text of the statusbar based on the current state
of the application.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
status_controller.pop(self.status_context)
if main_model.scan_in_progress:
status_controller.push(self.status_context, 'Scanning...')
elif main_model.updating_available_scanners:
status_controller.push(self.status_context, 'Querying hardware...')
elif main_model.updating_scan_options:
status_controller.push(self.status_context, 'Querying options...')
else:
if main_model.active_scanner:
status_controller.push(self.status_context,
'Ready with %s.' % main_model.active_scanner.display_name)
else:
status_controller.push(self.status_context, 'No scanner available.')
def _scan(self):
"""Begin a scan."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
main_model.scan_in_progress = True
scanning_thread = ScanningThread(
main_model.active_scanner, main_model.active_mode, main_model.active_resolution)
scanning_thread.connect("progress", self.on_scan_progress)
scanning_thread.connect("succeeded", self.on_scan_succeeded)
scanning_thread.connect("failed", self.on_scan_failed)
scanning_thread.connect("aborted", self.on_scan_aborted)
self.cancel_event = scanning_thread.cancel_event
main_view['progress_primary_label'].set_markup(
'<big><b>%s</b></big>' % main_model.active_scanner.display_name)
main_view['scan_progressbar'].set_fraction(0)
main_view['scan_progressbar'].set_text('Waiting for data')
main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>')
mode = main_model.active_mode if main_model.active_mode else 'Not set'
main_view['progress_mode_label'].set_markup(mode)
dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set'
main_view['progress_resolution_label'].set_markup(dpi)
main_view['scan_again_button'].set_sensitive(False)
main_view['quick_save_button'].set_sensitive(False)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL)
main_view['progress_window'].show_all()
scanning_thread.start()
def _update_available_scanners(self):
"""
Start a new update thread to query for available scanners.
"""
sane = self.application.get_sane()
main_model = self.application.get_main_model()
main_model.updating_available_scanners = True
update_thread = UpdateAvailableScannersThread(sane)
update_thread.connect("finished", self.on_update_available_scanners_thread_finished)
update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted)
update_thread.start()
def _update_scanner_options(self):
"""Determine the valid options for the current scanner."""
main_model = self.application.get_main_model()
main_model.updating_scan_options = True
update_thread = UpdateScannerOptionsThread(main_model.active_scanner)
update_thread.connect("finished", self.on_update_scanner_options_thread_finished)
update_thread.connect("aborted", self.on_update_scanner_options_thread_aborted)
update_thread.start()
- def display_device_exception_dialog(self, exception):
+ def display_device_exception_dialog(self, exc_info):
"""
Display an error dialog that provides the user with the option of
blacklisting the device which caused the error.
"""
dialog = gtk.MessageDialog(
parent=None, flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_NONE)
dialog.set_title("")
# TODO: is this needed?
if gtk.check_version (2, 4, 0) is not None:
dialog.set_has_separator (False)
primary = "<big><b>A hardware exception has been logged.</b></big>"
- secondary = '%s\n\n%s' % (exception.message, 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.')
+ secondary = '%s\n\n%s' % (exc_info[1].message, 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.')
dialog.set_markup(primary)
dialog.format_secondary_markup(secondary)
dialog.add_button('Blacklist Device', 1)
dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
response = dialog.run()
dialog.destroy()
# TODO: handle blacklisting
\ No newline at end of file
diff --git a/models/main.py b/models/main.py
index 5747d06..6842673 100644
--- a/models/main.py
+++ b/models/main.py
@@ -1,378 +1,376 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the MainModel, which manages general application
data.
"""
import logging
from gtkmvc.model import Model
from nostaples import constants
import saneme
class MainModel(Model):
"""
Handles data all data not specifically handled by another Model
(e.g. the state of the main application window).
Note: active_scanner is a tuple in the format (display_name,
sane_name). available_scanners is a list of such tuples.
"""
__properties__ = \
{
'show_toolbar' : True,
'show_statusbar' : True,
'show_thumbnails' : True,
'show_adjustments' : False,
'rotate_all_pages' : False,
'active_scanner' : None, # saneme.Device
'active_mode' : None,
'active_resolution' : None,
'available_scanners' : [], # [] of saneme.Device
'valid_modes' : [],
'valid_resolutions' : [],
'scan_in_progress' : False,
'updating_available_scanners' : False,
'updating_scan_options' : False,
}
def __init__(self, application):
"""
Constructs the MainModel, as well as necessary sub-models.
"""
self.application = application
Model.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def load_state(self):
"""
Load persisted state from the self.state_manager.
"""
state_manager = self.application.get_state_manager()
sane = self.application.get_sane()
self.show_toolbar = state_manager.init_state(
'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR,
self.state_show_toolbar_change)
self.show_statusbar = state_manager.init_state(
'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR,
self.state_show_statusbar_change)
self.show_thumbnails = state_manager.init_state(
'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS,
self.state_show_thumbnails_change)
self.show_adjustments = state_manager.init_state(
'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS,
self.state_show_adjustments_change)
self.rotate_all_pages = state_manager.init_state(
'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES,
self.state_rotate_all_pages_change)
# The local representation of active_scanner is a
# saneme.Device, but it is persisted by its name attribute only.
try:
self.active_scanner = sane.get_device_by_name(
state_manager.init_state(
'active_scanner', constants.DEFAULT_ACTIVE_SCANNER,
self.state_active_scanner_change))
except saneme.SaneNoSuchDeviceError:
self.active_scanner = None
self.active_mode = state_manager.init_state(
'scan_mode', constants.DEFAULT_SCAN_MODE,
self.state_scan_mode_change)
self.active_resolution = state_manager.init_state(
'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION,
self.state_scan_resolution_change)
# Property setters
# (see gtkmvc.support.metaclass_base.py for the origin of these accessors)
class GenericPropertySetter(object):
"""
- This 'function factory' produces callable objects
- to override the python-gtkmvc accessors established in
- gtkmvc.support.metaclass_base.py.
+ This callable object overrides the python-gtkmvc
+ accessors established in gtkmvc.support.metaclass_base.py.
- These functions not only handle notifying observers
- of changes in the property, but also persist changes
- to the gconf backend.
+ It handles not only notifying observers of changes in the
+ property, but also persist changes to the state backend.
"""
def __init__(self, property_name, state_name):
"""
Store the property name which is visible to the
application as well as its attribute name.
"""
self.property_name = property_name
self.state_name = state_name
self.property_attr_name = '_prop_%s' % self.property_name
def __call__(self, cls, value):
"""
Write state to gconf and notify observers of changes.
For more details on how this works see
L{set_prop_active_scanner}.
"""
old_value = getattr(cls, self.property_attr_name)
if old_value == value:
return
setattr(cls, self.property_attr_name, value)
cls.application.get_state_manager()[self.state_name] = value
cls.notify_property_value_change(
self.property_name, old_value, value)
set_prop_show_toolbar = GenericPropertySetter('show_toolbar', 'show_toolbar')
set_prop_show_statusbar = GenericPropertySetter('show_statusbar', 'show_statusbar')
set_prop_show_thumbnails = GenericPropertySetter('show_thumbnails', 'show_thumbnails')
set_prop_show_adjustments = GenericPropertySetter('show_adjustments', 'show_adjustments')
set_prop_rotate_all_pages = GenericPropertySetter('rotate_all_pages', 'rotate_all_pages')
def set_prop_active_scanner(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
main_controller = self.application.get_main_controller()
# Ignore spurious updates
old_value = self._prop_active_scanner
if old_value == value:
return
# Close the old scanner
old_value.close()
if value is not None:
assert isinstance(value, saneme.Device)
# Update the internal property variable
self._prop_active_scanner = value
# Only persist the state if the new value is not None
# and it can be opened without error.
# This prevents problems with trying to store a Null
# value in the state backend and also allows for smooth
# transitions if a scanner is disconnected and reconnected.
if value is not None:
# TODO: handle exceptions
try:
value.open()
except saneme.SaneError, e:
main_controller.display_device_exception_dialog(e)
self.application.get_state_manager()['active_scanner'] = value.name
# Emit the property change notification to all observers.
self.notify_property_value_change(
'active_scanner', old_value, value)
def set_prop_active_mode(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_active_mode
if old_value == value:
return
self._prop_active_mode = value
if value is not None:
self.application.get_state_manager()['scan_mode'] = value
self.notify_property_value_change(
'active_mode', old_value, value)
def set_prop_active_resolution(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_active_resolution
if old_value == value:
return
self._prop_active_resolution = value
if value is not None:
self.application.get_state_manager()['scan_resolution'] = value
self.notify_property_value_change(
'active_resolution', old_value, value)
def set_prop_available_scanners(self, value):
"""
Set the list of available scanners, updating the active_scanner
if it is no longer in the list.
"""
main_controller = self.application.get_main_controller()
old_value = self._prop_available_scanners
if len(value) == 0:
self._prop_active_scanner = None
else:
# Select the first available scanner if the previously
# selected scanner is not in the new list
# We avoid the active_scanner property setter so that
# The property notification callbacks will not be fired
# until after the menu has been updated.
if self._prop_active_scanner not in value:
try:
value[0].open()
self._prop_active_scanner = value[0]
self.application.get_state_manager()['active_scanner'] = \
value[0].name
except saneme.SaneError, e:
main_controller.display_device_exception_dialog(e)
# Otherwise maintain current selection
else:
pass
self._prop_available_scanners = value
# This will only actually cause an update if
# old_value != value
self.notify_property_value_change(
'available_scanners', old_value, value)
# Force the scanner options to update, even if the active
# scanner did not change. This is necessary in case the
# current value was loaded from state, in which case the
# options will not yet have been loaded).
self.notify_property_value_change(
'active_scanner', None, self._prop_active_scanner)
def set_prop_valid_modes(self, value):
"""
Set the list of valid scan modes, updating the active_mode
if it is no longer in the list.
See L{set_prop_available_scanners} for detailed comments.
"""
old_value = self._prop_valid_modes
if len(value) == 0:
self._prop_active_mode = None
else:
if self._prop_active_mode not in value:
self._prop_active_mode = value[0]
self.application.get_state_manager()['scan_mode'] = value[0]
else:
pass
self._prop_valid_modes = value
self.notify_property_value_change(
'valid_modes', old_value, value)
self.notify_property_value_change(
'active_mode', None, self._prop_active_mode)
def set_prop_valid_resolutions(self, value):
"""
Set the list of valid scan resolutions, updating the
active_resolution if it is no longer in the list.
See L{set_prop_available_scanners} for detailed comments.
"""
old_value = self._prop_valid_resolutions
if len(value) == 0:
self._prop_active_resolution = None
else:
if self._prop_active_resolution not in value:
self._prop_active_resolution = value[0]
self.application.get_state_manager()['scan_resolution'] = \
value[0]
else:
pass
self._prop_valid_resolutions = value
self.notify_property_value_change(
'valid_resolutions', old_value, value)
self.notify_property_value_change(
'active_resolution', None, self._prop_active_resolution)
# STATE CALLBACKS
def state_show_toolbar_change(self):
"""Read state."""
self.show_toolbar = \
self.application.get_state_manager()['show_toolbar']
def state_show_statusbar_change(self):
"""Read state."""
self.show_statusbar = \
self.application.get_state_manager()['show_statusbar']
def state_show_thumbnails_change(self):
"""Read state."""
self.show_thumbnails = \
self.application.get_state_manager()['show_thumbnails']
def state_show_adjustments_change(self):
"""Read state."""
self.show_adjustments = \
self.application.get_state_manager()['show_adjustments']
def state_rotate_all_pages_change(self):
"""Read state."""
self.rotate_all_pages = \
self.application.get_state_manager()['rotate_all_pages']
def state_active_scanner_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
sane = self.application.get_sane()
if state_manager['active_scanner'] in self.available_scanners:
try:
self.active_scanner = sane.get_device_by_name(state_manager['active_scanner'])
except SaneNoSuchDeviceError:
raise
else:
state_manager['active_scanner'] = self.active_scanner.name
def state_scan_mode_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
if state_manager['scan_mode'] in self.valid_modes:
self.active_mode = state_manager['scan_mode']
else:
state_manager['scan_mode'] = self.active_mode
def state_scan_resolution_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
if state_manager['scan_resolution'] in self.valid_resolutions:
self.active_resolution = state_manager['scan_resolution']
else:
state_manager['scan_resolution'] = self.active_resolution
\ No newline at end of file
diff --git a/utils/scanning.py b/utils/scanning.py
index 76386dc..782d611 100644
--- a/utils/scanning.py
+++ b/utils/scanning.py
@@ -1,224 +1,226 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains those functions (in the form of Thread objects)
that interface with scanning hardware via SANE.
"""
import commands
import logging
import os
import re
+import sys
import tempfile
import threading
import gobject
from nostaples import constants
import saneme
class IdleObject(gobject.GObject):
"""
Override gobject.GObject to always emit signals in the main thread
by emitting on an idle handler.
This class is based on an example by John Stowers:
U{http://www.johnstowers.co.nz/blog/index.php/tag/pygtk/}
"""
def __init__(self):
gobject.GObject.__init__(self)
def emit(self, *args):
gobject.idle_add(gobject.GObject.emit, self, *args)
def abort_on_exception(func):
"""
This function decorator wraps the run() method of a thread
so that any exceptions in that thread will be logged and
cause the threads 'abort' signal to be emitted with the exception
as an argument. This way all exception handling can occur
on the main thread.
"""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception, e:
thread_object = args[0]
+ exc_info = sys.exc_info()
thread_object.log.error('Exception type %s: %s' % (e.__class__.__name__, e.message))
- thread_object.emit('aborted', e)
+ thread_object.emit('aborted', exc_info)
return wrapper
class UpdateAvailableScannersThread(IdleObject, threading.Thread):
"""
Responsible for getting an updated list of available scanners
and passing it back to the main thread.
"""
__gsignals__ = {
'finished': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
'aborted': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane = sane
self.log.debug('Created.')
@abort_on_exception
def run(self):
"""
Queries SANE for a list of connected scanners and updates
the list of available scanners from the results.
"""
self.log.debug('Updating available scanners.')
devices = self.sane.get_device_list()
# NB: We callback with the lists so that they can updated on the main thread
self.emit('finished', devices)
class ScanningThread(IdleObject, threading.Thread):
"""
Responsible for scanning a page and emitting status
callbacks on the main thread.
This thread should treat its reference to the ScanningModel
as read-only. That way we don't have to worry about making
the Model thread-safe.
"""
__gsignals__ = {
'progress': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)),
'succeeded': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
'failed': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)),
'aborted': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane_device, mode, resolution):
"""
Initialize the thread and get a tempfile name that
will house the scanned image.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.mode = mode
self.resolution = resolution
self.cancel_event = threading.Event()
def progress_callback(self, scan_info, bytes_scanned):
"""
Pass the progress information on the the main thread
and cancel the scan if the cancel event has been set.
"""
self.emit("progress", scan_info, bytes_scanned)
if self.cancel_event.isSet():
return True
else:
return False
@abort_on_exception
def run(self):
"""
Set scanner options, scan a page and emit status callbacks.
"""
if not self.sane_device.is_open():
raise AssertionError('sane_device.is_open() returned false')
self.log.debug('Setting device options.')
try:
self.sane_device.options['mode'].value = self.mode
except saneme.SaneReloadOptionsError:
# TODO
pass
try:
self.sane_device.options['resolution'].value = int(self.resolution)
except saneme.SaneReloadOptionsError:
# TODO
pass
self.log.debug('Beginning scan.')
pil_image = None
pil_image = self.sane_device.scan(self.progress_callback)
if self.cancel_event.isSet():
self.emit("failed", "Scan cancelled")
else:
if not pil_image:
raise AssertionError('sane_device.scan() returned None')
self.emit('succeeded', pil_image)
class UpdateScannerOptionsThread(IdleObject, threading.Thread):
"""
Responsible for getting an up-to-date list of valid scanner options
and passing it back to the main thread.
"""
__gsignals__ = {
'finished': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
'aborted': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane_device):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.log.debug('Created.')
@abort_on_exception
def run(self):
"""
Queries SANE for a list of available options for the specified scanner.
"""
assert self.sane_device.is_open()
self.log.debug('Updating scanner options.')
mode_list = self.sane_device.options['mode'].constraint
resolution_list = [str(i) for i in self.sane_device.options['resolution'].constraint]
# NB: We callback with the lists so that they can updated on the main thread
self.emit('finished', mode_list, resolution_list)
\ No newline at end of file
|
onyxfish/nostaples
|
454b3365531dee965f3f8a90da1186eb36ede9a0
|
Reimplemented SaneDeviceInval exception.
|
diff --git a/sane/errors.py b/sane/errors.py
index 3fbf365..029a9b2 100644
--- a/sane/errors.py
+++ b/sane/errors.py
@@ -1,135 +1,144 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Python exceptions which take the place
of SANE's status codes in the Pythonic reimplementation of the API.
These are the errors that users will need to handle.
"""
class SaneError(Exception):
"""
Base class for all SANE Errors.
"""
pass
class SaneUnknownError(SaneError):
"""
Exception denoting an error within the SANE library that could
not be categorized.
"""
pass
class SaneNoSuchDeviceError(SaneError):
"""
Exception denoting that a device requested by name did not
exist.
"""
pass
class SaneUnsupportedOperationError(SaneError):
"""
Exception denoting an unsupported operation was requested.
Corresponds to SANE status code SANE_STATUS_UNSUPPORTED.
"""
pass
class SaneDeviceBusyError(SaneError):
"""
Exception denoting that the requested device is being
accessed by another process.
Corresponds to SANE status code SANE_STATUS_DEVICE_BUSY.
"""
pass
+
+class SaneInvalidParameterError(SaneError):
+ """
+ Exception denoting that SANE received an invalid parameter
+ to a function call.
+ Corresponds to SANE status code SANE_STATUS_INVAL.
+ """
+ pass
+
class SaneInvalidDataError(SaneError):
"""
Exception denoting that some data or argument was not
valid.
Corresponds to SANE status code SANE_STATUS_INVAL.
"""
pass
class SaneEndOfFileError(SaneError):
"""
TODO: Should the user ever see this? probably handled internally
Corresponds to SANE status code SANE_STATUS_EOF.
"""
pass
class SaneDeviceJammedError(SaneError):
"""
Exception denoting that the device is jammed.
Corresponds to SANE status code SANE_STATUS_JAMMED.
"""
pass
class SaneNoDocumentsError(SaneError):
"""
Exception denoting that there are pages in the document
feeder of the device.
Corresponds to SANE status code SANE_STATUS_NO_DOCS.
"""
pass
class SaneCoverOpenError(SaneError):
"""
Exception denoting that the cover of the device is open.
Corresponds to SANE status code SANE_STATUS_COVER_OPEN.
"""
pass
class SaneIOError(SaneError):
"""
Exception denoting that an IO error occurred while
communicating wtih the device.
Corresponds to the SANE status code SANE_STATUS_IO_ERROR.
"""
pass
class SaneOutOfMemoryError(SaneError):
"""
Exception denoting that SANE ran out of memory during an
operation.
Corresponds to the SANE status code SANE_STATUS_NO_MEM.
"""
pass
class SaneAccessDeniedError(SaneError):
"""
TODO: should this be handled in a special way?
Corresponds to the SANE status code SANE_STATUS_ACCESS_DENIED.
"""
pass
class SaneReloadOptionsError(SaneError):
"""
Exception denoting that a change to a SANE option has had
a cascade effect on other options and thus that they should
be read again to get the most up to date values.
"""
pass
\ No newline at end of file
diff --git a/sane/saneme.py b/sane/saneme.py
index 637d091..52b2bf3 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,879 +1,883 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method,
# including those that could bubble up
from array import *
import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the application
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SaneMe(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object, perform setup, and register
the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
self._setup()
atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
"""
version_code = SANE_Int()
auth_callback = SANE_Auth_Callback(self._sane_auth_callback)
status = sane_init(byref(version_code), auth_callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def _sane_auth_callback(self, resource, username, password):
"""
TODO
"""
raise NotImplementedError(
'sane_auth_callback requested, but not yet implemented.')
def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. To
ensure this method is called it is registered with atexit.
"""
for device in self._devices:
if device.is_open():
device.close()
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
# Public Methods
def get_device_list(self):
"""
Poll for connected devices. This method may take several
seconds to return.
Note that SANE is exited and re-inited before querying for
devices to workaround a limitation in SANE's USB driver
which causes the device list to only be updated on init.
This means that all settings applied to all devices will be
B{lost} and must be restored by the calling application.
This was found documented here:
U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html}
"""
if not self._version:
raise AssertionError('version was None')
# See docstring for details on this voodoo
self._shutdown()
self._setup()
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
return self._devices
def get_device_by_name(self, name):
"""
Retrieve a L{Device} by name.
Must be preceded by a call to L{get_device_list}.
"""
for device in self._devices:
if device.name == name:
return device
raise SaneNoSuchDeviceError()
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_display_name = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
if type(ctypes_device.name) is not StringType:
raise AssertionError('device name was not of StringType')
if type(ctypes_device.vendor) is not StringType:
raise AssertionError('device vendor was not of StringType')
if type(ctypes_device.model) is not StringType:
raise AssertionError('device model was not of StringType')
if type(ctypes_device.type) is not StringType:
raise AssertionError('device type was not of StringType')
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
self._display_name = ' '.join([self._vendor, self._model])
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_display_name(self):
"""
Get an appropriate name to use for displaying this device
to a user, e.g. 'Lexmark X1100/rev. B2'."""
return self._display_name
display_name = property(__get_display_name)
def __get_options(self):
"""Get the dictionary of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
raise SaneUnsupportedOperationError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
if self._handle:
raise AssertionError('device handle already exists.')
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
+ # If and exception will be thrown, nullify device handle
+ # so is_open() will return false for the device.
+ if status != SANE_STATUS_GOOD.value:
+ self._handle = None
+
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
- # TODO - invalid device name? disconnected?
- raise AssertionError(
+ raise SaneInvalidParameterError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
TODO: handle ADF scans
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
if not self._handle:
raise AssertionError('device handle was None.')
if self._handle == c_void_p(None):
raise AssertionError('device handle was a null pointer.')
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
# This is the size used for the scan buffer in SANE's scanimage
# utility. The precise reasoning for using 32kb is unclear.
bytes_per_read = 32768
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
cancel = False
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
return None
if cancel:
raise AssertionError('cancel was true after scan completed.')
sane_cancel(self._handle)
if scan_info.total_bytes != len(data_array):
raise AssertionError('length of scanned data did not match expected length.')
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'RGB', 0, 1)
else:
# TODO
raise NotImplementedError(
'Individual color frame scanned, but not yet supported.')
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint = None
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
if type(ctypes_option.name) is not StringType:
raise AssertionError('option name was not of StringType.')
if type(ctypes_option.title) is not StringType:
raise AssertionError('option title was not of StringType.')
if type(ctypes_option.desc) is not StringType:
raise AssertionError('option description was not of StringType.')
if type(ctypes_option.type) is not IntType:
raise AssertionError('option type was not of IntType.')
if type(ctypes_option.unit) is not IntType:
raise AssertionError('option unit was not of IntType.')
if type(ctypes_option.size) is not IntType:
raise AssertionError('option size was not of IntType.')
if type(ctypes_option.cap) is not IntType:
raise AssertionError('option capabilities was not of IntType.')
if type(ctypes_option.constraint_type) is not IntType:
raise AssertionError('option constraint_type was not of IntType.')
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
if type(ctypes_option.constraint.range) is not POINTER(SANE_Range):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_Range.')
if type(ctypes_option.constraint.range.contents.min) is not IntType:
raise AssertionError('option\'s constraint range min was not of IntType.')
if type(ctypes_option.constraint.range.contents.max) is not IntType:
raise AssertionError('option\'s constraint range max was not of IntType.')
if type(ctypes_option.constraint.range.contents.quant) is not IntType:
raise AssertionError('option\'s constraint range quant was not of IntType.')
self._constraint = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
if type(ctypes_option.constraint.word_list) is not POINTER(SANE_Word):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_Word.')
word_count = ctypes_option.constraint.word_list[0]
self._constraint = []
i = 1
while(i < word_count):
self._constraint.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
if type(ctypes_option.constraint.string_list) is not POINTER(SANE_String_Const):
raise AssertionError('option\'s constraint range was not a pointer to a SANE_String_Const.')
string_count = 0
self._constraint = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
return self._type
type = property(__get_type)
def __get_unit(self):
return self._unit
unit = property(__get_unit)
def __get_capability(self):
# TODO: break out into individual capabilities, rather than a bitset
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint(self):
"""
Get the constraint for this option.
If constraint_type is OPTION_CONSTRAINT_RANGE then
this is a tuple containing the (minimum, maximum, step)
for valid values.
If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then
this is a list of integers which are valid values.
If constraint_type is OPTION_CONSTRAINT_STRING_LIST then
this is a list of strings which are valid values.
"""
return self._constraint
constraint = property(__get_constraint)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# Constraint checking ensures this should never happen
raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported a value was invalid, but no values was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
if type(value) is not BooleanType:
raise AssertionError('option expected BooleanType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
if type(value) is not IntType:
raise AssertionError('option expected IntType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
if type(value) is not IntType:
raise AssertionError('option expected IntType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
if type(value) is not StringType:
raise AssertionError('option expected StringType')
if len(value) + 1 > self._size:
raise AssertionError('value for option is longer than max string size')
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
if value < self._constraint[0]:
raise AssertionError('value for option is less than min.')
if value > self._constraint[1]:
raise AssertionError('value for option is greater than max.')
if value % self._constraint[2] != 0:
raise AssertionError('value for option is not divisible by quant.')
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
if value not in self._constraint:
raise AssertionError('value for option not in list of valid values.')
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
if value not in self._constraint:
raise AssertionError('value for option not in list of valid strings.')
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# Constraint checking ensures this should never happen
raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
|
onyxfish/nostaples
|
065f2131ba745e8de1d6dc8c324a1d53308da097
|
Overhauled the way exceptions are handled across threads.
|
diff --git a/application.py b/application.py
index 8c871f8..699b616 100644
--- a/application.py
+++ b/application.py
@@ -1,335 +1,334 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds NoStaples' main method which handles
the instantiation of MVC objects and then starts the gtk
main loop.
"""
import logging.config
import os
import gtk
from nostaples import constants
from nostaples.controllers.about import AboutController
from nostaples.controllers.document import DocumentController
from nostaples.controllers.main import MainController
from nostaples.controllers.page import PageController
from nostaples.controllers.preferences import PreferencesController
from nostaples.controllers.save import SaveController
from nostaples.controllers.status import StatusController
from nostaples.models.document import DocumentModel
from nostaples.models.main import MainModel
from nostaples.models.page import PageModel
from nostaples.models.preferences import PreferencesModel
from nostaples.models.save import SaveModel
from nostaples.models.status import StatusModel
import nostaples.utils.gtkexcepthook
from nostaples.utils.state import GConfStateManager
from nostaples.views.about import AboutView
from nostaples.views.document import DocumentView
from nostaples.views.main import MainView
from nostaples.views.page import PageView
from nostaples.views.preferences import PreferencesView
from nostaples.views.save import SaveView
from nostaples.views.status import StatusView
from saneme import SaneMe
class Application(object):
"""
A 'front controller' class that stores references to all
top-level components of the application and facilitates
communication between them.
A reference to this class is injected into each controller
component of the application via its constructor. These
components then query the application object when they
need to access other parts of the system.
"""
_state_manager = None
_sane = None
_main_model = None
_main_controller = None
_main_view = None
_document_model = None
_document_controller = None
_document_view = None
_null_page_model = None
_page_controller = None
_page_view = None
_status_model = None
_status_controller = None
_status_view = None
_preferences_model = None
_preferences_controller = None
_preferences_view = None
_save_model = None
_save_controller = None
_save_view = None
_about_controller = None
_about_view = None
def __init__(self):
"""
Set up the config directory, logging, and state
persistence. Construct the Main MVC component triplet
(which will in turn construct all sub components).
Per
"""
self._init_config()
self._init_logging()
self._init_state()
self._init_sane()
self._init_main_components()
self._init_settings()
def _init_config(self):
"""Setup the config directory."""
if not os.path.exists(constants.TEMP_IMAGES_DIRECTORY):
os.mkdir(constants.TEMP_IMAGES_DIRECTORY)
def _init_logging(self):
"""Setup logging for the application."""
logging.config.fileConfig(constants.LOGGING_CONFIG)
def _init_state(self):
"""Setup the state manager."""
self._state_manager = GConfStateManager()
def _init_sane(self):
"""Setup SANE."""
self._sane = SaneMe(logging.getLogger("saneme"))
def _init_main_components(self):
"""
Create the main application components, which will
request creation of other components as necessary.
"""
self._main_model = MainModel(self)
self._main_controller = MainController(self)
self._main_view = MainView(self)
def _init_settings(self):
"""
Load current settings from the state manager and
poll for available scanners.
"""
self._main_model.load_state()
self.get_save_model().load_state()
self.get_preferences_model().load_state()
self._main_controller._update_available_scanners()
# PUBLIC METHODS
def run(self):
"""Execute the GTK main loop."""
assert isinstance(self._main_view, MainView)
self._main_view.show()
- gtk.gdk.threads_init()
gtk.main()
def get_state_manager(self):
"""Return the L{GConfStateManager} component."""
assert isinstance(self._state_manager, GConfStateManager)
return self._state_manager
def get_sane(self):
"""Return the SaneMe object."""
assert isinstance(self._sane, SaneMe)
return self._sane
def get_main_model(self):
"""Return the L{MainModel} component."""
assert self._main_model
return self._main_model
def get_main_controller(self):
"""Return the L{MainController} component."""
assert self._main_controller
return self._main_controller
def get_main_view(self):
"""Return the L{MainView} component."""
assert self._main_view
return self._main_view
def get_document_model(self):
"""Return the L{DocumentModel} component."""
if not self._document_model:
self._document_model = DocumentModel(self)
return self._document_model
def get_document_controller(self):
"""Return the L{DocumentController} component."""
if not self._document_controller:
self._document_controller = DocumentController(self)
return self._document_controller
def get_document_view(self):
"""Return the L{DocumentView} component."""
if not self._document_view:
self._document_view = DocumentView(self)
return self._document_view
def get_null_page_model(self):
"""
Return an empty L{PageModel} object.
This is the PageModel that is used when no
pages have been scanned.
"""
if not self._null_page_model:
self._null_page_model = PageModel(self)
return self._null_page_model
def get_current_page_model(self):
"""
Return the current/active L{PageModel} object.
This is a convenience function.
"""
return self.get_page_controller().get_current_page_model()
def get_page_controller(self):
"""Return the L{PageController} component."""
if not self._page_controller:
self._page_controller = PageController(self)
return self._page_controller
def get_page_view(self):
"""Return the L{PageView} component."""
if not self._page_view:
self._page_view = PageView(self)
return self._page_view
def get_status_model(self):
"""Return the L{StatusModel} component."""
if not self._status_model:
self._status_model = StatusModel(self)
return self._status_model
def get_status_controller(self):
"""Return the L{StatusController} component."""
if not self._status_controller:
self._status_controller = StatusController(self)
return self._status_controller
def get_status_view(self):
"""Return the L{StatusView} component."""
if not self._status_view:
self._status_view = StatusView(self)
return self._status_view
def get_preferences_model(self):
"""Return the L{PreferencesModel} component."""
if not self._preferences_model:
self._preferences_model = PreferencesModel(self)
return self._preferences_model
def get_preferences_controller(self):
"""Return the L{PreferencesController} component."""
if not self._preferences_controller:
self._preferences_controller = PreferencesController(self)
return self._preferences_controller
def get_preferences_view(self):
"""Return the L{PreferencesView} component."""
if not self._preferences_view:
self._preferences_view = PreferencesView(self)
return self._preferences_view
def show_preferences_dialog(self):
"""
Show the preferences dialog.
This is a convenience function.
"""
self.get_preferences_controller().run()
def get_save_model(self):
"""Return the L{SaveModel} component."""
if not self._save_model:
self._save_model = SaveModel(self)
return self._save_model
def get_save_controller(self):
"""Return the L{SaveController} component."""
if not self._save_controller:
self._save_controller = SaveController(self)
return self._save_controller
def get_save_view(self):
"""Return the L{SaveView} component."""
if not self._save_view:
self._save_view = SaveView(self)
return self._save_view
def show_save_dialog(self):
"""
Show the save dialog.
This is a convenience function.
"""
self.get_save_controller().run()
def get_about_controller(self):
"""Return the L{SaveController} component."""
if not self._about_controller:
self._about_controller = AboutController(self)
return self._about_controller
def get_about_view(self):
"""Return the L{SaveView} component."""
if not self._about_view:
self._about_view = AboutView(self)
return self._about_view
def show_about_dialog(self):
"""
Show the about dialog.
This is a convenience function.
"""
self.get_about_controller().run()
diff --git a/controllers/main.py b/controllers/main.py
index e4e0416..09a84ba 100644
--- a/controllers/main.py
+++ b/controllers/main.py
@@ -1,706 +1,787 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the L{MainController}, which manages interaction
between the L{MainModel} and L{MainView}.
"""
import commands
import logging
import os
import re
import threading
import gobject
import gtk
from gtkmvc.controller import Controller
from nostaples.models.page import PageModel
from nostaples.utils.scanning import *
+import saneme
class MainController(Controller):
"""
Manages interaction between the L{MainModel} and L{MainView}.
"""
# SETUP METHODS
def __init__(self, application):
"""
Constructs the MainController, as well as necessary sub-controllers
and services.
"""
self.application = application
Controller.__init__(self, application.get_main_model())
application.get_document_model().register_observer(self)
status_controller = application.get_status_controller()
self.status_context = \
status_controller.get_context_id(self.__class__.__name__)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def register_view(self, view):
"""
Registers this controller with a view.
"""
Controller.register_view(self, view)
self.log.debug('%s registered.', view.__class__.__name__)
def register_adapters(self):
"""
Registers adapters for property/widget pairs that do not require
complex processing.
"""
self.adapt('show_toolbar', 'show_toolbar_menu_item')
self.adapt('show_statusbar', 'show_statusbar_menu_item')
self.adapt('show_thumbnails', 'show_thumbnails_menu_item')
self.adapt('show_adjustments', 'show_adjustments_menu_item')
self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item')
self.log.debug('Adapters registered.')
# USER INTERFACE CALLBACKS
# Menu Items
def on_scan_window_destroy(self, window):
"""Exits the application."""
self.quit()
def on_scan_menu_item_activate(self, menu_item):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_menu_item_activate(self, menu_item):
"""Refresh the list of connected scanners from SANE."""
self._update_available_scanners()
def on_save_as_menu_item_activate(self, menu_item):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_delete_menu_item_activate(self, menu_item):
self.application.get_document_controller().delete_selected()
def on_preferences_menu_item_activate(self, menu_item):
"""Creates and displays a preferences dialog."""
self.application.show_preferences_dialog()
def on_quit_menu_item_activate(self, menu_item):
"""Exits the application."""
self.quit()
def on_zoom_in_menu_item_activate(self, menu_item):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_menu_item_activate(self, menu_item):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_menu_item_activate(self, menu_item):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_menu_item_activate(self, menu_item):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_available_scanner_menu_item_toggled(self, menu_item):
"""
Set the active scanner.
TODO: Need a second scanner to properly test this...
"""
main_model = self.application.get_main_model()
if menu_item.get_active():
for scanner in main_model.available_scanners:
if scanner.display_name == menu_item.get_children()[0].get_text():
main_model.active_scanner = scanner
return
def on_valid_mode_menu_item_toggled(self, menu_item):
"""Sets the active scan mode."""
if menu_item.get_active():
self.application.get_main_model().active_mode = \
menu_item.get_children()[0].get_text()
def on_valid_resolution_menu_item_toggled(self, menu_item):
"""Sets the active scan resolution."""
if menu_item.get_active():
self.application.get_main_model().active_resolution = \
menu_item.get_children()[0].get_text()
def on_go_first_menu_item_activate(self, menu_item):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_menu_item_activate(self, menu_item):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_menu_item_activate(self, menu_item):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_menu_item_activate(self, menu_item):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
def on_contents_menu_item_clicked(self, menu_item):
"""TODO"""
pass
def on_about_menu_item_activate(self, menu_item):
"""Show the about dialog."""
self.application.show_about_dialog()
# Toolbar Buttons
def on_scan_button_clicked(self, button):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_button_clicked(self, button):
self._update_available_scanners()
def on_save_as_button_clicked(self, button):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_zoom_in_button_clicked(self, button):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_button_clicked(self, button):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_button_clicked(self, button):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_button_clicked(self, button):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_go_first_button_clicked(self, button):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_button_clicked(self, button):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_button_clicked(self, button):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_button_clicked(self, button):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
# Progress Window INTERFACE CALLBACKS
def on_progress_window_delete_event(self, window, event):
"""
Emulate clicking of the cancel/close button and then
hide the window.
"""
main_view = self.application.get_main_view()
self.on_scan_cancel_button_clicked(None)
main_view['progress_window'].hide()
return True
def on_scan_cancel_button_clicked(self, button):
"""
Cancel the current scan or, if the scan is finished,
close the progress window.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress:
assert self.cancel_event
self.cancel_event.set()
else:
main_view['progress_window'].hide()
def on_scan_again_button_clicked(self, button):
"""Initiate a new scan from the progress window."""
self._scan()
def on_quick_save_button_clicked(self, button):
"""
Show the save dialog. If the user completes a save
then disable the quick save button until another
page is scanned.
"""
main_view = self.application.get_main_view()
document_model = self.application.get_document_model()
self.application.show_save_dialog()
if document_model.count == 0:
main_view['quick_save_button'].set_sensitive(False)
# MainModel PROPERTY CALLBACKS
def property_show_toolbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the toolbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_toolbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['main_toolbar'].show()
else:
main_view['main_toolbar'].hide()
def property_show_statusbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the statusbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_statusbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['status_view_docking_viewport'].show()
else:
main_view['status_view_docking_viewport'].hide()
def property_show_thumbnails_value_change(self, model, old_value, new_value):
"""Update the visibility of the thumbnails."""
main_view = self.application.get_main_view()
menu_item = main_view['show_thumbnails_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_thumbnails_visible(new_value)
def property_show_adjustments_value_change(self, model, old_value, new_value):
"""Update the visibility of the adjustments controls."""
main_view = self.application.get_main_view()
menu_item = main_view['show_adjustments_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_adjustments_visible(new_value)
def property_active_scanner_value_change(self, model, old_value, new_value):
"""
Update the menu and valid scanner options to match the new device.
"""
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
for menu_item in main_view['scanner_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value.display_name:
menu_item.set_active(True)
break
self._update_scanner_options()
def property_active_mode_value_change(self, model, old_value, new_value):
"""Select the active mode from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_mode_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_active_resolution_value_change(self, model, old_value, new_value):
"""Select the active resolution from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_resolution_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_available_scanners_value_change(self, model, old_value, new_value):
"""
Update the menu of available scanners.
"""
main_view = self.application.get_main_view()
self._clear_available_scanners_sub_menu()
# Generate the new menu
if len(new_value) == 0:
menu_item = gtk.MenuItem('No Scanners Connected')
menu_item.set_sensitive(False)
main_view['scanner_sub_menu'].append(menu_item)
else:
first_item = None
for i in range(len(new_value)):
# The first menu item defines the group
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i].display_name)
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i].display_name)
main_view['scanner_sub_menu'].append(menu_item)
main_view['scanner_sub_menu'].show_all()
def property_valid_modes_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan modes for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_modes_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Modes")
menu_item.set_sensitive(False)
main_view['scan_mode_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled)
main_view['scan_mode_sub_menu'].append(menu_item)
main_view['scan_mode_sub_menu'].show_all()
def property_valid_resolutions_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan resolutions for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_resolutions_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Resolutions")
menu_item.set_sensitive(False)
main_view['scan_resolution_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled)
main_view['scan_resolution_sub_menu'].append(menu_item)
main_view['scan_resolution_sub_menu'].show_all()
def property_scan_in_progress_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_available_scanners_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_scan_options_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
# DocumentModel PROPERTY CALLBACKS
def property_count_value_change(self, model, old_value, new_value):
"""Toggle available controls."""
self._toggle_document_controls()
# THREAD CALLBACKS
def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned):
main_view = self.application.get_main_view()
short_bytes_scanned = float(bytes_scanned) / 1000
short_total_bytes = float(scan_info.total_bytes) / 1000
main_view['scan_progressbar'].set_fraction(
float(bytes_scanned) / scan_info.total_bytes)
main_view['scan_progressbar'].set_text(
'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes))
# TODO: multi page scans
main_view['progress_secondary_label'].set_markup(
'<i>Scanning page.</i>')
def on_scan_succeeded(self, scanning_thread, pil_image):
"""
Append the new page to the current document.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
main_view['scan_progressbar'].set_fraction(1)
main_view['scan_progressbar'].set_text('Scan complete')
main_view['progress_secondary_label'].set_markup(
'<i>Adding page to document.</i>')
gtk.gdk.flush()
new_page = PageModel(self.application, pil_image, int(main_model.active_resolution))
self.application.get_document_model().append(new_page)
main_view['progress_secondary_label'].set_markup(
'<i>Page added.</i>')
main_view['scan_again_button'].set_sensitive(True)
main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
def on_scan_failed(self, scanning_thread, reason):
"""
Set that scan is complete.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
-
- #main_view['scan_progressbar'].set_fraction(0)
- #main_view['scan_progressbar'].set_text('No data')
+
main_view['progress_secondary_label'].set_markup(
'<i>%s</i>' % reason)
main_view['scan_again_button'].set_sensitive(True)
- main_view['quick_save_button'].set_sensitive(True)
+ if self.application.get_document_model().count > 0:
+ main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
+ def on_scan_aborted(self, scanning_thread, e):
+ """
+ Change display to indicate that scanning failed and
+ convey the to the user the reason why the thread aborted.
+
+ If the failure was from a SANE exception then give the
+ user the option to blacklist the device. If not, then
+ reraise the error and let the sys.excepthook deal with it.
+ """
+ self.on_scan_failed(scanning_thread, 'An error occurred.')
+
+ if isinstance(e, saneme.SaneError):
+ self.display_device_exception_dialog(e)
+ else:
+ raise e
+
def on_update_available_scanners_thread_finished(self, update_thread, scanner_list):
"""Set the new list of available scanners."""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.available_scanners = scanner_list
main_model.updating_available_scanners = False
+
+ def on_update_available_scanners_thread_aborted(self, update_thread, e):
+ """
+ Change the display to indicate that no scanners are available and
+ reraise the exception so that it can be caught by the sys.excepthook.
+
+ There is no reason to handle these cases with a special dialog,
+ if the application failed to even enumerate the available devices then
+ no other action will be possible.
+
+ This should be fantastically rare.
+ """
+ self.on_update_available_scanners_thread_finished(update_thread, [])
+ raise e
def on_update_scanner_options_thread_finished(self, update_thread, mode_list, resolution_list):
"""
Update the mode and resolution lists and rark that
the scanner is no longer in use.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.valid_modes = mode_list
main_model.valid_resolutions = resolution_list
main_model.updating_scan_options = False
+ def on_update_scanner_options_thread_aborted(self, update_thread, e):
+ """
+ Change display to indicate that updating the options failed and
+ convey the to the user the reason why the thread aborted.
+
+ If the failure was from a SANE exception then give the
+ user the option to blacklist the device. If not, then
+ reraise the error and let the sys.excepthook deal with it.
+ """
+ # TODO: If this fails the scanner icon will still stay lit,
+ # and when the user clicks it the app will error again since it
+ # will not have a valid mode/resolution.
+ self.on_update_scanner_options_thread_finished(update_thread, [], [])
+
+ if isinstance(e, saneme.SaneError):
+ self.display_device_exception_dialog(e)
+ else:
+ raise e
+
# PUBLIC METHODS
def quit(self):
"""Exits the application."""
self.log.debug('Quit.')
gtk.main_quit()
# PRIVATE METHODS
def _clear_available_scanners_sub_menu(self):
"""Clear the menu of available scanners."""
main_view = self.application.get_main_view()
for child in main_view['scanner_sub_menu'].get_children():
main_view['scanner_sub_menu'].remove(child)
def _clear_scan_modes_sub_menu(self):
"""Clear the menu of valid scan modes."""
main_view = self.application.get_main_view()
for child in main_view['scan_mode_sub_menu'].get_children():
main_view['scan_mode_sub_menu'].remove(child)
def _clear_scan_resolutions_sub_menu(self):
"""Clear the menu of valid scan resolutions."""
main_view = self.application.get_main_view()
for child in main_view['scan_resolution_sub_menu'].get_children():
main_view['scan_resolution_sub_menu'].remove(child)
def _toggle_scan_controls(self):
"""Toggle whether or not the scan controls or accessible."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_scan_controls_sensitive(False)
main_view.set_refresh_scanner_controls_sensitive(False)
else:
if main_model.active_scanner != None:
main_view.set_scan_controls_sensitive(True)
main_view.set_refresh_scanner_controls_sensitive(True)
def _toggle_document_controls(self):
"""
Toggle available document controls based on the current scanner
status and the number of scanned pages.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
# Disable all controls when the scanner is in use
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
count = self.application.get_document_model().count
# Disable all controls if no pages are scanned
if count == 0:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
# Enable most controls if any pages scanned
main_view.set_file_controls_sensitive(True)
main_view.set_delete_controls_sensitive(True)
main_view.set_zoom_controls_sensitive(True)
main_view.set_adjustment_controls_sensitive(True)
# Only enable navigation if more than one page scanned
if count > 1:
main_view.set_navigation_controls_sensitive(True)
else:
main_view.set_navigation_controls_sensitive(False)
def _update_status(self):
"""
Update the text of the statusbar based on the current state
of the application.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
status_controller.pop(self.status_context)
if main_model.scan_in_progress:
status_controller.push(self.status_context, 'Scanning...')
elif main_model.updating_available_scanners:
status_controller.push(self.status_context, 'Querying hardware...')
elif main_model.updating_scan_options:
status_controller.push(self.status_context, 'Querying options...')
else:
if main_model.active_scanner:
status_controller.push(self.status_context,
'Ready with %s.' % main_model.active_scanner.display_name)
else:
status_controller.push(self.status_context, 'No scanner available.')
def _scan(self):
"""Begin a scan."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
main_model.scan_in_progress = True
scanning_thread = ScanningThread(
main_model.active_scanner, main_model.active_mode, main_model.active_resolution)
scanning_thread.connect("progress", self.on_scan_progress)
scanning_thread.connect("succeeded", self.on_scan_succeeded)
scanning_thread.connect("failed", self.on_scan_failed)
+ scanning_thread.connect("aborted", self.on_scan_aborted)
self.cancel_event = scanning_thread.cancel_event
main_view['progress_primary_label'].set_markup(
'<big><b>%s</b></big>' % main_model.active_scanner.display_name)
main_view['scan_progressbar'].set_fraction(0)
main_view['scan_progressbar'].set_text('Waiting for data')
main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>')
- main_view['progress_mode_label'].set_markup(main_model.active_mode)
- main_view['progress_resolution_label'].set_markup('%s DPI' % main_model.active_resolution)
+ mode = main_model.active_mode if main_model.active_mode else 'Not set'
+ main_view['progress_mode_label'].set_markup(mode)
+ dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set'
+ main_view['progress_resolution_label'].set_markup(dpi)
main_view['scan_again_button'].set_sensitive(False)
main_view['quick_save_button'].set_sensitive(False)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL)
main_view['progress_window'].show_all()
scanning_thread.start()
def _update_available_scanners(self):
"""
Start a new update thread to query for available scanners.
"""
sane = self.application.get_sane()
main_model = self.application.get_main_model()
main_model.updating_available_scanners = True
update_thread = UpdateAvailableScannersThread(sane)
update_thread.connect("finished", self.on_update_available_scanners_thread_finished)
+ update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted)
update_thread.start()
def _update_scanner_options(self):
"""Determine the valid options for the current scanner."""
main_model = self.application.get_main_model()
main_model.updating_scan_options = True
update_thread = UpdateScannerOptionsThread(main_model.active_scanner)
update_thread.connect("finished", self.on_update_scanner_options_thread_finished)
- update_thread.start()
\ No newline at end of file
+ update_thread.connect("aborted", self.on_update_scanner_options_thread_aborted)
+ update_thread.start()
+
+ def display_device_exception_dialog(self, exception):
+ """
+ Display an error dialog that provides the user with the option of
+ blacklisting the device which caused the error.
+ """
+ dialog = gtk.MessageDialog(
+ parent=None, flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_NONE)
+ dialog.set_title("")
+
+ # TODO: is this needed?
+ if gtk.check_version (2, 4, 0) is not None:
+ dialog.set_has_separator (False)
+
+ primary = "<big><b>A hardware exception has been logged.</b></big>"
+ secondary = '%s\n\n%s' % (exception.message, 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.')
+
+ dialog.set_markup(primary)
+ dialog.format_secondary_markup(secondary)
+
+ dialog.add_button('Blacklist Device', 1)
+ dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
+
+ response = dialog.run()
+ dialog.destroy()
+
+ # TODO: handle blacklisting
\ No newline at end of file
diff --git a/gui/page_view.glade b/gui/page_view.glade
index 1373192..e3b2db6 100644
--- a/gui/page_view.glade
+++ b/gui/page_view.glade
@@ -1,63 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--Generated with glade3 3.4.5 on Thu Jan 22 20:33:06 2009 -->
+<!--Generated with glade3 3.4.5 on Mon Feb 16 21:48:04 2009 -->
<glade-interface>
<widget class="GtkWindow" id="dummy_page_view_window">
<child>
<widget class="GtkTable" id="page_view_table">
<property name="visible">True</property>
<property name="n_rows">2</property>
<property name="n_columns">2</property>
<child>
<placeholder/>
</child>
+ <child>
+ <widget class="GtkVScrollbar" id="page_view_vertical_scrollbar">
+ <property name="no_show_all">True</property>
+ <property name="adjustment">0 0 100 1 10 10</property>
+ </widget>
+ <packing>
+ <property name="left_attach">1</property>
+ <property name="right_attach">2</property>
+ <property name="x_options">GTK_SHRINK | GTK_FILL</property>
+ <property name="y_options">GTK_SHRINK | GTK_FILL</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkHScrollbar" id="page_view_horizontal_scrollbar">
+ <property name="no_show_all">True</property>
+ <property name="adjustment">10 0 100 1 10 10</property>
+ </widget>
+ <packing>
+ <property name="top_attach">1</property>
+ <property name="bottom_attach">2</property>
+ <property name="x_options">GTK_SHRINK | GTK_FILL</property>
+ <property name="y_options">GTK_SHRINK | GTK_FILL</property>
+ </packing>
+ </child>
<child>
<widget class="GtkLayout" id="page_view_image_layout">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_STRUCTURE_MASK | GDK_SCROLL_MASK</property>
<signal name="button_press_event" handler="on_page_view_image_layout_button_press_event"/>
<signal name="motion_notify_event" handler="on_page_view_image_layout_motion_notify_event"/>
<signal name="button_release_event" handler="on_page_view_image_layout_button_release_event"/>
<signal name="size_request" handler="on_page_view_image_layout_size_request"/>
<signal name="size_allocate" handler="on_page_view_image_layout_size_allocate"/>
<signal name="scroll_event" handler="on_page_view_image_layout_scroll_event"/>
<child>
<widget class="GtkImage" id="page_view_image">
<property name="visible">True</property>
<property name="stock">gtk-missing-image</property>
</widget>
<packing>
<property name="x">61</property>
<property name="y">32</property>
</packing>
</child>
</widget>
</child>
- <child>
- <widget class="GtkHScrollbar" id="page_view_horizontal_scrollbar">
- <property name="no_show_all">True</property>
- <property name="adjustment">10 0 100 1 10 10</property>
- </widget>
- <packing>
- <property name="top_attach">1</property>
- <property name="bottom_attach">2</property>
- <property name="x_options">GTK_SHRINK | GTK_FILL</property>
- <property name="y_options">GTK_SHRINK | GTK_FILL</property>
- </packing>
- </child>
- <child>
- <widget class="GtkVScrollbar" id="page_view_vertical_scrollbar">
- <property name="no_show_all">True</property>
- <property name="adjustment">0 0 100 1 10 10</property>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">2</property>
- <property name="x_options">GTK_SHRINK | GTK_FILL</property>
- <property name="y_options">GTK_SHRINK | GTK_FILL</property>
- </packing>
- </child>
</widget>
</child>
</widget>
</glade-interface>
diff --git a/gui/scan_window.glade b/gui/scan_window.glade
index bcb9d7e..ea9aa3a 100644
--- a/gui/scan_window.glade
+++ b/gui/scan_window.glade
@@ -1,913 +1,913 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--Generated with glade3 3.4.5 on Sun Feb 15 19:08:25 2009 -->
+<!--Generated with glade3 3.4.5 on Mon Feb 16 21:36:10 2009 -->
<glade-interface>
- <widget class="GtkWindow" id="scan_window">
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- <property name="title" translatable="yes">NoStaples</property>
+ <widget class="GtkWindow" id="progress_window">
+ <property name="width_request">400</property>
+ <property name="height_request">200</property>
+ <property name="title" translatable="yes">Scan in progress...</property>
+ <property name="resizable">False</property>
+ <property name="modal">True</property>
<property name="window_position">GTK_WIN_POS_CENTER</property>
- <property name="default_width">600</property>
- <property name="default_height">400</property>
- <signal name="destroy" handler="on_scan_window_destroy"/>
- <signal name="size_allocate" handler="on_scan_window_size_allocate"/>
+ <property name="destroy_with_parent">True</property>
+ <property name="icon_name">scanner</property>
+ <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property>
+ <property name="skip_taskbar_hint">True</property>
+ <property name="skip_pager_hint">True</property>
+ <property name="transient_for">scan_window</property>
+ <signal name="delete_event" handler="on_progress_window_delete_event"/>
<child>
- <widget class="GtkVBox" id="vbox1">
+ <widget class="GtkAlignment" id="alignment1">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="top_padding">12</property>
+ <property name="bottom_padding">12</property>
+ <property name="left_padding">12</property>
+ <property name="right_padding">12</property>
<child>
- <widget class="GtkMenuBar" id="menubar1">
+ <widget class="GtkVBox" id="vbox2">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="spacing">12</property>
<child>
- <widget class="GtkMenuItem" id="menuitem1">
+ <widget class="GtkVBox" id="vbox3">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- <property name="label" translatable="yes">_File</property>
- <property name="use_underline">True</property>
+ <property name="spacing">12</property>
<child>
- <widget class="GtkMenu" id="menu1">
+ <widget class="GtkLabel" id="progress_primary_label">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="xalign">0</property>
+ <property name="label" translatable="yes"><big><b>Scan in progress...</b></big></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkVBox" id="vbox4">
+ <property name="visible">True</property>
+ <property name="spacing">12</property>
<child>
- <widget class="GtkImageMenuItem" id="scan_menu_item">
+ <widget class="GtkVBox" id="vbox3">
<property name="visible">True</property>
- <property name="label" translatable="yes">S_can</property>
- <property name="use_underline">True</property>
- <signal name="activate" handler="on_scan_menu_item_activate"/>
- <child internal-child="image">
- <widget class="GtkImage" id="menu-item-image2">
+ <child>
+ <widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
- <property name="icon_name">scanner</property>
+ <property name="spacing">6</property>
+ <child>
+ <widget class="GtkLabel" id="static_mode_label">
+ <property name="width_request">90</property>
+ <property name="visible">True</property>
+ <property name="xalign">1</property>
+ <property name="label" translatable="yes"><b>Mode:</b></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="progress_mode_label">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Color</property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
</widget>
</child>
- </widget>
- </child>
- <child>
- <widget class="GtkImageMenuItem" id="refresh_available_scanners_menu_item">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Refresh Available Scanners</property>
- <property name="use_underline">True</property>
- <signal name="activate" handler="on_refresh_available_scanners_menu_item_activate"/>
- <child internal-child="image">
- <widget class="GtkImage" id="menu-item-image4">
- <property name="stock">gtk-refresh</property>
+ <child>
+ <widget class="GtkHBox" id="hbox5">
+ <property name="visible">True</property>
+ <property name="spacing">6</property>
+ <child>
+ <widget class="GtkLabel" id="static_page_size_label">
+ <property name="width_request">90</property>
+ <property name="visible">True</property>
+ <property name="xalign">1</property>
+ <property name="label" translatable="yes"><b>Page Size:</b></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="progress_page_size_label">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Letter (TODO)</property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkHBox" id="hbox3">
+ <property name="visible">True</property>
+ <property name="spacing">6</property>
+ <child>
+ <widget class="GtkLabel" id="static_resolution_label">
+ <property name="width_request">90</property>
+ <property name="visible">True</property>
+ <property name="xalign">1</property>
+ <property name="label" translatable="yes"><b>Resolution:</b></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="progress_resolution_label">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">150 DPI</property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
</widget>
+ <packing>
+ <property name="position">2</property>
+ </packing>
</child>
</widget>
</child>
<child>
- <widget class="GtkSeparatorMenuItem" id="separatormenuitem7">
- <property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- </widget>
- </child>
- <child>
- <widget class="GtkImageMenuItem" id="save_as_menu_item">
+ <widget class="GtkVBox" id="vbox4">
<property name="visible">True</property>
- <property name="label" translatable="yes">Save _As...</property>
- <property name="use_underline">True</property>
- <signal name="activate" handler="on_save_as_menu_item_activate"/>
- <accelerator key="S" modifiers="GDK_CONTROL_MASK" signal="activate"/>
- <child internal-child="image">
- <widget class="GtkImage" id="menu-item-image1">
- <property name="stock">gtk-save-as</property>
+ <child>
+ <widget class="GtkProgressBar" id="scan_progressbar">
+ <property name="visible">True</property>
+ <property name="show_text">True</property>
+ <property name="text" translatable="yes">X of Y bytes receieved.</property>
</widget>
+ <packing>
+ <property name="fill">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="progress_secondary_label">
+ <property name="visible">True</property>
+ <property name="xalign">0</property>
+ <property name="label" translatable="yes"><i>Scanning page 1 of Z.</i></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
</child>
</widget>
- </child>
- <child>
- <widget class="GtkSeparatorMenuItem" id="separatormenuitem1">
- <property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- </widget>
- </child>
- <child>
- <widget class="GtkImageMenuItem" id="quit_menu_item">
- <property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- <property name="label" translatable="yes">gtk-quit</property>
- <property name="use_underline">True</property>
- <property name="use_stock">True</property>
- <signal name="activate" handler="on_quit_menu_item_activate"/>
- </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
</child>
</widget>
+ <packing>
+ <property name="fill">False</property>
+ <property name="position">1</property>
+ </packing>
</child>
</widget>
</child>
<child>
- <widget class="GtkMenuItem" id="menuitem2">
+ <widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
- <property name="label" translatable="yes">_Edit</property>
- <property name="use_underline">True</property>
+ <property name="spacing">12</property>
<child>
- <widget class="GtkMenu" id="menu4">
+ <widget class="GtkButton" id="scan_cancel_button">
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <property name="label" translatable="yes">gtk-cancel</property>
+ <property name="use_stock">True</property>
+ <property name="response_id">0</property>
+ <signal name="clicked" handler="on_scan_cancel_button_clicked"/>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="pack_type">GTK_PACK_END</property>
+ <property name="position">2</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkButton" id="scan_again_button">
<property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <property name="response_id">0</property>
+ <signal name="clicked" handler="on_scan_again_button_clicked"/>
<child>
- <widget class="GtkImageMenuItem" id="delete_menu_item">
+ <widget class="GtkHBox" id="hbox4">
<property name="visible">True</property>
- <property name="label" translatable="yes">gtk-delete</property>
- <property name="use_underline">True</property>
- <property name="use_stock">True</property>
- <signal name="activate" handler="on_delete_menu_item_activate"/>
- <accelerator key="Delete" modifiers="" signal="activate"/>
- </widget>
- </child>
- <child>
+ <child>
+ <widget class="GtkImage" id="image1">
+ <property name="visible">True</property>
+ <property name="icon_name">scanner</property>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="label1">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Scan Again</property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="pack_type">GTK_PACK_END</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkButton" id="quick_save_button">
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <property name="response_id">0</property>
+ <signal name="clicked" handler="on_quick_save_button_clicked"/>
+ <child>
+ <widget class="GtkHBox" id="hbox6">
+ <property name="visible">True</property>
+ <child>
+ <widget class="GtkImage" id="image2">
+ <property name="visible">True</property>
+ <property name="stock">gtk-save-as</property>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="label2">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Quick Save</property>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="pack_type">GTK_PACK_END</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ <packing>
+ <property name="fill">False</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ <widget class="GtkWindow" id="scan_window">
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="title" translatable="yes">NoStaples</property>
+ <property name="window_position">GTK_WIN_POS_CENTER</property>
+ <property name="default_width">600</property>
+ <property name="default_height">400</property>
+ <signal name="destroy" handler="on_scan_window_destroy"/>
+ <signal name="size_allocate" handler="on_scan_window_size_allocate"/>
+ <child>
+ <widget class="GtkVBox" id="vbox1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <child>
+ <widget class="GtkMenuBar" id="menubar1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <child>
+ <widget class="GtkMenuItem" id="menuitem1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="label" translatable="yes">_File</property>
+ <property name="use_underline">True</property>
+ <child>
+ <widget class="GtkMenu" id="menu1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <child>
+ <widget class="GtkImageMenuItem" id="scan_menu_item">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">S_can</property>
+ <property name="use_underline">True</property>
+ <signal name="activate" handler="on_scan_menu_item_activate"/>
+ <child internal-child="image">
+ <widget class="GtkImage" id="menu-item-image2">
+ <property name="visible">True</property>
+ <property name="icon_name">scanner</property>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkImageMenuItem" id="refresh_available_scanners_menu_item">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Refresh Available Scanners</property>
+ <property name="use_underline">True</property>
+ <signal name="activate" handler="on_refresh_available_scanners_menu_item_activate"/>
+ <child internal-child="image">
+ <widget class="GtkImage" id="menu-item-image4">
+ <property name="stock">gtk-refresh</property>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkSeparatorMenuItem" id="separatormenuitem7">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkImageMenuItem" id="save_as_menu_item">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Save _As...</property>
+ <property name="use_underline">True</property>
+ <signal name="activate" handler="on_save_as_menu_item_activate"/>
+ <accelerator key="S" modifiers="GDK_CONTROL_MASK" signal="activate"/>
+ <child internal-child="image">
+ <widget class="GtkImage" id="menu-item-image1">
+ <property name="stock">gtk-save-as</property>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkSeparatorMenuItem" id="separatormenuitem1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkImageMenuItem" id="quit_menu_item">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="label" translatable="yes">gtk-quit</property>
+ <property name="use_underline">True</property>
+ <property name="use_stock">True</property>
+ <signal name="activate" handler="on_quit_menu_item_activate"/>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkMenuItem" id="menuitem2">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">_Edit</property>
+ <property name="use_underline">True</property>
+ <child>
+ <widget class="GtkMenu" id="menu4">
+ <property name="visible">True</property>
+ <child>
+ <widget class="GtkImageMenuItem" id="delete_menu_item">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">gtk-delete</property>
+ <property name="use_underline">True</property>
+ <property name="use_stock">True</property>
+ <signal name="activate" handler="on_delete_menu_item_activate"/>
+ <accelerator key="Delete" modifiers="" signal="activate"/>
+ </widget>
+ </child>
+ <child>
<widget class="GtkSeparatorMenuItem" id="separatormenuitem4">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="preferences_menu_item">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">gtk-preferences</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_preferences_menu_item_activate"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="view_menu">
<property name="visible">True</property>
<property name="label" translatable="yes">_View</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu2">
<property name="visible">True</property>
<child>
<widget class="GtkCheckMenuItem" id="show_toolbar_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Toolbar</property>
<property name="use_underline">True</property>
<property name="active">True</property>
<signal name="toggled" handler="on_show_toolbar_menu_item_toggled"/>
</widget>
</child>
<child>
<widget class="GtkCheckMenuItem" id="show_statusbar_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Statusbar</property>
<property name="use_underline">True</property>
<property name="active">True</property>
<signal name="toggled" handler="on_show_statusbar_menu_item_toggled"/>
</widget>
</child>
<child>
<widget class="GtkCheckMenuItem" id="show_thumbnails_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">Thumb_nails</property>
<property name="use_underline">True</property>
<property name="active">True</property>
<signal name="toggled" handler="on_show_thumbnails_menu_item_toggled"/>
</widget>
</child>
<child>
<widget class="GtkCheckMenuItem" id="show_adjustments_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Adjustments</property>
<property name="use_underline">True</property>
<signal name="toggled" handler="on_show_adjustments_menu_item_toggled"/>
</widget>
</child>
<child>
<widget class="GtkSeparatorMenuItem" id="separatormenuitem5">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="zoom_in_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-zoom-in</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_zoom_in_menu_item_activate"/>
<accelerator key="plus" modifiers="GDK_CONTROL_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="zoom_out_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-zoom-out</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_zoom_out_menu_item_activate"/>
<accelerator key="minus" modifiers="GDK_CONTROL_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="zoom_one_to_one_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-zoom-100</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_zoom_one_to_one_menu_item_activate"/>
<accelerator key="1" modifiers="GDK_CONTROL_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="zoom_best_fit_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-zoom-fit</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_zoom_best_fit_menu_item_activate"/>
<accelerator key="F" modifiers="GDK_CONTROL_MASK" signal="activate"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="menuitem9">
<property name="visible">True</property>
<property name="label" translatable="yes">_Tools</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu6">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="rotate_clockwise_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Rotate Clockwise</property>
<property name="use_underline">True</property>
<signal name="activate" handler="on_rotate_clockwise_menu_item_activate"/>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="rotate_counter_clockwise_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">Rotate _Counterclockwise</property>
<property name="use_underline">True</property>
<signal name="activate" handler="on_rotate_counter_clockwise_menu_item_activate"/>
</widget>
</child>
<child>
<widget class="GtkCheckMenuItem" id="rotate_all_pages_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">Apply rotation to all _pages?</property>
<property name="use_underline">True</property>
<signal name="toggled" handler="on_rotate_all_pages_menu_item_toggled"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="options_menu">
<property name="visible">True</property>
<property name="label" translatable="yes">_Options</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu7">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="scanner_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Scanner</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="scanner_sub_menu">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="menuitem5">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="label" translatable="yes">None</property>
<property name="use_underline">True</property>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="scan_mode_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Mode</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="scan_mode_sub_menu">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="menuitem8">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="label" translatable="yes">None</property>
<property name="use_underline">True</property>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="scan_resolution_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Resolution</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="scan_resolution_sub_menu">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="menuitem10">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="label" translatable="yes">None</property>
<property name="use_underline">True</property>
</widget>
</child>
</widget>
</child>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="menuitem3">
<property name="visible">True</property>
<property name="label" translatable="yes">_Go</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu5">
<property name="visible">True</property>
<child>
<widget class="GtkImageMenuItem" id="go_first_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-goto-first</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_go_first_menu_item_activate"/>
<accelerator key="Home" modifiers="" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="go_previous_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-go-back</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_go_previous_menu_item_activate"/>
<accelerator key="Left" modifiers="GDK_MOD1_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="go_next_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-go-forward</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_go_next_menu_item_activate"/>
<accelerator key="Right" modifiers="GDK_MOD1_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="go_last_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-goto-last</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_go_last_menu_item_activate"/>
<accelerator key="End" modifiers="" signal="activate"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="menuitem4">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">_Help</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu3">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<child>
<widget class="GtkImageMenuItem" id="contents_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Contents</property>
<property name="use_underline">True</property>
<accelerator key="F1" modifiers="" signal="activate"/>
<child internal-child="image">
<widget class="GtkImage" id="menu-item-image3">
<property name="visible">True</property>
<property name="stock">gtk-help</property>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="about_menu_item">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">gtk-about</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_about_menu_item_activate"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkToolbar" id="main_toolbar">
<property name="visible">True</property>
<property name="toolbar_style">GTK_TOOLBAR_BOTH_HORIZ</property>
<property name="icon_size">GTK_ICON_SIZE_SMALL_TOOLBAR</property>
<child>
<widget class="GtkToolButton" id="scan_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Scan</property>
<property name="icon_name">scanner</property>
<signal name="clicked" handler="on_scan_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="refresh_available_scanners_button">
<property name="visible">True</property>
<property name="stock_id">gtk-refresh</property>
<signal name="clicked" handler="on_refresh_available_scanners_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="save_as_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Save As...</property>
<property name="icon_name">document-save-as</property>
<signal name="clicked" handler="on_save_as_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkSeparatorToolItem" id="toolbutton1">
<property name="visible">True</property>
</widget>
</child>
<child>
<widget class="GtkToolButton" id="zoom_in_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Zoom In</property>
<property name="icon_name">zoom-in</property>
<signal name="clicked" handler="on_zoom_in_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="zoom_out_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Zoom Out</property>
<property name="icon_name">zoom-out</property>
<signal name="clicked" handler="on_zoom_out_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="zoom_one_to_one_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Normal Size</property>
<property name="icon_name">zoom-original</property>
<signal name="clicked" handler="on_zoom_one_to_one_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="zoom_best_fit_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Best Fit</property>
<property name="icon_name">zoom-fit-best</property>
<signal name="clicked" handler="on_zoom_best_fit_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkSeparatorToolItem" id="toolbutton2">
<property name="visible">True</property>
</widget>
</child>
<child>
<widget class="GtkToolButton" id="rotate_counter_clockwise_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Rotate Counterclockwise</property>
<property name="icon_name">object-rotate-left</property>
<signal name="clicked" handler="on_rotate_counter_clockwise_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="rotate_clockwise_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Rotate Clockwise</property>
<property name="icon_name">object-rotate-right</property>
<signal name="clicked" handler="on_rotate_clockwise_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkSeparatorToolItem" id="toolbutton4">
<property name="visible">True</property>
</widget>
</child>
<child>
<widget class="GtkToolButton" id="go_first_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">First</property>
<property name="stock_id">gtk-goto-first</property>
<signal name="clicked" handler="on_go_first_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="go_previous_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Back</property>
<property name="stock_id">gtk-go-back</property>
<signal name="clicked" handler="on_go_previous_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="go_next_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Forward</property>
<property name="stock_id">gtk-go-forward</property>
<signal name="clicked" handler="on_go_next_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="go_last_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Last</property>
<property name="stock_id">gtk-goto-last</property>
<signal name="clicked" handler="on_go_last_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkViewport" id="document_view_docking_viewport">
<property name="visible">True</property>
<property name="resize_mode">GTK_RESIZE_QUEUE</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkViewport" id="status_view_docking_viewport">
<property name="visible">True</property>
<property name="resize_mode">GTK_RESIZE_QUEUE</property>
<property name="shadow_type">GTK_SHADOW_NONE</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">3</property>
</packing>
</child>
</widget>
</child>
</widget>
- <widget class="GtkWindow" id="progress_window">
- <property name="width_request">400</property>
- <property name="height_request">200</property>
- <property name="title" translatable="yes">Scan in progress...</property>
- <property name="resizable">False</property>
- <property name="modal">True</property>
- <property name="window_position">GTK_WIN_POS_CENTER</property>
- <property name="destroy_with_parent">True</property>
- <property name="icon_name">scanner</property>
- <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property>
- <property name="skip_taskbar_hint">True</property>
- <property name="skip_pager_hint">True</property>
- <property name="transient_for">scan_window</property>
- <signal name="delete_event" handler="on_progress_window_delete_event"/>
- <child>
- <widget class="GtkAlignment" id="alignment1">
- <property name="visible">True</property>
- <property name="top_padding">12</property>
- <property name="bottom_padding">12</property>
- <property name="left_padding">12</property>
- <property name="right_padding">12</property>
- <child>
- <widget class="GtkVBox" id="vbox2">
- <property name="visible">True</property>
- <property name="spacing">12</property>
- <child>
- <widget class="GtkVBox" id="vbox3">
- <property name="visible">True</property>
- <property name="spacing">12</property>
- <child>
- <widget class="GtkLabel" id="progress_primary_label">
- <property name="visible">True</property>
- <property name="xalign">0</property>
- <property name="label" translatable="yes"><big><b>Scan in progress...</b></big></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkVBox" id="vbox4">
- <property name="visible">True</property>
- <property name="spacing">12</property>
- <child>
- <widget class="GtkVBox" id="vbox3">
- <property name="visible">True</property>
- <child>
- <widget class="GtkHBox" id="hbox2">
- <property name="visible">True</property>
- <property name="spacing">6</property>
- <child>
- <widget class="GtkLabel" id="static_mode_label">
- <property name="width_request">90</property>
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes"><b>Mode:</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="progress_mode_label">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Color</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkHBox" id="hbox5">
- <property name="visible">True</property>
- <property name="spacing">6</property>
- <child>
- <widget class="GtkLabel" id="static_page_size_label">
- <property name="width_request">90</property>
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes"><b>Page Size:</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="progress_page_size_label">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Letter (TODO)</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- <child>
- <widget class="GtkHBox" id="hbox3">
- <property name="visible">True</property>
- <property name="spacing">6</property>
- <child>
- <widget class="GtkLabel" id="static_resolution_label">
- <property name="width_request">90</property>
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes"><b>Resolution:</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="progress_resolution_label">
- <property name="visible">True</property>
- <property name="label" translatable="yes">150 DPI</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="position">2</property>
- </packing>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkVBox" id="vbox4">
- <property name="visible">True</property>
- <child>
- <widget class="GtkProgressBar" id="scan_progressbar">
- <property name="visible">True</property>
- <property name="show_text">True</property>
- <property name="text" translatable="yes">X of Y bytes receieved.</property>
- </widget>
- <packing>
- <property name="fill">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="progress_secondary_label">
- <property name="visible">True</property>
- <property name="xalign">0</property>
- <property name="label" translatable="yes"><i>Scanning page 1 of Z.</i></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="fill">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkHBox" id="hbox1">
- <property name="visible">True</property>
- <property name="spacing">12</property>
- <child>
- <widget class="GtkButton" id="scan_cancel_button">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <property name="label" translatable="yes">gtk-cancel</property>
- <property name="use_stock">True</property>
- <property name="response_id">0</property>
- <signal name="clicked" handler="on_scan_cancel_button_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="pack_type">GTK_PACK_END</property>
- <property name="position">2</property>
- </packing>
- </child>
- <child>
- <widget class="GtkButton" id="scan_again_button">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <property name="response_id">0</property>
- <signal name="clicked" handler="on_scan_again_button_clicked"/>
- <child>
- <widget class="GtkHBox" id="hbox4">
- <property name="visible">True</property>
- <child>
- <widget class="GtkImage" id="image1">
- <property name="visible">True</property>
- <property name="icon_name">scanner</property>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="label1">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Scan Again</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="pack_type">GTK_PACK_END</property>
- <property name="position">1</property>
- </packing>
- </child>
- <child>
- <widget class="GtkButton" id="quick_save_button">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <property name="response_id">0</property>
- <signal name="clicked" handler="on_quick_save_button_clicked"/>
- <child>
- <widget class="GtkHBox" id="hbox6">
- <property name="visible">True</property>
- <child>
- <widget class="GtkImage" id="image2">
- <property name="visible">True</property>
- <property name="stock">gtk-save-as</property>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="label2">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Quick Save</property>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="pack_type">GTK_PACK_END</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="fill">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- </child>
- </widget>
</glade-interface>
diff --git a/utils/gtkexcepthook.py b/utils/gtkexcepthook.py
index 7876f13..f0e8f3d 100644
--- a/utils/gtkexcepthook.py
+++ b/utils/gtkexcepthook.py
@@ -1,169 +1,169 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
# This module is based on:
# gtkexcepthook.py
# from http://blog.sysfs.net/archives/35-PyGTK-exception-handler.html
# which carries the following copyright notice:
# (c) 2003 Gustavo J A M Carneiro gjc at inescporto.pt
# 2004-2005 Filip Van Raemdonck
# http://www.daa.com.au/pipermail/pygtk/2003-August/005775.html
# Message-ID: <[email protected]>
# "The license is whatever you want."
"""
This module contains a replacement sys.excepthook which informs the
user of the error via a GTK dialog and allows them to control
whether or not the application exits.
"""
from cStringIO import StringIO
import inspect
import linecache
import logging
import pydoc
import sys
import traceback
import gtk
import pango
import pygtk
pygtk.require ('2.0')
def lookup (name, frame, lcls):
"""
Find the value for a given name in a given frame.
This function is unmodified from Filip Van Raemdonck's
version.
"""
if name in lcls:
return 'local', lcls[name]
elif name in frame.f_globals:
return 'global', frame.f_globals[name]
elif '__builtins__' in frame.f_globals:
builtins = frame.f_globals['__builtins__']
if type (builtins) is dict:
if name in builtins:
return 'builtin', builtins[name]
else:
if hasattr (builtins, name):
return 'builtin', getattr (builtins, name)
return None, []
def analyse (exctyp, value, tb):
"""
Create a text representation of an exception traceback.
This function is unmodified from Filip Van Raemdonck's
version.
"""
import tokenize, keyword
trace = StringIO()
nlines = 3
frecs = inspect.getinnerframes (tb, nlines)
trace.write ('Traceback (most recent call last):\n')
for frame, fname, lineno, funcname, context, cindex in frecs:
trace.write (' File "%s", line %d, ' % (fname, lineno))
args, varargs, varkw, lcls = inspect.getargvalues (frame)
def readline (lno=[lineno], *args):
if args: print args
try: return linecache.getline (fname, lno[0])
finally: lno[0] += 1
all, prev, name, scope = {}, None, '', None
for ttype, tstr, stup, etup, line in tokenize.generate_tokens (readline):
if ttype == tokenize.NAME and tstr not in keyword.kwlist:
if name:
if name[-1] == '.':
try:
val = getattr (prev, tstr)
except AttributeError:
# XXX skip the rest of this identifier only
break
name += tstr
else:
assert not name and not scope
scope, val = lookup (tstr, frame, lcls)
name = tstr
if val:
prev = val
#print ' found', scope, 'name', name, 'val', val, 'in', prev, 'for token', tstr
elif tstr == '.':
if prev:
name += '.'
else:
if name:
all[name] = (scope, prev)
prev, name, scope = None, '', None
if ttype == tokenize.NEWLINE:
break
trace.write (funcname +
inspect.formatargvalues (args, varargs, varkw, lcls, formatvalue=lambda v: '=' + pydoc.text.repr (v)) + '\n')
trace.write (''.join ([' ' + x.replace ('\t', ' ') for x in filter (lambda a: a.strip(), context)]))
if len (all):
trace.write (' variables: %s\n' % str (all))
trace.write ('%s: %s' % (exctyp.__name__, value))
return trace
def _gtkexcepthook(exception_type, instance, traceback):
"""
Display a GTK dialog informing the user that an unhandled
exception has occurred. Log the exception and provide the
option to continue or quit.
TODO: Should have a way to report bugs.
"""
trace_log = trace = analyse(exception_type, instance, traceback)
log = logging.getLogger("gtkexcepthook")
log.error("%s caught. Traceback follows \n%s" %
(exception_type, trace_log.getvalue()))
dialog = gtk.MessageDialog(
parent=None, flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_NONE)
dialog.set_title("")
# TODO: is this needed?
if gtk.check_version (2, 4, 0) is not None:
dialog.set_has_separator (False)
primary = "<big><b>An unhandled exception has been logged.</b></big>"
secondary = "It may be possible to continue normally, or you may choose to exit NoStaples and restart."
dialog.set_markup(primary)
dialog.format_secondary_text(secondary)
dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
dialog.add_button(gtk.STOCK_QUIT, 1)
response = dialog.run()
-
+
if response == 1 and gtk.main_level() > 0:
gtk.main_quit()
else:
pass
-
+
dialog.destroy()
sys.excepthook = _gtkexcepthook
\ No newline at end of file
diff --git a/utils/scanning.py b/utils/scanning.py
index 4c41251..76386dc 100644
--- a/utils/scanning.py
+++ b/utils/scanning.py
@@ -1,240 +1,224 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains those functions (in the form of Thread objects)
that interface with scanning hardware via SANE.
"""
import commands
import logging
import os
import re
import tempfile
import threading
import gobject
from nostaples import constants
import saneme
class IdleObject(gobject.GObject):
"""
Override gobject.GObject to always emit signals in the main thread
by emitting on an idle handler.
This class is based on an example by John Stowers:
U{http://www.johnstowers.co.nz/blog/index.php/tag/pygtk/}
"""
def __init__(self):
gobject.GObject.__init__(self)
def emit(self, *args):
- gobject.idle_add(gobject.GObject.emit,self,*args)
+ gobject.idle_add(gobject.GObject.emit, self, *args)
+def abort_on_exception(func):
+ """
+ This function decorator wraps the run() method of a thread
+ so that any exceptions in that thread will be logged and
+ cause the threads 'abort' signal to be emitted with the exception
+ as an argument. This way all exception handling can occur
+ on the main thread.
+ """
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except Exception, e:
+ thread_object = args[0]
+ thread_object.log.error('Exception type %s: %s' % (e.__class__.__name__, e.message))
+ thread_object.emit('aborted', e)
+ return wrapper
+
class UpdateAvailableScannersThread(IdleObject, threading.Thread):
"""
Responsible for getting an updated list of available scanners
and passing it back to the main thread.
"""
__gsignals__ = {
- "finished": (
- gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT]),
+ 'finished': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
+ 'aborted': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane = sane
self.log.debug('Created.')
+ @abort_on_exception
def run(self):
"""
Queries SANE for a list of connected scanners and updates
the list of available scanners from the results.
"""
self.log.debug('Updating available scanners.')
- try:
- devices = self.sane.get_device_list()
- except saneme.SaneOutOfMemoryError:
- # TODO
- raise
- except saneme.SaneUnknownError:
- # TODO
- raise
+ devices = self.sane.get_device_list()
# NB: We callback with the lists so that they can updated on the main thread
- self.emit("finished", devices)
+ self.emit('finished', devices)
class ScanningThread(IdleObject, threading.Thread):
"""
Responsible for scanning a page and emitting status
callbacks on the main thread.
This thread should treat its reference to the ScanningModel
as read-only. That way we don't have to worry about making
the Model thread-safe.
"""
__gsignals__ = {
- "progress": (
+ 'progress': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)),
- "succeeded": (
+ 'succeeded': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
+ 'failed': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)),
+ 'aborted': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
- "failed": (
- gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,))
}
- # TODO: add cancel event
-
def __init__(self, sane_device, mode, resolution):
"""
Initialize the thread and get a tempfile name that
will house the scanned image.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.mode = mode
self.resolution = resolution
self.cancel_event = threading.Event()
def progress_callback(self, scan_info, bytes_scanned):
"""
Pass the progress information on the the main thread
and cancel the scan if the cancel event has been set.
"""
self.emit("progress", scan_info, bytes_scanned)
if self.cancel_event.isSet():
return True
else:
return False
+ @abort_on_exception
def run(self):
"""
Set scanner options, scan a page and emit status callbacks.
"""
- assert self.sane_device.is_open()
-
+ if not self.sane_device.is_open():
+ raise AssertionError('sane_device.is_open() returned false')
+
self.log.debug('Setting device options.')
- # TODO: handle exceptions
try:
self.sane_device.options['mode'].value = self.mode
- except saneme.SaneIOError:
- raise
- except saneme.SaneOutOfMemoryError:
- raise
- except saneme.SaneAccessDeniedError:
- raise
- except saneme.SaneUnknownError:
- raise
except saneme.SaneReloadOptionsError:
+ # TODO
pass
-
- # TODO: handle exceptions
+
try:
self.sane_device.options['resolution'].value = int(self.resolution)
- except saneme.SaneIOError:
- raise
- except saneme.SaneOutOfMemoryError:
- raise
- except saneme.SaneAccessDeniedError:
- raise
- except saneme.SaneUnknownError:
- raise
except saneme.SaneReloadOptionsError:
+ # TODO
pass
self.log.debug('Beginning scan.')
pil_image = None
-
- # TODO: handle exceptions
- try:
- pil_image = self.sane_device.scan(self.progress_callback)
- except saneme.SaneDeviceBusyError:
- raise
- except saneme.SaneDeviceJammedError:
- raise
- except saneme.SaneNoDocumentsError:
- raise
- except saneme.SaneCoverOpenError:
- raise
- except saneme.SaneIOError:
- raise
- except saneme.SaneOutOfMemoryError:
- raise
- except saneme.SaneInvalidDataError:
- raise
- except saneme.SaneUnknownError:
- raise
+ pil_image = self.sane_device.scan(self.progress_callback)
if self.cancel_event.isSet():
self.emit("failed", "Scan cancelled")
else:
- assert pil_image is not None
- self.emit("succeeded", pil_image)
+ if not pil_image:
+ raise AssertionError('sane_device.scan() returned None')
+ self.emit('succeeded', pil_image)
class UpdateScannerOptionsThread(IdleObject, threading.Thread):
"""
Responsible for getting an up-to-date list of valid scanner options
and passing it back to the main thread.
"""
__gsignals__ = {
- "finished": (
- gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT]),
+ 'finished': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
+ 'aborted': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane_device):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.log.debug('Created.')
+ @abort_on_exception
def run(self):
"""
Queries SANE for a list of available options for the specified scanner.
"""
assert self.sane_device.is_open()
self.log.debug('Updating scanner options.')
mode_list = self.sane_device.options['mode'].constraint
resolution_list = [str(i) for i in self.sane_device.options['resolution'].constraint]
# NB: We callback with the lists so that they can updated on the main thread
- self.emit("finished", mode_list, resolution_list)
\ No newline at end of file
+ self.emit('finished', mode_list, resolution_list)
\ No newline at end of file
|
onyxfish/nostaples
|
b437ca1e25aab0ef9b38e4de5fdba7d447d91343
|
Revised assertion syntax so that all exceptions have messages.
|
diff --git a/sane/saneme.py b/sane/saneme.py
index 9dea61d..637d091 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,891 +1,933 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
-# TODO: document what exceptions can be thrown by each method
+# TODO: document what exceptions can be thrown by each method,
+# including those that could bubble up
from array import *
import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the application
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SaneMe(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object, perform setup, and register
the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
self._setup()
atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
"""
version_code = SANE_Int()
auth_callback = SANE_Auth_Callback(self._sane_auth_callback)
status = sane_init(byref(version_code), auth_callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def _sane_auth_callback(self, resource, username, password):
"""
TODO
"""
raise NotImplementedError(
'sane_auth_callback requested, but not yet implemented.')
def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. To
ensure this method is called it is registered with atexit.
"""
for device in self._devices:
if device.is_open():
device.close()
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
# Public Methods
def get_device_list(self):
"""
Poll for connected devices. This method may take several
seconds to return.
Note that SANE is exited and re-inited before querying for
devices to workaround a limitation in SANE's USB driver
which causes the device list to only be updated on init.
This means that all settings applied to all devices will be
B{lost} and must be restored by the calling application.
This was found documented here:
U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html}
"""
- assert self._version is not None
+ if not self._version:
+ raise AssertionError('version was None')
# See docstring for details on this voodoo
self._shutdown()
self._setup()
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
return self._devices
def get_device_by_name(self, name):
"""
Retrieve a L{Device} by name.
Must be preceded by a call to L{get_device_list}.
"""
for device in self._devices:
if device.name == name:
return device
raise SaneNoSuchDeviceError()
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_display_name = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
- assert type(ctypes_device.name) is StringType
- assert type(ctypes_device.vendor) is StringType
- assert type(ctypes_device.model) is StringType
- assert type(ctypes_device.type) is StringType
+ if type(ctypes_device.name) is not StringType:
+ raise AssertionError('device name was not of StringType')
+ if type(ctypes_device.vendor) is not StringType:
+ raise AssertionError('device vendor was not of StringType')
+ if type(ctypes_device.model) is not StringType:
+ raise AssertionError('device model was not of StringType')
+ if type(ctypes_device.type) is not StringType:
+ raise AssertionError('device type was not of StringType')
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
self._display_name = ' '.join([self._vendor, self._model])
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_display_name(self):
"""
Get an appropriate name to use for displaying this device
to a user, e.g. 'Lexmark X1100/rev. B2'."""
return self._display_name
display_name = property(__get_display_name)
def __get_options(self):
"""Get the dictionary of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
- assert self._handle is not None
- assert self._handle != c_void_p(None)
+ if not self._handle:
+ raise AssertionError('device handle was None.')
+ if self._handle == c_void_p(None):
+ raise AssertionError('device handle was a null pointer.')
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
raise SaneUnsupportedOperationError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
- assert self._handle is not None
- assert self._handle != c_void_p(None)
+ if not self._handle:
+ raise AssertionError('device handle was None.')
+ if self._handle == c_void_p(None):
+ raise AssertionError('device handle was a null pointer.')
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
- assert self._handle is None
+ if self._handle:
+ raise AssertionError('device handle already exists.')
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
# TODO - invalid device name? disconnected?
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
- assert self._handle != c_void_p(None)
+ if self._handle == c_void_p(None):
+ raise AssertionError('device handle was a null pointer.')
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
- assert self._handle is not None
- assert self._handle != c_void_p(None)
+ if not self._handle:
+ raise AssertionError('device handle was None.')
+ if self._handle == c_void_p(None):
+ raise AssertionError('device handle was a null pointer.')
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
TODO: handle ADF scans
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
- assert self._handle is not None
- assert self._handle != c_void_p(None)
+ if not self._handle:
+ raise AssertionError('device handle was None.')
+ if self._handle == c_void_p(None):
+ raise AssertionError('device handle was a null pointer.')
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
# This is the size used for the scan buffer in SANE's scanimage
# utility. The precise reasoning for using 32kb is unclear.
bytes_per_read = 32768
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
cancel = False
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
return None
- assert not cancel
+ if cancel:
+ raise AssertionError('cancel was true after scan completed.')
sane_cancel(self._handle)
- assert scan_info.total_bytes == len(data_array)
+ if scan_info.total_bytes != len(data_array):
+ raise AssertionError('length of scanned data did not match expected length.')
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'RGB', 0, 1)
else:
# TODO
raise NotImplementedError(
'Individual color frame scanned, but not yet supported.')
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint = None
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
- assert type(ctypes_option.name) is StringType
- assert type(ctypes_option.title) is StringType
- assert type(ctypes_option.desc) is StringType
- assert type(ctypes_option.type) is IntType
- assert type(ctypes_option.unit) is IntType
- assert type(ctypes_option.size) is IntType
- assert type(ctypes_option.cap) is IntType
- assert type(ctypes_option.constraint_type) is IntType
+ if type(ctypes_option.name) is not StringType:
+ raise AssertionError('option name was not of StringType.')
+ if type(ctypes_option.title) is not StringType:
+ raise AssertionError('option title was not of StringType.')
+ if type(ctypes_option.desc) is not StringType:
+ raise AssertionError('option description was not of StringType.')
+ if type(ctypes_option.type) is not IntType:
+ raise AssertionError('option type was not of IntType.')
+ if type(ctypes_option.unit) is not IntType:
+ raise AssertionError('option unit was not of IntType.')
+ if type(ctypes_option.size) is not IntType:
+ raise AssertionError('option size was not of IntType.')
+ if type(ctypes_option.cap) is not IntType:
+ raise AssertionError('option capabilities was not of IntType.')
+ if type(ctypes_option.constraint_type) is not IntType:
+ raise AssertionError('option constraint_type was not of IntType.')
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
- assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
- assert type(ctypes_option.constraint.range.contents.min) is IntType
- assert type(ctypes_option.constraint.range.contents.max) is IntType
- assert type(ctypes_option.constraint.range.contents.quant) is IntType
+ if type(ctypes_option.constraint.range) is not POINTER(SANE_Range):
+ raise AssertionError('option\'s constraint range was not a pointer to a SANE_Range.')
+ if type(ctypes_option.constraint.range.contents.min) is not IntType:
+ raise AssertionError('option\'s constraint range min was not of IntType.')
+ if type(ctypes_option.constraint.range.contents.max) is not IntType:
+ raise AssertionError('option\'s constraint range max was not of IntType.')
+ if type(ctypes_option.constraint.range.contents.quant) is not IntType:
+ raise AssertionError('option\'s constraint range quant was not of IntType.')
self._constraint = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
- assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
+ if type(ctypes_option.constraint.word_list) is not POINTER(SANE_Word):
+ raise AssertionError('option\'s constraint range was not a pointer to a SANE_Word.')
word_count = ctypes_option.constraint.word_list[0]
self._constraint = []
i = 1
while(i < word_count):
self._constraint.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
- assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
+ if type(ctypes_option.constraint.string_list) is not POINTER(SANE_String_Const):
+ raise AssertionError('option\'s constraint range was not a pointer to a SANE_String_Const.')
string_count = 0
self._constraint = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
return self._type
type = property(__get_type)
def __get_unit(self):
return self._unit
unit = property(__get_unit)
def __get_capability(self):
# TODO: break out into individual capabilities, rather than a bitset
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint(self):
"""
Get the constraint for this option.
If constraint_type is OPTION_CONSTRAINT_RANGE then
this is a tuple containing the (minimum, maximum, step)
for valid values.
If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then
this is a list of integers which are valid values.
If constraint_type is OPTION_CONSTRAINT_STRING_LIST then
this is a list of strings which are valid values.
"""
return self._constraint
constraint = property(__get_constraint)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# Constraint checking ensures this should never happen
raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported a value was invalid, but no values was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
- assert type(value) is BooleanType
+ if type(value) is not BooleanType:
+ raise AssertionError('option expected BooleanType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
- assert type(value) is IntType
+ if type(value) is not IntType:
+ raise AssertionError('option expected IntType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
- assert type(value) is IntType
+ if type(value) is not IntType:
+ raise AssertionError('option expected IntType')
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
- assert type(value) is StringType
- assert len(value) + 1 < self._size
+ if type(value) is not StringType:
+ raise AssertionError('option expected StringType')
+ if len(value) + 1 > self._size:
+ raise AssertionError('value for option is longer than max string size')
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
- assert value >= self._constraint[0]
- assert value <= self._constraint[1]
- assert value % self._constraint[2] == 0
+ if value < self._constraint[0]:
+ raise AssertionError('value for option is less than min.')
+ if value > self._constraint[1]:
+ raise AssertionError('value for option is greater than max.')
+ if value % self._constraint[2] != 0:
+ raise AssertionError('value for option is not divisible by quant.')
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
- assert value in self._constraint
+ if value not in self._constraint:
+ raise AssertionError('value for option not in list of valid values.')
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
- assert value in self._constraint
+ if value not in self._constraint:
+ raise AssertionError('value for option not in list of valid strings.')
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# Constraint checking ensures this should never happen
raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
def progress_callback(sane_info, bytes_read):
#print float(bytes_read) / sane_info.total_bytes
pass
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
sane = SaneMe(logging.getLogger())
devices = sane.get_device_list()
for dev in devices:
print dev.name
devices[0].open()
print devices[0].options.keys()
try:
devices[0].options['mode'].value = 'Gray'
except SaneReloadOptionsError:
pass
try:
devices[0].options['resolution'].value = 75
except SaneReloadOptionsError:
pass
try:
devices[0].options['preview'].value = False
except SaneReloadOptionsError:
pass
devices[0].scan(progress_callback).save('out.bmp')
devices[0].close()
\ No newline at end of file
|
onyxfish/nostaples
|
f5e04baa3b3cef46d7e496207232918385b10ba1
|
Overhauled the way exceptions are handled across threads.
|
diff --git a/application.py b/application.py
index 8c871f8..699b616 100644
--- a/application.py
+++ b/application.py
@@ -1,335 +1,334 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds NoStaples' main method which handles
the instantiation of MVC objects and then starts the gtk
main loop.
"""
import logging.config
import os
import gtk
from nostaples import constants
from nostaples.controllers.about import AboutController
from nostaples.controllers.document import DocumentController
from nostaples.controllers.main import MainController
from nostaples.controllers.page import PageController
from nostaples.controllers.preferences import PreferencesController
from nostaples.controllers.save import SaveController
from nostaples.controllers.status import StatusController
from nostaples.models.document import DocumentModel
from nostaples.models.main import MainModel
from nostaples.models.page import PageModel
from nostaples.models.preferences import PreferencesModel
from nostaples.models.save import SaveModel
from nostaples.models.status import StatusModel
import nostaples.utils.gtkexcepthook
from nostaples.utils.state import GConfStateManager
from nostaples.views.about import AboutView
from nostaples.views.document import DocumentView
from nostaples.views.main import MainView
from nostaples.views.page import PageView
from nostaples.views.preferences import PreferencesView
from nostaples.views.save import SaveView
from nostaples.views.status import StatusView
from saneme import SaneMe
class Application(object):
"""
A 'front controller' class that stores references to all
top-level components of the application and facilitates
communication between them.
A reference to this class is injected into each controller
component of the application via its constructor. These
components then query the application object when they
need to access other parts of the system.
"""
_state_manager = None
_sane = None
_main_model = None
_main_controller = None
_main_view = None
_document_model = None
_document_controller = None
_document_view = None
_null_page_model = None
_page_controller = None
_page_view = None
_status_model = None
_status_controller = None
_status_view = None
_preferences_model = None
_preferences_controller = None
_preferences_view = None
_save_model = None
_save_controller = None
_save_view = None
_about_controller = None
_about_view = None
def __init__(self):
"""
Set up the config directory, logging, and state
persistence. Construct the Main MVC component triplet
(which will in turn construct all sub components).
Per
"""
self._init_config()
self._init_logging()
self._init_state()
self._init_sane()
self._init_main_components()
self._init_settings()
def _init_config(self):
"""Setup the config directory."""
if not os.path.exists(constants.TEMP_IMAGES_DIRECTORY):
os.mkdir(constants.TEMP_IMAGES_DIRECTORY)
def _init_logging(self):
"""Setup logging for the application."""
logging.config.fileConfig(constants.LOGGING_CONFIG)
def _init_state(self):
"""Setup the state manager."""
self._state_manager = GConfStateManager()
def _init_sane(self):
"""Setup SANE."""
self._sane = SaneMe(logging.getLogger("saneme"))
def _init_main_components(self):
"""
Create the main application components, which will
request creation of other components as necessary.
"""
self._main_model = MainModel(self)
self._main_controller = MainController(self)
self._main_view = MainView(self)
def _init_settings(self):
"""
Load current settings from the state manager and
poll for available scanners.
"""
self._main_model.load_state()
self.get_save_model().load_state()
self.get_preferences_model().load_state()
self._main_controller._update_available_scanners()
# PUBLIC METHODS
def run(self):
"""Execute the GTK main loop."""
assert isinstance(self._main_view, MainView)
self._main_view.show()
- gtk.gdk.threads_init()
gtk.main()
def get_state_manager(self):
"""Return the L{GConfStateManager} component."""
assert isinstance(self._state_manager, GConfStateManager)
return self._state_manager
def get_sane(self):
"""Return the SaneMe object."""
assert isinstance(self._sane, SaneMe)
return self._sane
def get_main_model(self):
"""Return the L{MainModel} component."""
assert self._main_model
return self._main_model
def get_main_controller(self):
"""Return the L{MainController} component."""
assert self._main_controller
return self._main_controller
def get_main_view(self):
"""Return the L{MainView} component."""
assert self._main_view
return self._main_view
def get_document_model(self):
"""Return the L{DocumentModel} component."""
if not self._document_model:
self._document_model = DocumentModel(self)
return self._document_model
def get_document_controller(self):
"""Return the L{DocumentController} component."""
if not self._document_controller:
self._document_controller = DocumentController(self)
return self._document_controller
def get_document_view(self):
"""Return the L{DocumentView} component."""
if not self._document_view:
self._document_view = DocumentView(self)
return self._document_view
def get_null_page_model(self):
"""
Return an empty L{PageModel} object.
This is the PageModel that is used when no
pages have been scanned.
"""
if not self._null_page_model:
self._null_page_model = PageModel(self)
return self._null_page_model
def get_current_page_model(self):
"""
Return the current/active L{PageModel} object.
This is a convenience function.
"""
return self.get_page_controller().get_current_page_model()
def get_page_controller(self):
"""Return the L{PageController} component."""
if not self._page_controller:
self._page_controller = PageController(self)
return self._page_controller
def get_page_view(self):
"""Return the L{PageView} component."""
if not self._page_view:
self._page_view = PageView(self)
return self._page_view
def get_status_model(self):
"""Return the L{StatusModel} component."""
if not self._status_model:
self._status_model = StatusModel(self)
return self._status_model
def get_status_controller(self):
"""Return the L{StatusController} component."""
if not self._status_controller:
self._status_controller = StatusController(self)
return self._status_controller
def get_status_view(self):
"""Return the L{StatusView} component."""
if not self._status_view:
self._status_view = StatusView(self)
return self._status_view
def get_preferences_model(self):
"""Return the L{PreferencesModel} component."""
if not self._preferences_model:
self._preferences_model = PreferencesModel(self)
return self._preferences_model
def get_preferences_controller(self):
"""Return the L{PreferencesController} component."""
if not self._preferences_controller:
self._preferences_controller = PreferencesController(self)
return self._preferences_controller
def get_preferences_view(self):
"""Return the L{PreferencesView} component."""
if not self._preferences_view:
self._preferences_view = PreferencesView(self)
return self._preferences_view
def show_preferences_dialog(self):
"""
Show the preferences dialog.
This is a convenience function.
"""
self.get_preferences_controller().run()
def get_save_model(self):
"""Return the L{SaveModel} component."""
if not self._save_model:
self._save_model = SaveModel(self)
return self._save_model
def get_save_controller(self):
"""Return the L{SaveController} component."""
if not self._save_controller:
self._save_controller = SaveController(self)
return self._save_controller
def get_save_view(self):
"""Return the L{SaveView} component."""
if not self._save_view:
self._save_view = SaveView(self)
return self._save_view
def show_save_dialog(self):
"""
Show the save dialog.
This is a convenience function.
"""
self.get_save_controller().run()
def get_about_controller(self):
"""Return the L{SaveController} component."""
if not self._about_controller:
self._about_controller = AboutController(self)
return self._about_controller
def get_about_view(self):
"""Return the L{SaveView} component."""
if not self._about_view:
self._about_view = AboutView(self)
return self._about_view
def show_about_dialog(self):
"""
Show the about dialog.
This is a convenience function.
"""
self.get_about_controller().run()
diff --git a/controllers/main.py b/controllers/main.py
index e4e0416..09a84ba 100644
--- a/controllers/main.py
+++ b/controllers/main.py
@@ -1,706 +1,787 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the L{MainController}, which manages interaction
between the L{MainModel} and L{MainView}.
"""
import commands
import logging
import os
import re
import threading
import gobject
import gtk
from gtkmvc.controller import Controller
from nostaples.models.page import PageModel
from nostaples.utils.scanning import *
+import saneme
class MainController(Controller):
"""
Manages interaction between the L{MainModel} and L{MainView}.
"""
# SETUP METHODS
def __init__(self, application):
"""
Constructs the MainController, as well as necessary sub-controllers
and services.
"""
self.application = application
Controller.__init__(self, application.get_main_model())
application.get_document_model().register_observer(self)
status_controller = application.get_status_controller()
self.status_context = \
status_controller.get_context_id(self.__class__.__name__)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def register_view(self, view):
"""
Registers this controller with a view.
"""
Controller.register_view(self, view)
self.log.debug('%s registered.', view.__class__.__name__)
def register_adapters(self):
"""
Registers adapters for property/widget pairs that do not require
complex processing.
"""
self.adapt('show_toolbar', 'show_toolbar_menu_item')
self.adapt('show_statusbar', 'show_statusbar_menu_item')
self.adapt('show_thumbnails', 'show_thumbnails_menu_item')
self.adapt('show_adjustments', 'show_adjustments_menu_item')
self.adapt('rotate_all_pages', 'rotate_all_pages_menu_item')
self.log.debug('Adapters registered.')
# USER INTERFACE CALLBACKS
# Menu Items
def on_scan_window_destroy(self, window):
"""Exits the application."""
self.quit()
def on_scan_menu_item_activate(self, menu_item):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_menu_item_activate(self, menu_item):
"""Refresh the list of connected scanners from SANE."""
self._update_available_scanners()
def on_save_as_menu_item_activate(self, menu_item):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_delete_menu_item_activate(self, menu_item):
self.application.get_document_controller().delete_selected()
def on_preferences_menu_item_activate(self, menu_item):
"""Creates and displays a preferences dialog."""
self.application.show_preferences_dialog()
def on_quit_menu_item_activate(self, menu_item):
"""Exits the application."""
self.quit()
def on_zoom_in_menu_item_activate(self, menu_item):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_menu_item_activate(self, menu_item):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_menu_item_activate(self, menu_item):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_menu_item_activate(self, menu_item):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_menu_item_activate(self, menu_item):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_available_scanner_menu_item_toggled(self, menu_item):
"""
Set the active scanner.
TODO: Need a second scanner to properly test this...
"""
main_model = self.application.get_main_model()
if menu_item.get_active():
for scanner in main_model.available_scanners:
if scanner.display_name == menu_item.get_children()[0].get_text():
main_model.active_scanner = scanner
return
def on_valid_mode_menu_item_toggled(self, menu_item):
"""Sets the active scan mode."""
if menu_item.get_active():
self.application.get_main_model().active_mode = \
menu_item.get_children()[0].get_text()
def on_valid_resolution_menu_item_toggled(self, menu_item):
"""Sets the active scan resolution."""
if menu_item.get_active():
self.application.get_main_model().active_resolution = \
menu_item.get_children()[0].get_text()
def on_go_first_menu_item_activate(self, menu_item):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_menu_item_activate(self, menu_item):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_menu_item_activate(self, menu_item):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_menu_item_activate(self, menu_item):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
def on_contents_menu_item_clicked(self, menu_item):
"""TODO"""
pass
def on_about_menu_item_activate(self, menu_item):
"""Show the about dialog."""
self.application.show_about_dialog()
# Toolbar Buttons
def on_scan_button_clicked(self, button):
"""Scan a page into the current document."""
self._scan()
def on_refresh_available_scanners_button_clicked(self, button):
self._update_available_scanners()
def on_save_as_button_clicked(self, button):
"""Saves the current document to a file."""
self.application.show_save_dialog()
def on_zoom_in_button_clicked(self, button):
"""Zooms the page preview in."""
self.application.get_page_controller().zoom_in()
def on_zoom_out_button_clicked(self, button):
"""Zooms the page preview out."""
self.application.get_page_controller().zoom_out()
def on_zoom_one_to_one_button_clicked(self, button):
"""Zooms the page preview to the true size of the scanned image."""
self.application.get_page_controller().zoom_one_to_one()
def on_zoom_best_fit_button_clicked(self, button):
"""Zooms the page preview to best fit within the preview window."""
self.application.get_page_controller().zoom_best_fit()
def on_rotate_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress clockwise."""
self.application.get_document_controller().rotate_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_rotate_counter_clockwise_button_clicked(self, button):
"""Rotates the visible page ninety degress counter-clockwise."""
self.application.get_document_controller().rotate_counter_clockwise(
self.application.get_main_model().rotate_all_pages)
def on_go_first_button_clicked(self, button):
"""Selects the first scanned page."""
self.application.get_document_controller().goto_first_page()
def on_go_previous_button_clicked(self, button):
"""Selects the scanned page before to the currently selected one."""
self.application.get_document_controller().goto_previous_page()
def on_go_next_button_clicked(self, button):
"""Selects the scanned page after to the currently selected one."""
self.application.get_document_controller().goto_next_page()
def on_go_last_button_clicked(self, button):
"""Selects the last scanned page."""
self.application.get_document_controller().goto_last_page()
# Progress Window INTERFACE CALLBACKS
def on_progress_window_delete_event(self, window, event):
"""
Emulate clicking of the cancel/close button and then
hide the window.
"""
main_view = self.application.get_main_view()
self.on_scan_cancel_button_clicked(None)
main_view['progress_window'].hide()
return True
def on_scan_cancel_button_clicked(self, button):
"""
Cancel the current scan or, if the scan is finished,
close the progress window.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress:
assert self.cancel_event
self.cancel_event.set()
else:
main_view['progress_window'].hide()
def on_scan_again_button_clicked(self, button):
"""Initiate a new scan from the progress window."""
self._scan()
def on_quick_save_button_clicked(self, button):
"""
Show the save dialog. If the user completes a save
then disable the quick save button until another
page is scanned.
"""
main_view = self.application.get_main_view()
document_model = self.application.get_document_model()
self.application.show_save_dialog()
if document_model.count == 0:
main_view['quick_save_button'].set_sensitive(False)
# MainModel PROPERTY CALLBACKS
def property_show_toolbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the toolbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_toolbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['main_toolbar'].show()
else:
main_view['main_toolbar'].hide()
def property_show_statusbar_value_change(self, model, old_value, new_value):
"""Update the visibility of the statusbar."""
main_view = self.application.get_main_view()
menu_item = main_view['show_statusbar_menu_item']
menu_item.set_active(new_value)
if new_value:
main_view['status_view_docking_viewport'].show()
else:
main_view['status_view_docking_viewport'].hide()
def property_show_thumbnails_value_change(self, model, old_value, new_value):
"""Update the visibility of the thumbnails."""
main_view = self.application.get_main_view()
menu_item = main_view['show_thumbnails_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_thumbnails_visible(new_value)
def property_show_adjustments_value_change(self, model, old_value, new_value):
"""Update the visibility of the adjustments controls."""
main_view = self.application.get_main_view()
menu_item = main_view['show_adjustments_menu_item']
menu_item.set_active(new_value)
self.application.get_document_controller().toggle_adjustments_visible(new_value)
def property_active_scanner_value_change(self, model, old_value, new_value):
"""
Update the menu and valid scanner options to match the new device.
"""
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
for menu_item in main_view['scanner_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value.display_name:
menu_item.set_active(True)
break
self._update_scanner_options()
def property_active_mode_value_change(self, model, old_value, new_value):
"""Select the active mode from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_mode_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_active_resolution_value_change(self, model, old_value, new_value):
"""Select the active resolution from in the menu."""
main_view = self.application.get_main_view()
for menu_item in main_view['scan_resolution_sub_menu'].get_children():
if menu_item.get_children()[0].get_text() == new_value:
menu_item.set_active(True)
break
def property_available_scanners_value_change(self, model, old_value, new_value):
"""
Update the menu of available scanners.
"""
main_view = self.application.get_main_view()
self._clear_available_scanners_sub_menu()
# Generate the new menu
if len(new_value) == 0:
menu_item = gtk.MenuItem('No Scanners Connected')
menu_item.set_sensitive(False)
main_view['scanner_sub_menu'].append(menu_item)
else:
first_item = None
for i in range(len(new_value)):
# The first menu item defines the group
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i].display_name)
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i].display_name)
main_view['scanner_sub_menu'].append(menu_item)
main_view['scanner_sub_menu'].show_all()
def property_valid_modes_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan modes for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_modes_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Modes")
menu_item.set_sensitive(False)
main_view['scan_mode_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_mode_menu_item_toggled)
main_view['scan_mode_sub_menu'].append(menu_item)
main_view['scan_mode_sub_menu'].show_all()
def property_valid_resolutions_value_change(self, model, old_value, new_value):
"""
Updates the list of valid scan resolutions for the current scanner.
"""
main_view = self.application.get_main_view()
self._clear_scan_resolutions_sub_menu()
if len(new_value) == 0:
menu_item = gtk.MenuItem("No Scan Resolutions")
menu_item.set_sensitive(False)
main_view['scan_resolution_sub_menu'].append(menu_item)
else:
for i in range(len(new_value)):
if i == 0:
menu_item = gtk.RadioMenuItem(
None, new_value[i])
first_item = menu_item
else:
menu_item = gtk.RadioMenuItem(
first_item, new_value[i])
menu_item.connect('toggled', self.on_valid_resolution_menu_item_toggled)
main_view['scan_resolution_sub_menu'].append(menu_item)
main_view['scan_resolution_sub_menu'].show_all()
def property_scan_in_progress_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_available_scanners_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
def property_updating_scan_options_value_change(self, model, old_value, new_value):
"""Disable or re-enable scan controls."""
self._toggle_scan_controls()
self._toggle_document_controls()
self._update_status()
# DocumentModel PROPERTY CALLBACKS
def property_count_value_change(self, model, old_value, new_value):
"""Toggle available controls."""
self._toggle_document_controls()
# THREAD CALLBACKS
def on_scan_progress(self, scanning_thread, scan_info, bytes_scanned):
main_view = self.application.get_main_view()
short_bytes_scanned = float(bytes_scanned) / 1000
short_total_bytes = float(scan_info.total_bytes) / 1000
main_view['scan_progressbar'].set_fraction(
float(bytes_scanned) / scan_info.total_bytes)
main_view['scan_progressbar'].set_text(
'Received %ik of %ik bytes' % (short_bytes_scanned, short_total_bytes))
# TODO: multi page scans
main_view['progress_secondary_label'].set_markup(
'<i>Scanning page.</i>')
def on_scan_succeeded(self, scanning_thread, pil_image):
"""
Append the new page to the current document.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
main_view['scan_progressbar'].set_fraction(1)
main_view['scan_progressbar'].set_text('Scan complete')
main_view['progress_secondary_label'].set_markup(
'<i>Adding page to document.</i>')
gtk.gdk.flush()
new_page = PageModel(self.application, pil_image, int(main_model.active_resolution))
self.application.get_document_model().append(new_page)
main_view['progress_secondary_label'].set_markup(
'<i>Page added.</i>')
main_view['scan_again_button'].set_sensitive(True)
main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
def on_scan_failed(self, scanning_thread, reason):
"""
Set that scan is complete.
TODO: update docstring
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
status_controller = self.application.get_status_controller()
-
- #main_view['scan_progressbar'].set_fraction(0)
- #main_view['scan_progressbar'].set_text('No data')
+
main_view['progress_secondary_label'].set_markup(
'<i>%s</i>' % reason)
main_view['scan_again_button'].set_sensitive(True)
- main_view['quick_save_button'].set_sensitive(True)
+ if self.application.get_document_model().count > 0:
+ main_view['quick_save_button'].set_sensitive(True)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CLOSE)
main_model.scan_in_progress = False
+ def on_scan_aborted(self, scanning_thread, e):
+ """
+ Change display to indicate that scanning failed and
+ convey the to the user the reason why the thread aborted.
+
+ If the failure was from a SANE exception then give the
+ user the option to blacklist the device. If not, then
+ reraise the error and let the sys.excepthook deal with it.
+ """
+ self.on_scan_failed(scanning_thread, 'An error occurred.')
+
+ if isinstance(e, saneme.SaneError):
+ self.display_device_exception_dialog(e)
+ else:
+ raise e
+
def on_update_available_scanners_thread_finished(self, update_thread, scanner_list):
"""Set the new list of available scanners."""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.available_scanners = scanner_list
main_model.updating_available_scanners = False
+
+ def on_update_available_scanners_thread_aborted(self, update_thread, e):
+ """
+ Change the display to indicate that no scanners are available and
+ reraise the exception so that it can be caught by the sys.excepthook.
+
+ There is no reason to handle these cases with a special dialog,
+ if the application failed to even enumerate the available devices then
+ no other action will be possible.
+
+ This should be fantastically rare.
+ """
+ self.on_update_available_scanners_thread_finished(update_thread, [])
+ raise e
def on_update_scanner_options_thread_finished(self, update_thread, mode_list, resolution_list):
"""
Update the mode and resolution lists and rark that
the scanner is no longer in use.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
main_model.valid_modes = mode_list
main_model.valid_resolutions = resolution_list
main_model.updating_scan_options = False
+ def on_update_scanner_options_thread_aborted(self, update_thread, e):
+ """
+ Change display to indicate that updating the options failed and
+ convey the to the user the reason why the thread aborted.
+
+ If the failure was from a SANE exception then give the
+ user the option to blacklist the device. If not, then
+ reraise the error and let the sys.excepthook deal with it.
+ """
+ # TODO: If this fails the scanner icon will still stay lit,
+ # and when the user clicks it the app will error again since it
+ # will not have a valid mode/resolution.
+ self.on_update_scanner_options_thread_finished(update_thread, [], [])
+
+ if isinstance(e, saneme.SaneError):
+ self.display_device_exception_dialog(e)
+ else:
+ raise e
+
# PUBLIC METHODS
def quit(self):
"""Exits the application."""
self.log.debug('Quit.')
gtk.main_quit()
# PRIVATE METHODS
def _clear_available_scanners_sub_menu(self):
"""Clear the menu of available scanners."""
main_view = self.application.get_main_view()
for child in main_view['scanner_sub_menu'].get_children():
main_view['scanner_sub_menu'].remove(child)
def _clear_scan_modes_sub_menu(self):
"""Clear the menu of valid scan modes."""
main_view = self.application.get_main_view()
for child in main_view['scan_mode_sub_menu'].get_children():
main_view['scan_mode_sub_menu'].remove(child)
def _clear_scan_resolutions_sub_menu(self):
"""Clear the menu of valid scan resolutions."""
main_view = self.application.get_main_view()
for child in main_view['scan_resolution_sub_menu'].get_children():
main_view['scan_resolution_sub_menu'].remove(child)
def _toggle_scan_controls(self):
"""Toggle whether or not the scan controls or accessible."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_scan_controls_sensitive(False)
main_view.set_refresh_scanner_controls_sensitive(False)
else:
if main_model.active_scanner != None:
main_view.set_scan_controls_sensitive(True)
main_view.set_refresh_scanner_controls_sensitive(True)
def _toggle_document_controls(self):
"""
Toggle available document controls based on the current scanner
status and the number of scanned pages.
"""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
# Disable all controls when the scanner is in use
if main_model.scan_in_progress or main_model.updating_available_scanners or \
main_model.updating_scan_options:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
count = self.application.get_document_model().count
# Disable all controls if no pages are scanned
if count == 0:
main_view.set_file_controls_sensitive(False)
main_view.set_delete_controls_sensitive(False)
main_view.set_zoom_controls_sensitive(False)
main_view.set_adjustment_controls_sensitive(False)
main_view.set_navigation_controls_sensitive(False)
else:
# Enable most controls if any pages scanned
main_view.set_file_controls_sensitive(True)
main_view.set_delete_controls_sensitive(True)
main_view.set_zoom_controls_sensitive(True)
main_view.set_adjustment_controls_sensitive(True)
# Only enable navigation if more than one page scanned
if count > 1:
main_view.set_navigation_controls_sensitive(True)
else:
main_view.set_navigation_controls_sensitive(False)
def _update_status(self):
"""
Update the text of the statusbar based on the current state
of the application.
"""
main_model = self.application.get_main_model()
status_controller = self.application.get_status_controller()
status_controller.pop(self.status_context)
if main_model.scan_in_progress:
status_controller.push(self.status_context, 'Scanning...')
elif main_model.updating_available_scanners:
status_controller.push(self.status_context, 'Querying hardware...')
elif main_model.updating_scan_options:
status_controller.push(self.status_context, 'Querying options...')
else:
if main_model.active_scanner:
status_controller.push(self.status_context,
'Ready with %s.' % main_model.active_scanner.display_name)
else:
status_controller.push(self.status_context, 'No scanner available.')
def _scan(self):
"""Begin a scan."""
main_model = self.application.get_main_model()
main_view = self.application.get_main_view()
main_model.scan_in_progress = True
scanning_thread = ScanningThread(
main_model.active_scanner, main_model.active_mode, main_model.active_resolution)
scanning_thread.connect("progress", self.on_scan_progress)
scanning_thread.connect("succeeded", self.on_scan_succeeded)
scanning_thread.connect("failed", self.on_scan_failed)
+ scanning_thread.connect("aborted", self.on_scan_aborted)
self.cancel_event = scanning_thread.cancel_event
main_view['progress_primary_label'].set_markup(
'<big><b>%s</b></big>' % main_model.active_scanner.display_name)
main_view['scan_progressbar'].set_fraction(0)
main_view['scan_progressbar'].set_text('Waiting for data')
main_view['progress_secondary_label'].set_markup('<i>Preparing device.</i>')
- main_view['progress_mode_label'].set_markup(main_model.active_mode)
- main_view['progress_resolution_label'].set_markup('%s DPI' % main_model.active_resolution)
+ mode = main_model.active_mode if main_model.active_mode else 'Not set'
+ main_view['progress_mode_label'].set_markup(mode)
+ dpi = '%s DPI' % main_model.active_resolution if main_model.active_resolution else 'Not set'
+ main_view['progress_resolution_label'].set_markup(dpi)
main_view['scan_again_button'].set_sensitive(False)
main_view['quick_save_button'].set_sensitive(False)
main_view['scan_cancel_button'].set_label(gtk.STOCK_CANCEL)
main_view['progress_window'].show_all()
scanning_thread.start()
def _update_available_scanners(self):
"""
Start a new update thread to query for available scanners.
"""
sane = self.application.get_sane()
main_model = self.application.get_main_model()
main_model.updating_available_scanners = True
update_thread = UpdateAvailableScannersThread(sane)
update_thread.connect("finished", self.on_update_available_scanners_thread_finished)
+ update_thread.connect("aborted", self.on_update_available_scanners_thread_aborted)
update_thread.start()
def _update_scanner_options(self):
"""Determine the valid options for the current scanner."""
main_model = self.application.get_main_model()
main_model.updating_scan_options = True
update_thread = UpdateScannerOptionsThread(main_model.active_scanner)
update_thread.connect("finished", self.on_update_scanner_options_thread_finished)
- update_thread.start()
\ No newline at end of file
+ update_thread.connect("aborted", self.on_update_scanner_options_thread_aborted)
+ update_thread.start()
+
+ def display_device_exception_dialog(self, exception):
+ """
+ Display an error dialog that provides the user with the option of
+ blacklisting the device which caused the error.
+ """
+ dialog = gtk.MessageDialog(
+ parent=None, flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_NONE)
+ dialog.set_title("")
+
+ # TODO: is this needed?
+ if gtk.check_version (2, 4, 0) is not None:
+ dialog.set_has_separator (False)
+
+ primary = "<big><b>A hardware exception has been logged.</b></big>"
+ secondary = '%s\n\n%s' % (exception.message, 'If this error continues to occur you may choose to blacklist the device so that it no longer appears in the list of available scanners.')
+
+ dialog.set_markup(primary)
+ dialog.format_secondary_markup(secondary)
+
+ dialog.add_button('Blacklist Device', 1)
+ dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
+
+ response = dialog.run()
+ dialog.destroy()
+
+ # TODO: handle blacklisting
\ No newline at end of file
diff --git a/gui/page_view.glade b/gui/page_view.glade
index 1373192..e3b2db6 100644
--- a/gui/page_view.glade
+++ b/gui/page_view.glade
@@ -1,63 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--Generated with glade3 3.4.5 on Thu Jan 22 20:33:06 2009 -->
+<!--Generated with glade3 3.4.5 on Mon Feb 16 21:48:04 2009 -->
<glade-interface>
<widget class="GtkWindow" id="dummy_page_view_window">
<child>
<widget class="GtkTable" id="page_view_table">
<property name="visible">True</property>
<property name="n_rows">2</property>
<property name="n_columns">2</property>
<child>
<placeholder/>
</child>
+ <child>
+ <widget class="GtkVScrollbar" id="page_view_vertical_scrollbar">
+ <property name="no_show_all">True</property>
+ <property name="adjustment">0 0 100 1 10 10</property>
+ </widget>
+ <packing>
+ <property name="left_attach">1</property>
+ <property name="right_attach">2</property>
+ <property name="x_options">GTK_SHRINK | GTK_FILL</property>
+ <property name="y_options">GTK_SHRINK | GTK_FILL</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkHScrollbar" id="page_view_horizontal_scrollbar">
+ <property name="no_show_all">True</property>
+ <property name="adjustment">10 0 100 1 10 10</property>
+ </widget>
+ <packing>
+ <property name="top_attach">1</property>
+ <property name="bottom_attach">2</property>
+ <property name="x_options">GTK_SHRINK | GTK_FILL</property>
+ <property name="y_options">GTK_SHRINK | GTK_FILL</property>
+ </packing>
+ </child>
<child>
<widget class="GtkLayout" id="page_view_image_layout">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_STRUCTURE_MASK | GDK_SCROLL_MASK</property>
<signal name="button_press_event" handler="on_page_view_image_layout_button_press_event"/>
<signal name="motion_notify_event" handler="on_page_view_image_layout_motion_notify_event"/>
<signal name="button_release_event" handler="on_page_view_image_layout_button_release_event"/>
<signal name="size_request" handler="on_page_view_image_layout_size_request"/>
<signal name="size_allocate" handler="on_page_view_image_layout_size_allocate"/>
<signal name="scroll_event" handler="on_page_view_image_layout_scroll_event"/>
<child>
<widget class="GtkImage" id="page_view_image">
<property name="visible">True</property>
<property name="stock">gtk-missing-image</property>
</widget>
<packing>
<property name="x">61</property>
<property name="y">32</property>
</packing>
</child>
</widget>
</child>
- <child>
- <widget class="GtkHScrollbar" id="page_view_horizontal_scrollbar">
- <property name="no_show_all">True</property>
- <property name="adjustment">10 0 100 1 10 10</property>
- </widget>
- <packing>
- <property name="top_attach">1</property>
- <property name="bottom_attach">2</property>
- <property name="x_options">GTK_SHRINK | GTK_FILL</property>
- <property name="y_options">GTK_SHRINK | GTK_FILL</property>
- </packing>
- </child>
- <child>
- <widget class="GtkVScrollbar" id="page_view_vertical_scrollbar">
- <property name="no_show_all">True</property>
- <property name="adjustment">0 0 100 1 10 10</property>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">2</property>
- <property name="x_options">GTK_SHRINK | GTK_FILL</property>
- <property name="y_options">GTK_SHRINK | GTK_FILL</property>
- </packing>
- </child>
</widget>
</child>
</widget>
</glade-interface>
diff --git a/gui/scan_window.glade b/gui/scan_window.glade
index bcb9d7e..ea9aa3a 100644
--- a/gui/scan_window.glade
+++ b/gui/scan_window.glade
@@ -1,913 +1,913 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--Generated with glade3 3.4.5 on Sun Feb 15 19:08:25 2009 -->
+<!--Generated with glade3 3.4.5 on Mon Feb 16 21:36:10 2009 -->
<glade-interface>
- <widget class="GtkWindow" id="scan_window">
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- <property name="title" translatable="yes">NoStaples</property>
+ <widget class="GtkWindow" id="progress_window">
+ <property name="width_request">400</property>
+ <property name="height_request">200</property>
+ <property name="title" translatable="yes">Scan in progress...</property>
+ <property name="resizable">False</property>
+ <property name="modal">True</property>
<property name="window_position">GTK_WIN_POS_CENTER</property>
- <property name="default_width">600</property>
- <property name="default_height">400</property>
- <signal name="destroy" handler="on_scan_window_destroy"/>
- <signal name="size_allocate" handler="on_scan_window_size_allocate"/>
+ <property name="destroy_with_parent">True</property>
+ <property name="icon_name">scanner</property>
+ <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property>
+ <property name="skip_taskbar_hint">True</property>
+ <property name="skip_pager_hint">True</property>
+ <property name="transient_for">scan_window</property>
+ <signal name="delete_event" handler="on_progress_window_delete_event"/>
<child>
- <widget class="GtkVBox" id="vbox1">
+ <widget class="GtkAlignment" id="alignment1">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="top_padding">12</property>
+ <property name="bottom_padding">12</property>
+ <property name="left_padding">12</property>
+ <property name="right_padding">12</property>
<child>
- <widget class="GtkMenuBar" id="menubar1">
+ <widget class="GtkVBox" id="vbox2">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="spacing">12</property>
<child>
- <widget class="GtkMenuItem" id="menuitem1">
+ <widget class="GtkVBox" id="vbox3">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- <property name="label" translatable="yes">_File</property>
- <property name="use_underline">True</property>
+ <property name="spacing">12</property>
<child>
- <widget class="GtkMenu" id="menu1">
+ <widget class="GtkLabel" id="progress_primary_label">
<property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="xalign">0</property>
+ <property name="label" translatable="yes"><big><b>Scan in progress...</b></big></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkVBox" id="vbox4">
+ <property name="visible">True</property>
+ <property name="spacing">12</property>
<child>
- <widget class="GtkImageMenuItem" id="scan_menu_item">
+ <widget class="GtkVBox" id="vbox3">
<property name="visible">True</property>
- <property name="label" translatable="yes">S_can</property>
- <property name="use_underline">True</property>
- <signal name="activate" handler="on_scan_menu_item_activate"/>
- <child internal-child="image">
- <widget class="GtkImage" id="menu-item-image2">
+ <child>
+ <widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
- <property name="icon_name">scanner</property>
+ <property name="spacing">6</property>
+ <child>
+ <widget class="GtkLabel" id="static_mode_label">
+ <property name="width_request">90</property>
+ <property name="visible">True</property>
+ <property name="xalign">1</property>
+ <property name="label" translatable="yes"><b>Mode:</b></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="progress_mode_label">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Color</property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
</widget>
</child>
- </widget>
- </child>
- <child>
- <widget class="GtkImageMenuItem" id="refresh_available_scanners_menu_item">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Refresh Available Scanners</property>
- <property name="use_underline">True</property>
- <signal name="activate" handler="on_refresh_available_scanners_menu_item_activate"/>
- <child internal-child="image">
- <widget class="GtkImage" id="menu-item-image4">
- <property name="stock">gtk-refresh</property>
+ <child>
+ <widget class="GtkHBox" id="hbox5">
+ <property name="visible">True</property>
+ <property name="spacing">6</property>
+ <child>
+ <widget class="GtkLabel" id="static_page_size_label">
+ <property name="width_request">90</property>
+ <property name="visible">True</property>
+ <property name="xalign">1</property>
+ <property name="label" translatable="yes"><b>Page Size:</b></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="progress_page_size_label">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Letter (TODO)</property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkHBox" id="hbox3">
+ <property name="visible">True</property>
+ <property name="spacing">6</property>
+ <child>
+ <widget class="GtkLabel" id="static_resolution_label">
+ <property name="width_request">90</property>
+ <property name="visible">True</property>
+ <property name="xalign">1</property>
+ <property name="label" translatable="yes"><b>Resolution:</b></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="progress_resolution_label">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">150 DPI</property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
</widget>
+ <packing>
+ <property name="position">2</property>
+ </packing>
</child>
</widget>
</child>
<child>
- <widget class="GtkSeparatorMenuItem" id="separatormenuitem7">
- <property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- </widget>
- </child>
- <child>
- <widget class="GtkImageMenuItem" id="save_as_menu_item">
+ <widget class="GtkVBox" id="vbox4">
<property name="visible">True</property>
- <property name="label" translatable="yes">Save _As...</property>
- <property name="use_underline">True</property>
- <signal name="activate" handler="on_save_as_menu_item_activate"/>
- <accelerator key="S" modifiers="GDK_CONTROL_MASK" signal="activate"/>
- <child internal-child="image">
- <widget class="GtkImage" id="menu-item-image1">
- <property name="stock">gtk-save-as</property>
+ <child>
+ <widget class="GtkProgressBar" id="scan_progressbar">
+ <property name="visible">True</property>
+ <property name="show_text">True</property>
+ <property name="text" translatable="yes">X of Y bytes receieved.</property>
</widget>
+ <packing>
+ <property name="fill">False</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="progress_secondary_label">
+ <property name="visible">True</property>
+ <property name="xalign">0</property>
+ <property name="label" translatable="yes"><i>Scanning page 1 of Z.</i></property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
</child>
</widget>
- </child>
- <child>
- <widget class="GtkSeparatorMenuItem" id="separatormenuitem1">
- <property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- </widget>
- </child>
- <child>
- <widget class="GtkImageMenuItem" id="quit_menu_item">
- <property name="visible">True</property>
- <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
- <property name="label" translatable="yes">gtk-quit</property>
- <property name="use_underline">True</property>
- <property name="use_stock">True</property>
- <signal name="activate" handler="on_quit_menu_item_activate"/>
- </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
</child>
</widget>
+ <packing>
+ <property name="fill">False</property>
+ <property name="position">1</property>
+ </packing>
</child>
</widget>
</child>
<child>
- <widget class="GtkMenuItem" id="menuitem2">
+ <widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
- <property name="label" translatable="yes">_Edit</property>
- <property name="use_underline">True</property>
+ <property name="spacing">12</property>
<child>
- <widget class="GtkMenu" id="menu4">
+ <widget class="GtkButton" id="scan_cancel_button">
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <property name="label" translatable="yes">gtk-cancel</property>
+ <property name="use_stock">True</property>
+ <property name="response_id">0</property>
+ <signal name="clicked" handler="on_scan_cancel_button_clicked"/>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="pack_type">GTK_PACK_END</property>
+ <property name="position">2</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkButton" id="scan_again_button">
<property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <property name="response_id">0</property>
+ <signal name="clicked" handler="on_scan_again_button_clicked"/>
<child>
- <widget class="GtkImageMenuItem" id="delete_menu_item">
+ <widget class="GtkHBox" id="hbox4">
<property name="visible">True</property>
- <property name="label" translatable="yes">gtk-delete</property>
- <property name="use_underline">True</property>
- <property name="use_stock">True</property>
- <signal name="activate" handler="on_delete_menu_item_activate"/>
- <accelerator key="Delete" modifiers="" signal="activate"/>
- </widget>
- </child>
- <child>
+ <child>
+ <widget class="GtkImage" id="image1">
+ <property name="visible">True</property>
+ <property name="icon_name">scanner</property>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="label1">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Scan Again</property>
+ <property name="use_markup">True</property>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="pack_type">GTK_PACK_END</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkButton" id="quick_save_button">
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <property name="response_id">0</property>
+ <signal name="clicked" handler="on_quick_save_button_clicked"/>
+ <child>
+ <widget class="GtkHBox" id="hbox6">
+ <property name="visible">True</property>
+ <child>
+ <widget class="GtkImage" id="image2">
+ <property name="visible">True</property>
+ <property name="stock">gtk-save-as</property>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkLabel" id="label2">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Quick Save</property>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="pack_type">GTK_PACK_END</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ <packing>
+ <property name="fill">False</property>
+ <property name="position">1</property>
+ </packing>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ <widget class="GtkWindow" id="scan_window">
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="title" translatable="yes">NoStaples</property>
+ <property name="window_position">GTK_WIN_POS_CENTER</property>
+ <property name="default_width">600</property>
+ <property name="default_height">400</property>
+ <signal name="destroy" handler="on_scan_window_destroy"/>
+ <signal name="size_allocate" handler="on_scan_window_size_allocate"/>
+ <child>
+ <widget class="GtkVBox" id="vbox1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <child>
+ <widget class="GtkMenuBar" id="menubar1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <child>
+ <widget class="GtkMenuItem" id="menuitem1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="label" translatable="yes">_File</property>
+ <property name="use_underline">True</property>
+ <child>
+ <widget class="GtkMenu" id="menu1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <child>
+ <widget class="GtkImageMenuItem" id="scan_menu_item">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">S_can</property>
+ <property name="use_underline">True</property>
+ <signal name="activate" handler="on_scan_menu_item_activate"/>
+ <child internal-child="image">
+ <widget class="GtkImage" id="menu-item-image2">
+ <property name="visible">True</property>
+ <property name="icon_name">scanner</property>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkImageMenuItem" id="refresh_available_scanners_menu_item">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Refresh Available Scanners</property>
+ <property name="use_underline">True</property>
+ <signal name="activate" handler="on_refresh_available_scanners_menu_item_activate"/>
+ <child internal-child="image">
+ <widget class="GtkImage" id="menu-item-image4">
+ <property name="stock">gtk-refresh</property>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkSeparatorMenuItem" id="separatormenuitem7">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkImageMenuItem" id="save_as_menu_item">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">Save _As...</property>
+ <property name="use_underline">True</property>
+ <signal name="activate" handler="on_save_as_menu_item_activate"/>
+ <accelerator key="S" modifiers="GDK_CONTROL_MASK" signal="activate"/>
+ <child internal-child="image">
+ <widget class="GtkImage" id="menu-item-image1">
+ <property name="stock">gtk-save-as</property>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkSeparatorMenuItem" id="separatormenuitem1">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkImageMenuItem" id="quit_menu_item">
+ <property name="visible">True</property>
+ <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
+ <property name="label" translatable="yes">gtk-quit</property>
+ <property name="use_underline">True</property>
+ <property name="use_stock">True</property>
+ <signal name="activate" handler="on_quit_menu_item_activate"/>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ </widget>
+ </child>
+ <child>
+ <widget class="GtkMenuItem" id="menuitem2">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">_Edit</property>
+ <property name="use_underline">True</property>
+ <child>
+ <widget class="GtkMenu" id="menu4">
+ <property name="visible">True</property>
+ <child>
+ <widget class="GtkImageMenuItem" id="delete_menu_item">
+ <property name="visible">True</property>
+ <property name="label" translatable="yes">gtk-delete</property>
+ <property name="use_underline">True</property>
+ <property name="use_stock">True</property>
+ <signal name="activate" handler="on_delete_menu_item_activate"/>
+ <accelerator key="Delete" modifiers="" signal="activate"/>
+ </widget>
+ </child>
+ <child>
<widget class="GtkSeparatorMenuItem" id="separatormenuitem4">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="preferences_menu_item">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">gtk-preferences</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_preferences_menu_item_activate"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="view_menu">
<property name="visible">True</property>
<property name="label" translatable="yes">_View</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu2">
<property name="visible">True</property>
<child>
<widget class="GtkCheckMenuItem" id="show_toolbar_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Toolbar</property>
<property name="use_underline">True</property>
<property name="active">True</property>
<signal name="toggled" handler="on_show_toolbar_menu_item_toggled"/>
</widget>
</child>
<child>
<widget class="GtkCheckMenuItem" id="show_statusbar_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Statusbar</property>
<property name="use_underline">True</property>
<property name="active">True</property>
<signal name="toggled" handler="on_show_statusbar_menu_item_toggled"/>
</widget>
</child>
<child>
<widget class="GtkCheckMenuItem" id="show_thumbnails_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">Thumb_nails</property>
<property name="use_underline">True</property>
<property name="active">True</property>
<signal name="toggled" handler="on_show_thumbnails_menu_item_toggled"/>
</widget>
</child>
<child>
<widget class="GtkCheckMenuItem" id="show_adjustments_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Adjustments</property>
<property name="use_underline">True</property>
<signal name="toggled" handler="on_show_adjustments_menu_item_toggled"/>
</widget>
</child>
<child>
<widget class="GtkSeparatorMenuItem" id="separatormenuitem5">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="zoom_in_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-zoom-in</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_zoom_in_menu_item_activate"/>
<accelerator key="plus" modifiers="GDK_CONTROL_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="zoom_out_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-zoom-out</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_zoom_out_menu_item_activate"/>
<accelerator key="minus" modifiers="GDK_CONTROL_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="zoom_one_to_one_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-zoom-100</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_zoom_one_to_one_menu_item_activate"/>
<accelerator key="1" modifiers="GDK_CONTROL_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="zoom_best_fit_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-zoom-fit</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_zoom_best_fit_menu_item_activate"/>
<accelerator key="F" modifiers="GDK_CONTROL_MASK" signal="activate"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="menuitem9">
<property name="visible">True</property>
<property name="label" translatable="yes">_Tools</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu6">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="rotate_clockwise_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Rotate Clockwise</property>
<property name="use_underline">True</property>
<signal name="activate" handler="on_rotate_clockwise_menu_item_activate"/>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="rotate_counter_clockwise_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">Rotate _Counterclockwise</property>
<property name="use_underline">True</property>
<signal name="activate" handler="on_rotate_counter_clockwise_menu_item_activate"/>
</widget>
</child>
<child>
<widget class="GtkCheckMenuItem" id="rotate_all_pages_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">Apply rotation to all _pages?</property>
<property name="use_underline">True</property>
<signal name="toggled" handler="on_rotate_all_pages_menu_item_toggled"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="options_menu">
<property name="visible">True</property>
<property name="label" translatable="yes">_Options</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu7">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="scanner_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Scanner</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="scanner_sub_menu">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="menuitem5">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="label" translatable="yes">None</property>
<property name="use_underline">True</property>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="scan_mode_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Mode</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="scan_mode_sub_menu">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="menuitem8">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="label" translatable="yes">None</property>
<property name="use_underline">True</property>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="scan_resolution_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Resolution</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="scan_resolution_sub_menu">
<property name="visible">True</property>
<child>
<widget class="GtkMenuItem" id="menuitem10">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="label" translatable="yes">None</property>
<property name="use_underline">True</property>
</widget>
</child>
</widget>
</child>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="menuitem3">
<property name="visible">True</property>
<property name="label" translatable="yes">_Go</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu5">
<property name="visible">True</property>
<child>
<widget class="GtkImageMenuItem" id="go_first_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-goto-first</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_go_first_menu_item_activate"/>
<accelerator key="Home" modifiers="" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="go_previous_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-go-back</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_go_previous_menu_item_activate"/>
<accelerator key="Left" modifiers="GDK_MOD1_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="go_next_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-go-forward</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_go_next_menu_item_activate"/>
<accelerator key="Right" modifiers="GDK_MOD1_MASK" signal="activate"/>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="go_last_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">gtk-goto-last</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_go_last_menu_item_activate"/>
<accelerator key="End" modifiers="" signal="activate"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkMenuItem" id="menuitem4">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">_Help</property>
<property name="use_underline">True</property>
<child>
<widget class="GtkMenu" id="menu3">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<child>
<widget class="GtkImageMenuItem" id="contents_menu_item">
<property name="visible">True</property>
<property name="label" translatable="yes">_Contents</property>
<property name="use_underline">True</property>
<accelerator key="F1" modifiers="" signal="activate"/>
<child internal-child="image">
<widget class="GtkImage" id="menu-item-image3">
<property name="visible">True</property>
<property name="stock">gtk-help</property>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkImageMenuItem" id="about_menu_item">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">gtk-about</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
<signal name="activate" handler="on_about_menu_item_activate"/>
</widget>
</child>
</widget>
</child>
</widget>
</child>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkToolbar" id="main_toolbar">
<property name="visible">True</property>
<property name="toolbar_style">GTK_TOOLBAR_BOTH_HORIZ</property>
<property name="icon_size">GTK_ICON_SIZE_SMALL_TOOLBAR</property>
<child>
<widget class="GtkToolButton" id="scan_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Scan</property>
<property name="icon_name">scanner</property>
<signal name="clicked" handler="on_scan_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="refresh_available_scanners_button">
<property name="visible">True</property>
<property name="stock_id">gtk-refresh</property>
<signal name="clicked" handler="on_refresh_available_scanners_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="save_as_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Save As...</property>
<property name="icon_name">document-save-as</property>
<signal name="clicked" handler="on_save_as_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkSeparatorToolItem" id="toolbutton1">
<property name="visible">True</property>
</widget>
</child>
<child>
<widget class="GtkToolButton" id="zoom_in_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Zoom In</property>
<property name="icon_name">zoom-in</property>
<signal name="clicked" handler="on_zoom_in_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="zoom_out_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Zoom Out</property>
<property name="icon_name">zoom-out</property>
<signal name="clicked" handler="on_zoom_out_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="zoom_one_to_one_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Normal Size</property>
<property name="icon_name">zoom-original</property>
<signal name="clicked" handler="on_zoom_one_to_one_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="zoom_best_fit_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Best Fit</property>
<property name="icon_name">zoom-fit-best</property>
<signal name="clicked" handler="on_zoom_best_fit_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkSeparatorToolItem" id="toolbutton2">
<property name="visible">True</property>
</widget>
</child>
<child>
<widget class="GtkToolButton" id="rotate_counter_clockwise_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Rotate Counterclockwise</property>
<property name="icon_name">object-rotate-left</property>
<signal name="clicked" handler="on_rotate_counter_clockwise_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="rotate_clockwise_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Rotate Clockwise</property>
<property name="icon_name">object-rotate-right</property>
<signal name="clicked" handler="on_rotate_clockwise_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkSeparatorToolItem" id="toolbutton4">
<property name="visible">True</property>
</widget>
</child>
<child>
<widget class="GtkToolButton" id="go_first_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">First</property>
<property name="stock_id">gtk-goto-first</property>
<signal name="clicked" handler="on_go_first_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="go_previous_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Back</property>
<property name="stock_id">gtk-go-back</property>
<signal name="clicked" handler="on_go_previous_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="go_next_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Forward</property>
<property name="stock_id">gtk-go-forward</property>
<signal name="clicked" handler="on_go_next_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<widget class="GtkToolButton" id="go_last_button">
<property name="visible">True</property>
<property name="tooltip" translatable="yes">Last</property>
<property name="stock_id">gtk-goto-last</property>
<signal name="clicked" handler="on_go_last_button_clicked"/>
</widget>
<packing>
<property name="homogeneous">True</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkViewport" id="document_view_docking_viewport">
<property name="visible">True</property>
<property name="resize_mode">GTK_RESIZE_QUEUE</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkViewport" id="status_view_docking_viewport">
<property name="visible">True</property>
<property name="resize_mode">GTK_RESIZE_QUEUE</property>
<property name="shadow_type">GTK_SHADOW_NONE</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">3</property>
</packing>
</child>
</widget>
</child>
</widget>
- <widget class="GtkWindow" id="progress_window">
- <property name="width_request">400</property>
- <property name="height_request">200</property>
- <property name="title" translatable="yes">Scan in progress...</property>
- <property name="resizable">False</property>
- <property name="modal">True</property>
- <property name="window_position">GTK_WIN_POS_CENTER</property>
- <property name="destroy_with_parent">True</property>
- <property name="icon_name">scanner</property>
- <property name="type_hint">GDK_WINDOW_TYPE_HINT_DIALOG</property>
- <property name="skip_taskbar_hint">True</property>
- <property name="skip_pager_hint">True</property>
- <property name="transient_for">scan_window</property>
- <signal name="delete_event" handler="on_progress_window_delete_event"/>
- <child>
- <widget class="GtkAlignment" id="alignment1">
- <property name="visible">True</property>
- <property name="top_padding">12</property>
- <property name="bottom_padding">12</property>
- <property name="left_padding">12</property>
- <property name="right_padding">12</property>
- <child>
- <widget class="GtkVBox" id="vbox2">
- <property name="visible">True</property>
- <property name="spacing">12</property>
- <child>
- <widget class="GtkVBox" id="vbox3">
- <property name="visible">True</property>
- <property name="spacing">12</property>
- <child>
- <widget class="GtkLabel" id="progress_primary_label">
- <property name="visible">True</property>
- <property name="xalign">0</property>
- <property name="label" translatable="yes"><big><b>Scan in progress...</b></big></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkVBox" id="vbox4">
- <property name="visible">True</property>
- <property name="spacing">12</property>
- <child>
- <widget class="GtkVBox" id="vbox3">
- <property name="visible">True</property>
- <child>
- <widget class="GtkHBox" id="hbox2">
- <property name="visible">True</property>
- <property name="spacing">6</property>
- <child>
- <widget class="GtkLabel" id="static_mode_label">
- <property name="width_request">90</property>
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes"><b>Mode:</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="progress_mode_label">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Color</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkHBox" id="hbox5">
- <property name="visible">True</property>
- <property name="spacing">6</property>
- <child>
- <widget class="GtkLabel" id="static_page_size_label">
- <property name="width_request">90</property>
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes"><b>Page Size:</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="progress_page_size_label">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Letter (TODO)</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- <child>
- <widget class="GtkHBox" id="hbox3">
- <property name="visible">True</property>
- <property name="spacing">6</property>
- <child>
- <widget class="GtkLabel" id="static_resolution_label">
- <property name="width_request">90</property>
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes"><b>Resolution:</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="progress_resolution_label">
- <property name="visible">True</property>
- <property name="label" translatable="yes">150 DPI</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="position">2</property>
- </packing>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkVBox" id="vbox4">
- <property name="visible">True</property>
- <child>
- <widget class="GtkProgressBar" id="scan_progressbar">
- <property name="visible">True</property>
- <property name="show_text">True</property>
- <property name="text" translatable="yes">X of Y bytes receieved.</property>
- </widget>
- <packing>
- <property name="fill">False</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="progress_secondary_label">
- <property name="visible">True</property>
- <property name="xalign">0</property>
- <property name="label" translatable="yes"><i>Scanning page 1 of Z.</i></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="fill">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkHBox" id="hbox1">
- <property name="visible">True</property>
- <property name="spacing">12</property>
- <child>
- <widget class="GtkButton" id="scan_cancel_button">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <property name="label" translatable="yes">gtk-cancel</property>
- <property name="use_stock">True</property>
- <property name="response_id">0</property>
- <signal name="clicked" handler="on_scan_cancel_button_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="pack_type">GTK_PACK_END</property>
- <property name="position">2</property>
- </packing>
- </child>
- <child>
- <widget class="GtkButton" id="scan_again_button">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <property name="response_id">0</property>
- <signal name="clicked" handler="on_scan_again_button_clicked"/>
- <child>
- <widget class="GtkHBox" id="hbox4">
- <property name="visible">True</property>
- <child>
- <widget class="GtkImage" id="image1">
- <property name="visible">True</property>
- <property name="icon_name">scanner</property>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="label1">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Scan Again</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="pack_type">GTK_PACK_END</property>
- <property name="position">1</property>
- </packing>
- </child>
- <child>
- <widget class="GtkButton" id="quick_save_button">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <property name="response_id">0</property>
- <signal name="clicked" handler="on_quick_save_button_clicked"/>
- <child>
- <widget class="GtkHBox" id="hbox6">
- <property name="visible">True</property>
- <child>
- <widget class="GtkImage" id="image2">
- <property name="visible">True</property>
- <property name="stock">gtk-save-as</property>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="label2">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Quick Save</property>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="pack_type">GTK_PACK_END</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="fill">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- </child>
- </widget>
</glade-interface>
diff --git a/utils/gtkexcepthook.py b/utils/gtkexcepthook.py
index 7876f13..f0e8f3d 100644
--- a/utils/gtkexcepthook.py
+++ b/utils/gtkexcepthook.py
@@ -1,169 +1,169 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
# This module is based on:
# gtkexcepthook.py
# from http://blog.sysfs.net/archives/35-PyGTK-exception-handler.html
# which carries the following copyright notice:
# (c) 2003 Gustavo J A M Carneiro gjc at inescporto.pt
# 2004-2005 Filip Van Raemdonck
# http://www.daa.com.au/pipermail/pygtk/2003-August/005775.html
# Message-ID: <[email protected]>
# "The license is whatever you want."
"""
This module contains a replacement sys.excepthook which informs the
user of the error via a GTK dialog and allows them to control
whether or not the application exits.
"""
from cStringIO import StringIO
import inspect
import linecache
import logging
import pydoc
import sys
import traceback
import gtk
import pango
import pygtk
pygtk.require ('2.0')
def lookup (name, frame, lcls):
"""
Find the value for a given name in a given frame.
This function is unmodified from Filip Van Raemdonck's
version.
"""
if name in lcls:
return 'local', lcls[name]
elif name in frame.f_globals:
return 'global', frame.f_globals[name]
elif '__builtins__' in frame.f_globals:
builtins = frame.f_globals['__builtins__']
if type (builtins) is dict:
if name in builtins:
return 'builtin', builtins[name]
else:
if hasattr (builtins, name):
return 'builtin', getattr (builtins, name)
return None, []
def analyse (exctyp, value, tb):
"""
Create a text representation of an exception traceback.
This function is unmodified from Filip Van Raemdonck's
version.
"""
import tokenize, keyword
trace = StringIO()
nlines = 3
frecs = inspect.getinnerframes (tb, nlines)
trace.write ('Traceback (most recent call last):\n')
for frame, fname, lineno, funcname, context, cindex in frecs:
trace.write (' File "%s", line %d, ' % (fname, lineno))
args, varargs, varkw, lcls = inspect.getargvalues (frame)
def readline (lno=[lineno], *args):
if args: print args
try: return linecache.getline (fname, lno[0])
finally: lno[0] += 1
all, prev, name, scope = {}, None, '', None
for ttype, tstr, stup, etup, line in tokenize.generate_tokens (readline):
if ttype == tokenize.NAME and tstr not in keyword.kwlist:
if name:
if name[-1] == '.':
try:
val = getattr (prev, tstr)
except AttributeError:
# XXX skip the rest of this identifier only
break
name += tstr
else:
assert not name and not scope
scope, val = lookup (tstr, frame, lcls)
name = tstr
if val:
prev = val
#print ' found', scope, 'name', name, 'val', val, 'in', prev, 'for token', tstr
elif tstr == '.':
if prev:
name += '.'
else:
if name:
all[name] = (scope, prev)
prev, name, scope = None, '', None
if ttype == tokenize.NEWLINE:
break
trace.write (funcname +
inspect.formatargvalues (args, varargs, varkw, lcls, formatvalue=lambda v: '=' + pydoc.text.repr (v)) + '\n')
trace.write (''.join ([' ' + x.replace ('\t', ' ') for x in filter (lambda a: a.strip(), context)]))
if len (all):
trace.write (' variables: %s\n' % str (all))
trace.write ('%s: %s' % (exctyp.__name__, value))
return trace
def _gtkexcepthook(exception_type, instance, traceback):
"""
Display a GTK dialog informing the user that an unhandled
exception has occurred. Log the exception and provide the
option to continue or quit.
TODO: Should have a way to report bugs.
"""
trace_log = trace = analyse(exception_type, instance, traceback)
log = logging.getLogger("gtkexcepthook")
log.error("%s caught. Traceback follows \n%s" %
(exception_type, trace_log.getvalue()))
dialog = gtk.MessageDialog(
parent=None, flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_NONE)
dialog.set_title("")
# TODO: is this needed?
if gtk.check_version (2, 4, 0) is not None:
dialog.set_has_separator (False)
primary = "<big><b>An unhandled exception has been logged.</b></big>"
secondary = "It may be possible to continue normally, or you may choose to exit NoStaples and restart."
dialog.set_markup(primary)
dialog.format_secondary_text(secondary)
dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
dialog.add_button(gtk.STOCK_QUIT, 1)
response = dialog.run()
-
+
if response == 1 and gtk.main_level() > 0:
gtk.main_quit()
else:
pass
-
+
dialog.destroy()
sys.excepthook = _gtkexcepthook
\ No newline at end of file
diff --git a/utils/scanning.py b/utils/scanning.py
index 4c41251..76386dc 100644
--- a/utils/scanning.py
+++ b/utils/scanning.py
@@ -1,240 +1,224 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains those functions (in the form of Thread objects)
that interface with scanning hardware via SANE.
"""
import commands
import logging
import os
import re
import tempfile
import threading
import gobject
from nostaples import constants
import saneme
class IdleObject(gobject.GObject):
"""
Override gobject.GObject to always emit signals in the main thread
by emitting on an idle handler.
This class is based on an example by John Stowers:
U{http://www.johnstowers.co.nz/blog/index.php/tag/pygtk/}
"""
def __init__(self):
gobject.GObject.__init__(self)
def emit(self, *args):
- gobject.idle_add(gobject.GObject.emit,self,*args)
+ gobject.idle_add(gobject.GObject.emit, self, *args)
+def abort_on_exception(func):
+ """
+ This function decorator wraps the run() method of a thread
+ so that any exceptions in that thread will be logged and
+ cause the threads 'abort' signal to be emitted with the exception
+ as an argument. This way all exception handling can occur
+ on the main thread.
+ """
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except Exception, e:
+ thread_object = args[0]
+ thread_object.log.error('Exception type %s: %s' % (e.__class__.__name__, e.message))
+ thread_object.emit('aborted', e)
+ return wrapper
+
class UpdateAvailableScannersThread(IdleObject, threading.Thread):
"""
Responsible for getting an updated list of available scanners
and passing it back to the main thread.
"""
__gsignals__ = {
- "finished": (
- gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT]),
+ 'finished': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
+ 'aborted': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane = sane
self.log.debug('Created.')
+ @abort_on_exception
def run(self):
"""
Queries SANE for a list of connected scanners and updates
the list of available scanners from the results.
"""
self.log.debug('Updating available scanners.')
- try:
- devices = self.sane.get_device_list()
- except saneme.SaneOutOfMemoryError:
- # TODO
- raise
- except saneme.SaneUnknownError:
- # TODO
- raise
+ devices = self.sane.get_device_list()
# NB: We callback with the lists so that they can updated on the main thread
- self.emit("finished", devices)
+ self.emit('finished', devices)
class ScanningThread(IdleObject, threading.Thread):
"""
Responsible for scanning a page and emitting status
callbacks on the main thread.
This thread should treat its reference to the ScanningModel
as read-only. That way we don't have to worry about making
the Model thread-safe.
"""
__gsignals__ = {
- "progress": (
+ 'progress': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)),
- "succeeded": (
+ 'succeeded': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
+ 'failed': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)),
+ 'aborted': (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
- "failed": (
- gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,))
}
- # TODO: add cancel event
-
def __init__(self, sane_device, mode, resolution):
"""
Initialize the thread and get a tempfile name that
will house the scanned image.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.mode = mode
self.resolution = resolution
self.cancel_event = threading.Event()
def progress_callback(self, scan_info, bytes_scanned):
"""
Pass the progress information on the the main thread
and cancel the scan if the cancel event has been set.
"""
self.emit("progress", scan_info, bytes_scanned)
if self.cancel_event.isSet():
return True
else:
return False
+ @abort_on_exception
def run(self):
"""
Set scanner options, scan a page and emit status callbacks.
"""
- assert self.sane_device.is_open()
-
+ if not self.sane_device.is_open():
+ raise AssertionError('sane_device.is_open() returned false')
+
self.log.debug('Setting device options.')
- # TODO: handle exceptions
try:
self.sane_device.options['mode'].value = self.mode
- except saneme.SaneIOError:
- raise
- except saneme.SaneOutOfMemoryError:
- raise
- except saneme.SaneAccessDeniedError:
- raise
- except saneme.SaneUnknownError:
- raise
except saneme.SaneReloadOptionsError:
+ # TODO
pass
-
- # TODO: handle exceptions
+
try:
self.sane_device.options['resolution'].value = int(self.resolution)
- except saneme.SaneIOError:
- raise
- except saneme.SaneOutOfMemoryError:
- raise
- except saneme.SaneAccessDeniedError:
- raise
- except saneme.SaneUnknownError:
- raise
except saneme.SaneReloadOptionsError:
+ # TODO
pass
self.log.debug('Beginning scan.')
pil_image = None
-
- # TODO: handle exceptions
- try:
- pil_image = self.sane_device.scan(self.progress_callback)
- except saneme.SaneDeviceBusyError:
- raise
- except saneme.SaneDeviceJammedError:
- raise
- except saneme.SaneNoDocumentsError:
- raise
- except saneme.SaneCoverOpenError:
- raise
- except saneme.SaneIOError:
- raise
- except saneme.SaneOutOfMemoryError:
- raise
- except saneme.SaneInvalidDataError:
- raise
- except saneme.SaneUnknownError:
- raise
+ pil_image = self.sane_device.scan(self.progress_callback)
if self.cancel_event.isSet():
self.emit("failed", "Scan cancelled")
else:
- assert pil_image is not None
- self.emit("succeeded", pil_image)
+ if not pil_image:
+ raise AssertionError('sane_device.scan() returned None')
+ self.emit('succeeded', pil_image)
class UpdateScannerOptionsThread(IdleObject, threading.Thread):
"""
Responsible for getting an up-to-date list of valid scanner options
and passing it back to the main thread.
"""
__gsignals__ = {
- "finished": (
- gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT]),
+ 'finished': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
+ 'aborted': (
+ gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, sane_device):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.log.debug('Created.')
+ @abort_on_exception
def run(self):
"""
Queries SANE for a list of available options for the specified scanner.
"""
assert self.sane_device.is_open()
self.log.debug('Updating scanner options.')
mode_list = self.sane_device.options['mode'].constraint
resolution_list = [str(i) for i in self.sane_device.options['resolution'].constraint]
# NB: We callback with the lists so that they can updated on the main thread
- self.emit("finished", mode_list, resolution_list)
\ No newline at end of file
+ self.emit('finished', mode_list, resolution_list)
\ No newline at end of file
|
onyxfish/nostaples
|
3827069035602f06a7cbc3b32beb054a94f54f3c
|
Cleanup prior to merge into mainline and 0.3 release.
|
diff --git a/gui/document_view.glade b/gui/document_view.glade
index ac86d61..9fcecb0 100644
--- a/gui/document_view.glade
+++ b/gui/document_view.glade
@@ -1,204 +1,204 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--Generated with glade3 3.4.5 on Sat Jan 17 09:21:17 2009 -->
+<!--Generated with glade3 3.4.5 on Mon Feb 16 08:23:41 2009 -->
<glade-interface>
<widget class="GtkWindow" id="dummy_document_view_window">
<child>
<widget class="GtkHBox" id="document_view_horizontal_box">
<property name="visible">True</property>
<child>
<widget class="GtkScrolledWindow" id="thumbnails_scrolled_window">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="hscrollbar_policy">GTK_POLICY_NEVER</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkViewport" id="page_view_docking_viewport">
<property name="visible">True</property>
<property name="resize_mode">GTK_RESIZE_QUEUE</property>
<property name="shadow_type">GTK_SHADOW_NONE</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkAlignment" id="adjustments_alignment">
<property name="no_show_all">True</property>
<property name="top_padding">6</property>
<property name="bottom_padding">6</property>
<property name="left_padding">6</property>
<property name="right_padding">6</property>
<child>
<widget class="GtkVBox" id="vbox4">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="spacing">6</property>
<child>
<widget class="GtkVBox" id="vbox5">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<child>
<widget class="GtkLabel" id="brightness_label">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">Brightness:</property>
</widget>
<packing>
- <property name="expand">False</property>
+ <property name="fill">False</property>
</packing>
</child>
<child>
<widget class="GtkHScale" id="brightness_scale">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="can_focus">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="update_policy">GTK_UPDATE_DELAYED</property>
<property name="adjustment">1 0 2 0.5 1 0</property>
<property name="restrict_to_fill_level">False</property>
<property name="fill_level">0</property>
<property name="value_pos">GTK_POS_LEFT</property>
<signal name="value_changed" handler="on_brightness_scale_value_changed"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">1</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
</packing>
</child>
<child>
<widget class="GtkVBox" id="vbox6">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<child>
<widget class="GtkLabel" id="contrast_label">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">Contrast:</property>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
</packing>
</child>
<child>
<widget class="GtkHScale" id="contrast_scale">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="can_focus">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="update_policy">GTK_UPDATE_DELAYED</property>
<property name="adjustment">1 0 2 0.5 1 0</property>
<property name="restrict_to_fill_level">False</property>
<property name="fill_level">0</property>
<property name="value_pos">GTK_POS_LEFT</property>
<signal name="value_changed" handler="on_contrast_scale_value_changed"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">1</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkVBox" id="vbox7">
<property name="visible">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<child>
<widget class="GtkLabel" id="sharpness_label">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="label" translatable="yes">Sharpness:</property>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
</packing>
</child>
<child>
<widget class="GtkHScale" id="sharpness_scale">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="can_focus">True</property>
<property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
<property name="update_policy">GTK_UPDATE_DELAYED</property>
<property name="adjustment">1 0 2 0.5 1 0</property>
<property name="restrict_to_fill_level">False</property>
<property name="fill_level">0</property>
<property name="value_pos">GTK_POS_LEFT</property>
<signal name="value_changed" handler="on_sharpness_scale_value_changed"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">1</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkHBox" id="hbox4">
<property name="visible">True</property>
<property name="homogeneous">True</property>
<child>
<widget class="GtkCheckButton" id="adjust_all_pages_check">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="can_focus">True</property>
<property name="label" translatable="yes">Apply to all pages?</property>
<property name="response_id">0</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_adjust_all_pages_check_toggled"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">3</property>
</packing>
</child>
</widget>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="pack_type">GTK_PACK_END</property>
<property name="position">2</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
diff --git a/models/main.py b/models/main.py
index 5626f72..10e8371 100644
--- a/models/main.py
+++ b/models/main.py
@@ -1,390 +1,416 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module holds the MainModel, which manages general application
data.
"""
import logging
from gtkmvc.model import Model
from nostaples import constants
import saneme
class MainModel(Model):
"""
Handles data all data not specifically handled by another Model
(e.g. the state of the main application window).
Note: active_scanner is a tuple in the format (display_name,
sane_name). available_scanners is a list of such tuples.
"""
__properties__ = \
{
'show_toolbar' : True,
'show_statusbar' : True,
'show_thumbnails' : True,
'show_adjustments' : False,
'rotate_all_pages' : False,
'active_scanner' : None, # saneme.Device
'active_mode' : None,
'active_resolution' : None,
'available_scanners' : [], # [] of saneme.Device
'valid_modes' : [],
'valid_resolutions' : [],
'scan_in_progress' : False,
'updating_available_scanners' : False,
'updating_scan_options' : False,
}
def __init__(self, application):
"""
Constructs the MainModel, as well as necessary sub-models.
"""
self.application = application
Model.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.log.debug('Created.')
def load_state(self):
"""
Load persisted state from the self.state_manager.
"""
state_manager = self.application.get_state_manager()
sane = self.application.get_sane()
self.show_toolbar = state_manager.init_state(
'show_toolbar', constants.DEFAULT_SHOW_TOOLBAR,
self.state_show_toolbar_change)
self.show_statusbar = state_manager.init_state(
'show_statusbar', constants.DEFAULT_SHOW_STATUSBAR,
self.state_show_statusbar_change)
self.show_thumbnails = state_manager.init_state(
'show_thumbnails', constants.DEFAULT_SHOW_THUMBNAILS,
self.state_show_thumbnails_change)
self.show_adjustments = state_manager.init_state(
'show_adjustments', constants.DEFAULT_SHOW_ADJUSTMENTS,
self.state_show_adjustments_change)
self.rotate_all_pages = state_manager.init_state(
'rotate_all_pages', constants.DEFAULT_ROTATE_ALL_PAGES,
self.state_rotate_all_pages_change)
# The local representation of active_scanner is a
# saneme.Device, but it is persisted by its name attribute only.
try:
self.active_scanner = sane.get_device_by_name(
state_manager.init_state(
'active_scanner', constants.DEFAULT_ACTIVE_SCANNER,
self.state_active_scanner_change))
except saneme.SaneNoSuchDeviceError:
self.active_scanner = None
self.active_mode = state_manager.init_state(
'scan_mode', constants.DEFAULT_SCAN_MODE,
self.state_scan_mode_change)
self.active_resolution = state_manager.init_state(
'scan_resolution', constants.DEFAULT_SCAN_RESOLUTION,
self.state_scan_resolution_change)
# Property setters
# (see gtkmvc.support.metaclass_base.py for the origin of these accessors)
def set_prop_show_toolbar(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_show_toolbar
if old_value == value:
return
self._prop_show_toolbar = value
self.application.get_state_manager()['show_toolbar'] = value
self.notify_property_value_change(
'show_toolbar', old_value, value)
def set_prop_show_statusbar(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_show_statusbar
if old_value == value:
return
self._prop_show_statusbar = value
self.application.get_state_manager()['show_statusbar'] = value
self.notify_property_value_change(
'show_statusbar', old_value, value)
def set_prop_show_thumbnails(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_show_thumbnails
if old_value == value:
return
self._prop_show_thumbnails = value
self.application.get_state_manager()['show_thumbnails'] = value
self.notify_property_value_change(
'show_thumbnails', old_value, value)
def set_prop_show_adjustments(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_show_adjustments
if old_value == value:
return
self._prop_show_adjustments = value
self.application.get_state_manager()['show_adjustments'] = value
self.notify_property_value_change(
'show_adjustments', old_value, value)
def set_prop_rotate_all_pages(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_rotate_all_pages
if old_value == value:
return
self._prop_rotate_all_pages = value
self.application.get_state_manager()['rotate_all_pages'] = value
self.notify_property_value_change(
'rotate_all_pages', old_value, value)
def set_prop_active_scanner(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
# Ignore spurious updates
old_value = self._prop_active_scanner
if old_value == value:
return
# Close the old scanner
old_value.close()
if value is not None:
assert isinstance(value, saneme.Device)
# Update the internal property variable
self._prop_active_scanner = value
# Only persist the state if the new value is not None
# This prevents problems with trying to store a Null
# value in the state backend and also allows for smooth
# transitions if a scanner is disconnected and reconnected.
if value is not None:
self.application.get_state_manager()['active_scanner'] = value.name
- value.open()
+
+ # TODO: handle exceptions
+ try:
+ value.open()
+ except saneme.SaneDeviceBusyError:
+ raise
+ except saneme.SaneIOError:
+ raise
+ except saneme.SaneOutOfMemoryError:
+ raise
+ except saneme.SaneAccessDeniedError:
+ raise
+ except saneme.SaneUnknownError:
+ raise
# Emit the property change notification to all observers.
self.notify_property_value_change(
'active_scanner', old_value, value)
def set_prop_active_mode(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_active_mode
if old_value == value:
return
self._prop_active_mode = value
if value is not None:
self.application.get_state_manager()['scan_mode'] = value
self.notify_property_value_change(
'active_mode', old_value, value)
def set_prop_active_resolution(self, value):
"""
Write state.
See L{set_prop_active_scanner} for detailed comments.
"""
old_value = self._prop_active_resolution
if old_value == value:
return
self._prop_active_resolution = value
if value is not None:
self.application.get_state_manager()['scan_resolution'] = value
self.notify_property_value_change(
'active_resolution', old_value, value)
def set_prop_available_scanners(self, value):
"""
Set the list of available scanners, updating the active_scanner
if it is no longer in the list.
"""
old_value = self._prop_available_scanners
if len(value) == 0:
self._prop_active_scanner = None
else:
# Select the first available scanner if the previously
# selected scanner is not in the new list
# We avoid the active_scanner property setter so that
# The property notification callbacks will not be fired
# until after the menu has been updated.
if self._prop_active_scanner not in value:
self._prop_active_scanner = value[0]
self.application.get_state_manager()['active_scanner'] = \
value[0].name
- self._prop_active_scanner.open()
+
+ # TODO: handle exceptions
+ try:
+ self._prop_active_scanner.open()
+ except saneme.SaneDeviceBusyError:
+ raise
+ except saneme.SaneIOError:
+ raise
+ except saneme.SaneOutOfMemoryError:
+ raise
+ except saneme.SaneAccessDeniedError:
+ raise
+ except saneme.SaneUnknownError:
+ raise
# Otherwise maintain current selection
else:
pass
self._prop_available_scanners = value
# This will only actually cause an update if
# old_value != value
self.notify_property_value_change(
'available_scanners', old_value, value)
# Force the scanner options to update, even if the active
# scanner did not change. This is necessary in case the
# current value was loaded from state, in which case the
# options will not yet have been loaded).
self.notify_property_value_change(
'active_scanner', None, self._prop_active_scanner)
def set_prop_valid_modes(self, value):
"""
Set the list of valid scan modes, updating the active_mode
if it is no longer in the list.
See L{set_prop_available_scanners} for detailed comments.
"""
old_value = self._prop_valid_modes
if len(value) == 0:
self._prop_active_mode = None
else:
if self._prop_active_mode not in value:
self._prop_active_mode = value[0]
self.application.get_state_manager()['scan_mode'] = value[0]
else:
pass
self._prop_valid_modes = value
self.notify_property_value_change(
'valid_modes', old_value, value)
self.notify_property_value_change(
'active_mode', None, self._prop_active_mode)
def set_prop_valid_resolutions(self, value):
"""
Set the list of valid scan resolutions, updating the
active_resolution if it is no longer in the list.
See L{set_prop_available_scanners} for detailed comments.
"""
old_value = self._prop_valid_resolutions
if len(value) == 0:
self._prop_active_resolution = None
else:
if self._prop_active_resolution not in value:
self._prop_active_resolution = value[0]
self.application.get_state_manager()['scan_resolution'] = \
value[0]
else:
pass
self._prop_valid_resolutions = value
self.notify_property_value_change(
'valid_resolutions', old_value, value)
self.notify_property_value_change(
'active_resolution', None, self._prop_active_resolution)
# STATE CALLBACKS
def state_show_toolbar_change(self):
"""Read state."""
self.show_toolbar = \
self.application.get_state_manager()['show_toolbar']
def state_show_statusbar_change(self):
"""Read state."""
self.show_statusbar = \
self.application.get_state_manager()['show_statusbar']
def state_show_thumbnails_change(self):
"""Read state."""
self.show_thumbnails = \
self.application.get_state_manager()['show_thumbnails']
def state_show_adjustments_change(self):
"""Read state."""
self.show_adjustments = \
self.application.get_state_manager()['show_adjustments']
def state_rotate_all_pages_change(self):
"""Read state."""
self.rotate_all_pages = \
self.application.get_state_manager()['rotate_all_pages']
def state_active_scanner_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
sane = self.application.get_sane()
if state_manager['active_scanner'] in self.available_scanners:
try:
self.active_scanner = sane.get_device_by_name(state_manager['active_scanner'])
except SaneNoSuchDeviceError:
raise
else:
state_manager['active_scanner'] = self.active_scanner.name
def state_scan_mode_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
if state_manager['scan_mode'] in self.valid_modes:
self.active_mode = state_manager['scan_mode']
else:
state_manager['scan_mode'] = self.active_mode
def state_scan_resolution_change(self):
"""Read state, validating the input."""
state_manager = self.application.get_state_manager()
if state_manager['scan_resolution'] in self.valid_resolutions:
self.active_resolution = state_manager['scan_resolution']
else:
state_manager['scan_resolution'] = self.active_resolution
\ No newline at end of file
diff --git a/utils/scanning.py b/utils/scanning.py
index 34c2ecb..4c41251 100644
--- a/utils/scanning.py
+++ b/utils/scanning.py
@@ -1,210 +1,240 @@
#!/usr/bin/python
#~ This file is part of NoStaples.
#~ NoStaples is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ NoStaples 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 NoStaples. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains those functions (in the form of Thread objects)
that interface with scanning hardware via SANE.
"""
import commands
import logging
import os
import re
import tempfile
import threading
import gobject
from nostaples import constants
import saneme
class IdleObject(gobject.GObject):
"""
Override gobject.GObject to always emit signals in the main thread
by emitting on an idle handler.
This class is based on an example by John Stowers:
U{http://www.johnstowers.co.nz/blog/index.php/tag/pygtk/}
"""
def __init__(self):
gobject.GObject.__init__(self)
def emit(self, *args):
gobject.idle_add(gobject.GObject.emit,self,*args)
class UpdateAvailableScannersThread(IdleObject, threading.Thread):
"""
Responsible for getting an updated list of available scanners
and passing it back to the main thread.
"""
__gsignals__ = {
"finished": (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT]),
}
def __init__(self, sane):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane = sane
self.log.debug('Created.')
def run(self):
"""
Queries SANE for a list of connected scanners and updates
the list of available scanners from the results.
"""
self.log.debug('Updating available scanners.')
try:
devices = self.sane.get_device_list()
except saneme.SaneOutOfMemoryError:
# TODO
raise
except saneme.SaneUnknownError:
# TODO
raise
# NB: We callback with the lists so that they can updated on the main thread
self.emit("finished", devices)
class ScanningThread(IdleObject, threading.Thread):
"""
Responsible for scanning a page and emitting status
callbacks on the main thread.
This thread should treat its reference to the ScanningModel
as read-only. That way we don't have to worry about making
the Model thread-safe.
"""
__gsignals__ = {
"progress": (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)),
"succeeded": (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"failed": (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,))
}
# TODO: add cancel event
def __init__(self, sane_device, mode, resolution):
"""
Initialize the thread and get a tempfile name that
will house the scanned image.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.mode = mode
self.resolution = resolution
self.cancel_event = threading.Event()
def progress_callback(self, scan_info, bytes_scanned):
"""
Pass the progress information on the the main thread
and cancel the scan if the cancel event has been set.
"""
self.emit("progress", scan_info, bytes_scanned)
if self.cancel_event.isSet():
return True
else:
return False
def run(self):
"""
- Scan a page and emit status callbacks.
+ Set scanner options, scan a page and emit status callbacks.
"""
assert self.sane_device.is_open()
self.log.debug('Setting device options.')
+ # TODO: handle exceptions
try:
self.sane_device.options['mode'].value = self.mode
- # TODO
+ except saneme.SaneIOError:
+ raise
+ except saneme.SaneOutOfMemoryError:
+ raise
+ except saneme.SaneAccessDeniedError:
+ raise
+ except saneme.SaneUnknownError:
+ raise
except saneme.SaneReloadOptionsError:
pass
-
+
+ # TODO: handle exceptions
try:
self.sane_device.options['resolution'].value = int(self.resolution)
- # TODO
+ except saneme.SaneIOError:
+ raise
+ except saneme.SaneOutOfMemoryError:
+ raise
+ except saneme.SaneAccessDeniedError:
+ raise
+ except saneme.SaneUnknownError:
+ raise
except saneme.SaneReloadOptionsError:
pass
self.log.debug('Beginning scan.')
pil_image = None
+ # TODO: handle exceptions
try:
pil_image = self.sane_device.scan(self.progress_callback)
- # TODO: handle individual errors
- except saneme.SaneError:
+ except saneme.SaneDeviceBusyError:
+ raise
+ except saneme.SaneDeviceJammedError:
+ raise
+ except saneme.SaneNoDocumentsError:
+ raise
+ except saneme.SaneCoverOpenError:
+ raise
+ except saneme.SaneIOError:
+ raise
+ except saneme.SaneOutOfMemoryError:
+ raise
+ except saneme.SaneInvalidDataError:
+ raise
+ except saneme.SaneUnknownError:
raise
if self.cancel_event.isSet():
self.emit("failed", "Scan cancelled")
else:
assert pil_image is not None
self.emit("succeeded", pil_image)
class UpdateScannerOptionsThread(IdleObject, threading.Thread):
"""
Responsible for getting an up-to-date list of valid scanner options
and passing it back to the main thread.
"""
__gsignals__ = {
"finished": (
gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT]),
}
def __init__(self, sane_device):
"""
Initialize the thread.
"""
IdleObject.__init__(self)
threading.Thread.__init__(self)
self.log = logging.getLogger(self.__class__.__name__)
self.sane_device = sane_device
self.log.debug('Created.')
def run(self):
"""
Queries SANE for a list of available options for the specified scanner.
"""
assert self.sane_device.is_open()
self.log.debug('Updating scanner options.')
mode_list = self.sane_device.options['mode'].constraint
resolution_list = [str(i) for i in self.sane_device.options['resolution'].constraint]
# NB: We callback with the lists so that they can updated on the main thread
self.emit("finished", mode_list, resolution_list)
\ No newline at end of file
|
onyxfish/nostaples
|
ee8435daa637c229f471b82342c5770d10b3c3bf
|
Code review prior to 0.1 release.
|
diff --git a/sane/errors.py b/sane/errors.py
index dda046d..3fbf365 100644
--- a/sane/errors.py
+++ b/sane/errors.py
@@ -1,137 +1,135 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Python exceptions which take the place
of SANE's status codes in the Pythonic reimplementation of the API.
These are the errors that users will need to handle.
"""
-# TODO: add detail parameters, e.g.: SaneUnsupportedOperationError should include the device as an attribute
-
class SaneError(Exception):
"""
Base class for all SANE Errors.
"""
pass
class SaneUnknownError(SaneError):
"""
Exception denoting an error within the SANE library that could
not be categorized.
"""
pass
class SaneNoSuchDeviceError(SaneError):
"""
Exception denoting that a device requested by name did not
exist.
"""
pass
class SaneUnsupportedOperationError(SaneError):
"""
Exception denoting an unsupported operation was requested.
Corresponds to SANE status code SANE_STATUS_UNSUPPORTED.
"""
pass
class SaneDeviceBusyError(SaneError):
"""
Exception denoting that the requested device is being
accessed by another process.
Corresponds to SANE status code SANE_STATUS_DEVICE_BUSY.
"""
pass
class SaneInvalidDataError(SaneError):
"""
Exception denoting that some data or argument was not
valid.
Corresponds to SANE status code SANE_STATUS_INVAL.
"""
pass
class SaneEndOfFileError(SaneError):
"""
TODO: Should the user ever see this? probably handled internally
Corresponds to SANE status code SANE_STATUS_EOF.
"""
pass
class SaneDeviceJammedError(SaneError):
"""
Exception denoting that the device is jammed.
Corresponds to SANE status code SANE_STATUS_JAMMED.
"""
pass
class SaneNoDocumentsError(SaneError):
"""
Exception denoting that there are pages in the document
feeder of the device.
Corresponds to SANE status code SANE_STATUS_NO_DOCS.
"""
pass
class SaneCoverOpenError(SaneError):
"""
Exception denoting that the cover of the device is open.
Corresponds to SANE status code SANE_STATUS_COVER_OPEN.
"""
pass
class SaneIOError(SaneError):
"""
Exception denoting that an IO error occurred while
communicating wtih the device.
Corresponds to the SANE status code SANE_STATUS_IO_ERROR.
"""
pass
class SaneOutOfMemoryError(SaneError):
"""
Exception denoting that SANE ran out of memory during an
operation.
Corresponds to the SANE status code SANE_STATUS_NO_MEM.
"""
pass
class SaneAccessDeniedError(SaneError):
"""
TODO: should this be handled in a special way?
Corresponds to the SANE status code SANE_STATUS_ACCESS_DENIED.
"""
pass
class SaneReloadOptionsError(SaneError):
"""
Exception denoting that a change to a SANE option has had
a cascade effect on other options and thus that they should
be read again to get the most up to date values.
"""
pass
\ No newline at end of file
diff --git a/sane/saneme.py b/sane/saneme.py
index 9634c6d..9dea61d 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,873 +1,891 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method
from array import *
import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
-# Redeclare saneh enumerations which are visible to the end user
+# Redeclare saneh enumerations which are visible to the application
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SaneMe(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object, perform setup, and register
the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
self._setup()
atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
-
- TODO: handle the authentication callback... or not
"""
version_code = SANE_Int()
- callback = SANE_Auth_Callback(sane_auth_callback)
+ auth_callback = SANE_Auth_Callback(self._sane_auth_callback)
- status = sane_init(byref(version_code), callback)
+ status = sane_init(byref(version_code), auth_callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
+
+ def _sane_auth_callback(self, resource, username, password):
+ """
+ TODO
+ """
+ raise NotImplementedError(
+ 'sane_auth_callback requested, but not yet implemented.')
def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. To
ensure this method is called it is registered with atexit.
"""
for device in self._devices:
if device.is_open():
device.close()
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
# Public Methods
def get_device_list(self):
"""
Poll for connected devices. This method may take several
seconds to return.
Note that SANE is exited and re-inited before querying for
devices to workaround a limitation in SANE's USB driver
which causes the device list to only be updated on init.
+ This means that all settings applied to all devices will be
+ B{lost} and must be restored by the calling application.
+
This was found documented here:
U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html}
"""
assert self._version is not None
-
- for device in self._devices:
- if device.is_open():
- device.close()
# See docstring for details on this voodoo
- sane_exit()
- status = sane_init(byref(SANE_Int()), SANE_Auth_Callback(sane_auth_callback))
-
- if status != SANE_STATUS_GOOD.value:
- raise SaneUnknownError(
- 'sane_init returned an invalid status.')
+ self._shutdown()
+ self._setup()
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
return self._devices
def get_device_by_name(self, name):
"""
Retrieve a L{Device} by name.
Must be preceded by a call to L{get_device_list}.
"""
for device in self._devices:
if device.name == name:
return device
raise SaneNoSuchDeviceError()
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
-
- TODO: make open/close implicit?
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_display_name = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
assert type(ctypes_device.name) is StringType
assert type(ctypes_device.vendor) is StringType
assert type(ctypes_device.model) is StringType
assert type(ctypes_device.type) is StringType
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
self._display_name = ' '.join([self._vendor, self._model])
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_display_name(self):
"""
Get an appropriate name to use for displaying this device
to a user, e.g. 'Lexmark X1100/rev. B2'."""
return self._display_name
display_name = property(__get_display_name)
def __get_options(self):
- """Get the list of options that this device has."""
+ """Get the dictionary of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
- # TODO: handle statuses/exceptions
+ if status == SANE_STATUS_GOOD.value:
+ pass
+ elif status == SANE_STATUS_UNSUPPORTED.value:
+ raise SaneUnsupportedOperationError(
+ 'sane_control_option reported that a value was outside the option\'s constraint.')
+ elif status == SANE_STATUS_INVAL.value:
+ raise AssertionError(
+ 'sane_open reported that the device name was invalid.')
+ elif status == SANE_STATUS_IO_ERROR.value:
+ raise SaneIOError(
+ 'sane_open reported a communications error.')
+ elif status == SANE_STATUS_NO_MEM.value:
+ raise SaneOutOfMemoryError(
+ 'sane_open ran out of memory.')
+ elif status == SANE_STATUS_ACCESS_DENIED.value:
+ raise SaneAccessDeniedError(
+ 'sane_open requires greater access to open the device.')
+ else:
+ raise SaneUnknownError(
+ 'sane_open returned an invalid status.')
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
assert self._handle is None
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
# TODO - invalid device name? disconnected?
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
assert self._handle != c_void_p(None)
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
TODO: handle ADF scans
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
- raise SaneUnknownError()
+ raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
# This is the size used for the scan buffer in SANE's scanimage
# utility. The precise reasoning for using 32kb is unclear.
bytes_per_read = 32768
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
cancel = False
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
return None
assert not cancel
sane_cancel(self._handle)
assert scan_info.total_bytes == len(data_array)
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'RGB', 0, 1)
else:
- # TODO - handle seperate frames for R, G, and B
- raise NotImplementedError()
+ # TODO
+ raise NotImplementedError(
+ 'Individual color frame scanned, but not yet supported.')
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint = None
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
assert type(ctypes_option.name) is StringType
assert type(ctypes_option.title) is StringType
assert type(ctypes_option.desc) is StringType
assert type(ctypes_option.type) is IntType
assert type(ctypes_option.unit) is IntType
assert type(ctypes_option.size) is IntType
assert type(ctypes_option.cap) is IntType
assert type(ctypes_option.constraint_type) is IntType
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
assert type(ctypes_option.constraint.range.contents.min) is IntType
assert type(ctypes_option.constraint.range.contents.max) is IntType
assert type(ctypes_option.constraint.range.contents.quant) is IntType
self._constraint = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
word_count = ctypes_option.constraint.word_list[0]
self._constraint = []
i = 1
while(i < word_count):
self._constraint.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
string_count = 0
self._constraint = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
return self._type
type = property(__get_type)
def __get_unit(self):
return self._unit
unit = property(__get_unit)
def __get_capability(self):
# TODO: break out into individual capabilities, rather than a bitset
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint(self):
"""
Get the constraint for this option.
If constraint_type is OPTION_CONSTRAINT_RANGE then
this is a tuple containing the (minimum, maximum, step)
for valid values.
If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then
this is a list of integers which are valid values.
If constraint_type is OPTION_CONSTRAINT_STRING_LIST then
this is a list of strings which are valid values.
"""
return self._constraint
constraint = property(__get_constraint)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
- # Constraint checking ensures this should NEVER happen
- raise SaneUnsupportedOperationError(
+ # Constraint checking ensures this should never happen
+ raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported a value was invalid, but no values was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
assert type(value) is BooleanType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
assert type(value) is StringType
assert len(value) + 1 < self._size
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert value >= self._constraint[0]
assert value <= self._constraint[1]
assert value % self._constraint[2] == 0
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert value in self._constraint
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert value in self._constraint
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
- # Constraint checking ensures this should NEVER happen
- raise SaneUnsupportedOperationError(
+ # Constraint checking ensures this should never happen
+ raise AssertionError(
'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
def progress_callback(sane_info, bytes_read):
#print float(bytes_read) / sane_info.total_bytes
pass
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
sane = SaneMe(logging.getLogger())
devices = sane.get_device_list()
for dev in devices:
print dev.name
devices[0].open()
print devices[0].options.keys()
try:
devices[0].options['mode'].value = 'Gray'
except SaneReloadOptionsError:
pass
try:
devices[0].options['resolution'].value = 75
except SaneReloadOptionsError:
pass
try:
devices[0].options['preview'].value = False
except SaneReloadOptionsError:
pass
devices[0].scan(progress_callback).save('out.bmp')
devices[0].close()
\ No newline at end of file
|
onyxfish/nostaples
|
ab6e75eb9e0a17bdfcce2a141f195b74c4b6b133
|
Additional integration fixes.
|
diff --git a/sane/saneme.py b/sane/saneme.py
index 5c3f9bc..9634c6d 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,896 +1,873 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method
from array import *
import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the end user
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SaneMe(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object, perform setup, and register
the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
self._setup()
atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
TODO: handle the authentication callback... or not
"""
version_code = SANE_Int()
callback = SANE_Auth_Callback(sane_auth_callback)
status = sane_init(byref(version_code), callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. To
ensure this method is called it is registered with atexit.
"""
for device in self._devices:
if device.is_open():
device.close()
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
# Public Methods
def get_device_list(self):
"""
Poll for connected devices. This method may take several
seconds to return.
Note that SANE is exited and re-inited before querying for
devices to workaround a limitation in SANE's USB driver
which causes the device list to only be updated on init.
This was found documented here:
U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html}
"""
assert self._version is not None
for device in self._devices:
if device.is_open():
device.close()
# See docstring for details on this voodoo
sane_exit()
status = sane_init(byref(SANE_Int()), SANE_Auth_Callback(sane_auth_callback))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
return self._devices
def get_device_by_name(self, name):
"""
Retrieve a L{Device} by name.
Must be preceded by a call to L{get_device_list}.
"""
for device in self._devices:
if device.name == name:
return device
raise SaneNoSuchDeviceError()
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
TODO: make open/close implicit?
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_display_name = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
assert type(ctypes_device.name) is StringType
assert type(ctypes_device.vendor) is StringType
assert type(ctypes_device.model) is StringType
assert type(ctypes_device.type) is StringType
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
self._display_name = ' '.join([self._vendor, self._model])
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_display_name(self):
"""
Get an appropriate name to use for displaying this device
to a user, e.g. 'Lexmark X1100/rev. B2'."""
return self._display_name
display_name = property(__get_display_name)
def __get_options(self):
"""Get the list of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
# TODO: handle statuses/exceptions
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
assert self._handle is None
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
# TODO - invalid device name? disconnected?
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
assert self._handle != c_void_p(None)
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
+ TODO: handle ADF scans
+
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
# This is the size used for the scan buffer in SANE's scanimage
- # utility. The reasoning for this value (32kb) is unclear,
- # but it does not seem to suffer the same stuttering problems as
- # lower values, nor is it ridiculously large.
+ # utility. The precise reasoning for using 32kb is unclear.
bytes_per_read = 32768
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
cancel = False
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
return None
assert not cancel
sane_cancel(self._handle)
assert scan_info.total_bytes == len(data_array)
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'RGB', 0, 1)
else:
- # TODO - seperate frames for R, G, and B
+ # TODO - handle seperate frames for R, G, and B
raise NotImplementedError()
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
- _constraint_string_list = []
- _constraint_word_list = []
- _constraint_range = ()
+ _constraint = None
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
assert type(ctypes_option.name) is StringType
assert type(ctypes_option.title) is StringType
assert type(ctypes_option.desc) is StringType
assert type(ctypes_option.type) is IntType
assert type(ctypes_option.unit) is IntType
assert type(ctypes_option.size) is IntType
assert type(ctypes_option.cap) is IntType
assert type(ctypes_option.constraint_type) is IntType
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
assert type(ctypes_option.constraint.range.contents.min) is IntType
assert type(ctypes_option.constraint.range.contents.max) is IntType
assert type(ctypes_option.constraint.range.contents.quant) is IntType
- self._constraint_range = (
+ self._constraint = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
word_count = ctypes_option.constraint.word_list[0]
- self._constraint_word_list = []
+ self._constraint = []
i = 1
while(i < word_count):
- self._constraint_word_list.append(ctypes_option.constraint.word_list[i])
+ self._constraint.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
string_count = 0
- self._constraint_string_list = []
+ self._constraint = []
while ctypes_option.constraint.string_list[string_count]:
- self._constraint_string_list.append(ctypes_option.constraint.string_list[string_count])
+ self._constraint.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
- # TODO: convert to Python types at creation?
return self._type
type = property(__get_type)
def __get_unit(self):
- # TODO: convert to string representation at creation?
return self._unit
unit = property(__get_unit)
- def __get_size(self):
- # TODO: hide from user view?
- return self._size
-
- size = property(__get_size)
-
def __get_capability(self):
- # TODO: recast into a dictionary?
+ # TODO: break out into individual capabilities, rather than a bitset
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
- def __get_constraint_string_list(self):
+ def __get_constraint(self):
"""
- Get a list of strings which are valid values for this option.
+ Get the constraint for this option.
- Only relevant if constraint_type is OPTION_CONSTRAINT_STRING_LIST.
- """
- return self._constraint_string_list
+ If constraint_type is OPTION_CONSTRAINT_RANGE then
+ this is a tuple containing the (minimum, maximum, step)
+ for valid values.
- constraint_string_list = property(__get_constraint_string_list)
-
- def __get_constraint_word_list(self):
- """
- Get a list of integers that are valid values for this option.
+ If constraint_type is OPTION_CONSTRAINT_INTEGER_LIST then
+ this is a list of integers which are valid values.
- Only relevant if constraint_type is OPTION_CONSTRAINT_WORD_LIST.
+ If constraint_type is OPTION_CONSTRAINT_STRING_LIST then
+ this is a list of strings which are valid values.
"""
- return self._constraint_word_list
+ return self._constraint
- constraint_word_list = property(__get_constraint_word_list)
-
- def __get_constraint_range(self):
- """
- Get a tuple containing the (minimum, maximum, step) of
- valid values for this option.
-
- Only relevant if constraint_type is OPTION_CONSTRAINT_RANGE.
- """
- return self._constraint_range
-
- constraint_range = property(__get_constraint_range)
+ constraint = property(__get_constraint)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
- # TODO - should never happen if we check cap's before setting
- pass
+ # Constraint checking ensures this should NEVER happen
+ raise SaneUnsupportedOperationError(
+ 'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported a value was invalid, but no values was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
assert type(value) is BooleanType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
assert type(value) is StringType
assert len(value) + 1 < self._size
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
- assert value >= self._constraint_range[0]
- assert value <= self._constraint_range[1]
- assert value % self._constraint_range[2] == 0
+ assert value >= self._constraint[0]
+ assert value <= self._constraint[1]
+ assert value % self._constraint[2] == 0
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
- assert value in self._constraint_word_list
+ assert value in self._constraint
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
- assert value in self._constraint_string_list
+ assert value in self._constraint
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
- # TODO - should never happen if we check cap's before setting
- pass
+ # Constraint checking ensures this should NEVER happen
+ raise SaneUnsupportedOperationError(
+ 'sane_control_option reported that a value was outside the option\'s constraint.')
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
- # TODO: handle statuses/exceptions
-
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
def progress_callback(sane_info, bytes_read):
#print float(bytes_read) / sane_info.total_bytes
pass
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
sane = SaneMe(logging.getLogger())
devices = sane.get_device_list()
for dev in devices:
print dev.name
devices[0].open()
print devices[0].options.keys()
try:
devices[0].options['mode'].value = 'Gray'
except SaneReloadOptionsError:
pass
try:
devices[0].options['resolution'].value = 75
except SaneReloadOptionsError:
pass
try:
devices[0].options['preview'].value = False
except SaneReloadOptionsError:
pass
devices[0].scan(progress_callback).save('out.bmp')
devices[0].close()
\ No newline at end of file
|
onyxfish/nostaples
|
338c4b8814058770597ba2ce50a6a20c636585c5
|
Corrected scan buffer size.
|
diff --git a/sane/saneme.py b/sane/saneme.py
index e6bdfeb..5c3f9bc 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,892 +1,896 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method
from array import *
import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the end user
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SaneMe(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object, perform setup, and register
the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
self._setup()
atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
TODO: handle the authentication callback... or not
"""
version_code = SANE_Int()
callback = SANE_Auth_Callback(sane_auth_callback)
status = sane_init(byref(version_code), callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. To
ensure this method is called it is registered with atexit.
"""
for device in self._devices:
if device.is_open():
device.close()
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
# Public Methods
def get_device_list(self):
"""
Poll for connected devices. This method may take several
seconds to return.
Note that SANE is exited and re-inited before querying for
devices to workaround a limitation in SANE's USB driver
which causes the device list to only be updated on init.
This was found documented here:
U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html}
"""
assert self._version is not None
for device in self._devices:
if device.is_open():
device.close()
# See docstring for details on this voodoo
sane_exit()
status = sane_init(byref(SANE_Int()), SANE_Auth_Callback(sane_auth_callback))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
return self._devices
def get_device_by_name(self, name):
"""
Retrieve a L{Device} by name.
Must be preceded by a call to L{get_device_list}.
"""
for device in self._devices:
if device.name == name:
return device
raise SaneNoSuchDeviceError()
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
TODO: make open/close implicit?
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_display_name = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
assert type(ctypes_device.name) is StringType
assert type(ctypes_device.vendor) is StringType
assert type(ctypes_device.model) is StringType
assert type(ctypes_device.type) is StringType
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
self._display_name = ' '.join([self._vendor, self._model])
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_display_name(self):
"""
Get an appropriate name to use for displaying this device
to a user, e.g. 'Lexmark X1100/rev. B2'."""
return self._display_name
display_name = property(__get_display_name)
def __get_options(self):
"""Get the list of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
# TODO: handle statuses/exceptions
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
assert self._handle is None
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
# TODO - invalid device name? disconnected?
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
assert self._handle != c_void_p(None)
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
- # Should be a multiple of three (for RGB data) and a reasonable size
- # so that the progress callback will occur frequently without spamming.
- bytes_per_read = 4800
+ # This is the size used for the scan buffer in SANE's scanimage
+ # utility. The reasoning for this value (32kb) is unclear,
+ # but it does not seem to suffer the same stuttering problems as
+ # lower values, nor is it ridiculously large.
+ bytes_per_read = 32768
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
cancel = False
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
-
- if not cancel:
- sane_cancel(self._handle)
+ return None
+
+ assert not cancel
+
+ sane_cancel(self._handle)
assert scan_info.total_bytes == len(data_array)
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'RGB', 0, 1)
else:
# TODO - seperate frames for R, G, and B
raise NotImplementedError()
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint_string_list = []
_constraint_word_list = []
_constraint_range = ()
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
assert type(ctypes_option.name) is StringType
assert type(ctypes_option.title) is StringType
assert type(ctypes_option.desc) is StringType
assert type(ctypes_option.type) is IntType
assert type(ctypes_option.unit) is IntType
assert type(ctypes_option.size) is IntType
assert type(ctypes_option.cap) is IntType
assert type(ctypes_option.constraint_type) is IntType
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
assert type(ctypes_option.constraint.range.contents.min) is IntType
assert type(ctypes_option.constraint.range.contents.max) is IntType
assert type(ctypes_option.constraint.range.contents.quant) is IntType
self._constraint_range = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
word_count = ctypes_option.constraint.word_list[0]
self._constraint_word_list = []
i = 1
while(i < word_count):
self._constraint_word_list.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
string_count = 0
self._constraint_string_list = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint_string_list.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
# TODO: convert to Python types at creation?
return self._type
type = property(__get_type)
def __get_unit(self):
# TODO: convert to string representation at creation?
return self._unit
unit = property(__get_unit)
def __get_size(self):
# TODO: hide from user view?
return self._size
size = property(__get_size)
def __get_capability(self):
# TODO: recast into a dictionary?
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint_string_list(self):
"""
Get a list of strings which are valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_STRING_LIST.
"""
return self._constraint_string_list
constraint_string_list = property(__get_constraint_string_list)
def __get_constraint_word_list(self):
"""
Get a list of integers that are valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_WORD_LIST.
"""
return self._constraint_word_list
constraint_word_list = property(__get_constraint_word_list)
def __get_constraint_range(self):
"""
Get a tuple containing the (minimum, maximum, step) of
valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_RANGE.
"""
return self._constraint_range
constraint_range = property(__get_constraint_range)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# TODO - should never happen if we check cap's before setting
pass
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported a value was invalid, but no values was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
assert type(value) is BooleanType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
assert type(value) is StringType
assert len(value) + 1 < self._size
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert value >= self._constraint_range[0]
assert value <= self._constraint_range[1]
assert value % self._constraint_range[2] == 0
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert value in self._constraint_word_list
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert value in self._constraint_string_list
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# TODO - should never happen if we check cap's before setting
pass
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
# TODO: handle statuses/exceptions
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
def progress_callback(sane_info, bytes_read):
#print float(bytes_read) / sane_info.total_bytes
pass
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
sane = SaneMe(logging.getLogger())
devices = sane.get_device_list()
for dev in devices:
print dev.name
devices[0].open()
print devices[0].options.keys()
try:
devices[0].options['mode'].value = 'Gray'
except SaneReloadOptionsError:
pass
try:
devices[0].options['resolution'].value = 75
except SaneReloadOptionsError:
pass
try:
devices[0].options['preview'].value = False
except SaneReloadOptionsError:
pass
devices[0].scan(progress_callback).save('out.bmp')
devices[0].close()
\ No newline at end of file
|
onyxfish/nostaples
|
2e158f90d5d8c01fb8c7c322e0729720c9be0128
|
Changes made to ease integration into NoStaples.
|
diff --git a/sane/__init__.py b/sane/__init__.py
index 60baab2..968d8b1 100644
--- a/sane/__init__.py
+++ b/sane/__init__.py
@@ -1,2 +1,3 @@
# Allow importing this entire package as a single object
-from saneme import *
\ No newline at end of file
+from saneme import *
+from errors import *
\ No newline at end of file
diff --git a/sane/errors.py b/sane/errors.py
index 0fdef8b..dda046d 100644
--- a/sane/errors.py
+++ b/sane/errors.py
@@ -1,130 +1,137 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Python exceptions which take the place
of SANE's status codes in the Pythonic reimplementation of the API.
These are the errors that users will need to handle.
"""
# TODO: add detail parameters, e.g.: SaneUnsupportedOperationError should include the device as an attribute
class SaneError(Exception):
"""
Base class for all SANE Errors.
"""
pass
class SaneUnknownError(SaneError):
"""
Exception denoting an error within the SANE library that could
not be categorized.
"""
pass
+
+class SaneNoSuchDeviceError(SaneError):
+ """
+ Exception denoting that a device requested by name did not
+ exist.
+ """
+ pass
class SaneUnsupportedOperationError(SaneError):
"""
Exception denoting an unsupported operation was requested.
Corresponds to SANE status code SANE_STATUS_UNSUPPORTED.
"""
pass
class SaneDeviceBusyError(SaneError):
"""
Exception denoting that the requested device is being
accessed by another process.
Corresponds to SANE status code SANE_STATUS_DEVICE_BUSY.
"""
pass
class SaneInvalidDataError(SaneError):
"""
Exception denoting that some data or argument was not
valid.
Corresponds to SANE status code SANE_STATUS_INVAL.
"""
pass
class SaneEndOfFileError(SaneError):
"""
TODO: Should the user ever see this? probably handled internally
Corresponds to SANE status code SANE_STATUS_EOF.
"""
pass
class SaneDeviceJammedError(SaneError):
"""
Exception denoting that the device is jammed.
Corresponds to SANE status code SANE_STATUS_JAMMED.
"""
pass
class SaneNoDocumentsError(SaneError):
"""
Exception denoting that there are pages in the document
feeder of the device.
Corresponds to SANE status code SANE_STATUS_NO_DOCS.
"""
pass
class SaneCoverOpenError(SaneError):
"""
Exception denoting that the cover of the device is open.
Corresponds to SANE status code SANE_STATUS_COVER_OPEN.
"""
pass
class SaneIOError(SaneError):
"""
Exception denoting that an IO error occurred while
communicating wtih the device.
Corresponds to the SANE status code SANE_STATUS_IO_ERROR.
"""
pass
class SaneOutOfMemoryError(SaneError):
"""
Exception denoting that SANE ran out of memory during an
operation.
Corresponds to the SANE status code SANE_STATUS_NO_MEM.
"""
pass
class SaneAccessDeniedError(SaneError):
"""
TODO: should this be handled in a special way?
Corresponds to the SANE status code SANE_STATUS_ACCESS_DENIED.
"""
pass
class SaneReloadOptionsError(SaneError):
"""
Exception denoting that a change to a SANE option has had
a cascade effect on other options and thus that they should
be read again to get the most up to date values.
"""
pass
\ No newline at end of file
diff --git a/sane/saneme.py b/sane/saneme.py
index 0d77db0..e6bdfeb 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,850 +1,892 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method
from array import *
import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the end user
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
-class SANE(object):
+class SaneMe(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object, perform setup, and register
the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
self._setup()
atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
-
- def __get_devices(self):
- """
- Get the list of available devices, as of the most recent call
- to L{update_devices}.
- """
- return self._devices
-
- devices = property(__get_devices)
def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
TODO: handle the authentication callback... or not
"""
version_code = SANE_Int()
callback = SANE_Auth_Callback(sane_auth_callback)
status = sane_init(byref(version_code), callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. To
ensure this method is called it is registered with atexit.
-
- TODO: close any open devices before exiting
"""
+ for device in self._devices:
+ if device.is_open():
+ device.close()
+
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
# Public Methods
- def update_devices(self):
+ def get_device_list(self):
"""
- Poll for connected devices.
+ Poll for connected devices. This method may take several
+ seconds to return.
+
+ Note that SANE is exited and re-inited before querying for
+ devices to workaround a limitation in SANE's USB driver
+ which causes the device list to only be updated on init.
+
+ This was found documented here:
+ U{http://www.nabble.com/sane_get_devices-and-sanei_usb_init-td20766234.html}
"""
assert self._version is not None
+
+ for device in self._devices:
+ if device.is_open():
+ device.close()
+
+ # See docstring for details on this voodoo
+ sane_exit()
+ status = sane_init(byref(SANE_Int()), SANE_Auth_Callback(sane_auth_callback))
+
+ if status != SANE_STATUS_GOOD.value:
+ raise SaneUnknownError(
+ 'sane_init returned an invalid status.')
cdevices = POINTER(POINTER(SANE_Device))()
-
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
+
+ return self._devices
+
+ def get_device_by_name(self, name):
+ """
+ Retrieve a L{Device} by name.
+
+ Must be preceded by a call to L{get_device_list}.
+ """
+ for device in self._devices:
+ if device.name == name:
+ return device
+
+ raise SaneNoSuchDeviceError()
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
+
+ TODO: make open/close implicit?
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
+ _display_name = ''
+
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
assert type(ctypes_device.name) is StringType
assert type(ctypes_device.vendor) is StringType
assert type(ctypes_device.model) is StringType
assert type(ctypes_device.type) is StringType
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
+ self._display_name = ' '.join([self._vendor, self._model])
+
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
+ def __get_display_name(self):
+ """
+ Get an appropriate name to use for displaying this device
+ to a user, e.g. 'Lexmark X1100/rev. B2'."""
+ return self._display_name
+
+ display_name = property(__get_display_name)
+
def __get_options(self):
"""Get the list of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
# TODO: handle statuses/exceptions
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
assert self._handle is None
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
# TODO - invalid device name? disconnected?
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
assert self._handle != c_void_p(None)
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
# Should be a multiple of three (for RGB data) and a reasonable size
# so that the progress callback will occur frequently without spamming.
bytes_per_read = 4800
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
+ cancel = False
+
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
if not cancel:
sane_cancel(self._handle)
assert scan_info.total_bytes == len(data_array)
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
- data_array, 'raw', 'L', 0, 1)
+ data_array, 'raw', 'RGB', 0, 1)
else:
# TODO - seperate frames for R, G, and B
raise NotImplementedError()
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint_string_list = []
_constraint_word_list = []
_constraint_range = ()
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
assert type(ctypes_option.name) is StringType
assert type(ctypes_option.title) is StringType
assert type(ctypes_option.desc) is StringType
assert type(ctypes_option.type) is IntType
assert type(ctypes_option.unit) is IntType
assert type(ctypes_option.size) is IntType
assert type(ctypes_option.cap) is IntType
assert type(ctypes_option.constraint_type) is IntType
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
assert type(ctypes_option.constraint.range.contents.min) is IntType
assert type(ctypes_option.constraint.range.contents.max) is IntType
assert type(ctypes_option.constraint.range.contents.quant) is IntType
self._constraint_range = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
word_count = ctypes_option.constraint.word_list[0]
self._constraint_word_list = []
i = 1
while(i < word_count):
self._constraint_word_list.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
string_count = 0
self._constraint_string_list = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint_string_list.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
# TODO: convert to Python types at creation?
return self._type
type = property(__get_type)
def __get_unit(self):
# TODO: convert to string representation at creation?
return self._unit
unit = property(__get_unit)
def __get_size(self):
# TODO: hide from user view?
return self._size
size = property(__get_size)
def __get_capability(self):
# TODO: recast into a dictionary?
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint_string_list(self):
"""
Get a list of strings which are valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_STRING_LIST.
"""
return self._constraint_string_list
constraint_string_list = property(__get_constraint_string_list)
def __get_constraint_word_list(self):
"""
Get a list of integers that are valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_WORD_LIST.
"""
return self._constraint_word_list
constraint_word_list = property(__get_constraint_word_list)
def __get_constraint_range(self):
"""
Get a tuple containing the (minimum, maximum, step) of
valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_RANGE.
"""
return self._constraint_range
constraint_range = property(__get_constraint_range)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# TODO - should never happen if we check cap's before setting
pass
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported a value was invalid, but no values was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
assert type(value) is BooleanType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
assert type(value) is StringType
assert len(value) + 1 < self._size
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert value >= self._constraint_range[0]
assert value <= self._constraint_range[1]
assert value % self._constraint_range[2] == 0
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert value in self._constraint_word_list
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert value in self._constraint_string_list
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# TODO - should never happen if we check cap's before setting
pass
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
# TODO: handle statuses/exceptions
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
def progress_callback(sane_info, bytes_read):
#print float(bytes_read) / sane_info.total_bytes
pass
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
- sane = SANE(logging.getLogger())
- sane.update_devices()
+ sane = SaneMe(logging.getLogger())
+ devices = sane.get_device_list()
- for dev in sane.devices:
+ for dev in devices:
print dev.name
- sane.devices[0].open()
+ devices[0].open()
- print sane.devices[0].options.keys()
+ print devices[0].options.keys()
try:
- sane.devices[0].options['mode'].value = 'Gray'
+ devices[0].options['mode'].value = 'Gray'
except SaneReloadOptionsError:
pass
try:
- sane.devices[0].options['resolution'].value = 75
+ devices[0].options['resolution'].value = 75
except SaneReloadOptionsError:
pass
try:
- sane.devices[0].options['preview'].value = False
+ devices[0].options['preview'].value = False
except SaneReloadOptionsError:
pass
- sane.devices[0].scan(progress_callback).save('out.bmp')
+ devices[0].scan(progress_callback).save('out.bmp')
- sane.devices[0].close()
\ No newline at end of file
+ devices[0].close()
\ No newline at end of file
|
onyxfish/nostaples
|
882cfd61ab7c8f974f7bd7ce5c129d7d2cd3c568
|
Fixed setup and teardown functions to be properly automatic (using __init__ and atexit).
|
diff --git a/sane/saneme.py b/sane/saneme.py
index 503eda3..0d77db0 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,859 +1,850 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method
from array import *
+import atexit
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the end user
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SANE(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
- Create the SANE object. Note that all functional setup of the
- SANE object is deferred until the user explicitly calls L{setup}.
+ Create the SANE object, perform setup, and register
+ the cleanup function.
@param log: an optional Python logging object to log to.
"""
self._log = log
- def __del__(self):
- """
- Verify that the SANE connectoin was terminated.
- """
- assert self._version is None
+ self._setup()
+ atexit.register(self._shutdown)
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def __get_devices(self):
"""
Get the list of available devices, as of the most recent call
to L{update_devices}.
"""
return self._devices
devices = property(__get_devices)
-
- # Public Methods
- def setup(self):
+ def _setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
- Optionally, set a logging object to receive debugging
- information.
-
- See L{exit} for an explanation of why this does not occur
- in L{__init__}.
TODO: handle the authentication callback... or not
"""
version_code = SANE_Int()
callback = SANE_Auth_Callback(sane_auth_callback)
status = sane_init(byref(version_code), callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
- def shutdown(self):
+ def _shutdown(self):
"""
Deinitialize SANE.
This code would go in L{__del__}, but it is not guaranteed that method
- will be called and sane_exit must be called to release resources. Thus
- the parallel L{__init__} method for consistency.
+ will be called and sane_exit must be called to release resources. To
+ ensure this method is called it is registered with atexit.
TODO: close any open devices before exiting
"""
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
+ # Public Methods
+
def update_devices(self):
"""
Poll for connected devices.
"""
assert self._version is not None
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
assert type(ctypes_device.name) is StringType
assert type(ctypes_device.vendor) is StringType
assert type(ctypes_device.model) is StringType
assert type(ctypes_device.type) is StringType
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_options(self):
"""Get the list of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
# TODO: handle statuses/exceptions
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
assert self._handle is None
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
# TODO - invalid device name? disconnected?
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
assert self._handle != c_void_p(None)
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
# Should be a multiple of three (for RGB data) and a reasonable size
# so that the progress callback will occur frequently without spamming.
bytes_per_read = 4800
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
if not cancel:
sane_cancel(self._handle)
assert scan_info.total_bytes == len(data_array)
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
else:
# TODO - seperate frames for R, G, and B
raise NotImplementedError()
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint_string_list = []
_constraint_word_list = []
_constraint_range = ()
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
assert type(ctypes_option.name) is StringType
assert type(ctypes_option.title) is StringType
assert type(ctypes_option.desc) is StringType
assert type(ctypes_option.type) is IntType
assert type(ctypes_option.unit) is IntType
assert type(ctypes_option.size) is IntType
assert type(ctypes_option.cap) is IntType
assert type(ctypes_option.constraint_type) is IntType
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
assert type(ctypes_option.constraint.range.contents.min) is IntType
assert type(ctypes_option.constraint.range.contents.max) is IntType
assert type(ctypes_option.constraint.range.contents.quant) is IntType
self._constraint_range = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
word_count = ctypes_option.constraint.word_list[0]
self._constraint_word_list = []
i = 1
while(i < word_count):
self._constraint_word_list.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
string_count = 0
self._constraint_string_list = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint_string_list.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
# TODO: convert to Python types at creation?
return self._type
type = property(__get_type)
def __get_unit(self):
# TODO: convert to string representation at creation?
return self._unit
unit = property(__get_unit)
def __get_size(self):
# TODO: hide from user view?
return self._size
size = property(__get_size)
def __get_capability(self):
# TODO: recast into a dictionary?
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint_string_list(self):
"""
Get a list of strings which are valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_STRING_LIST.
"""
return self._constraint_string_list
constraint_string_list = property(__get_constraint_string_list)
def __get_constraint_word_list(self):
"""
Get a list of integers that are valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_WORD_LIST.
"""
return self._constraint_word_list
constraint_word_list = property(__get_constraint_word_list)
def __get_constraint_range(self):
"""
Get a tuple containing the (minimum, maximum, step) of
valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_RANGE.
"""
return self._constraint_range
constraint_range = property(__get_constraint_range)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# TODO - should never happen if we check cap's before setting
pass
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported a value was invalid, but no values was being set.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
c_value = None
# Type checking
if self._type == SANE_TYPE_BOOL.value:
assert type(value) is BooleanType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
assert type(value) is StringType
assert len(value) + 1 < self._size
c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
# Constraint checking
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert value >= self._constraint_range[0]
assert value <= self._constraint_range[1]
assert value % self._constraint_range[2] == 0
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert value in self._constraint_word_list
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert value in self._constraint_string_list
info_flags = SANE_Int()
status = sane_control_option(
handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_UNSUPPORTED.value:
# TODO - should never happen if we check cap's before setting
pass
elif status == SANE_STATUS_INVAL.value:
raise AssertionError(
'sane_control_option reported that the value to be set was invalid, despite checks.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_control_option reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_control_option ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_control_option requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_control_option returned an invalid status.')
# TODO: handle statuses/exceptions
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
# See SANE API 4.3.7
if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
raise SaneReloadOptionsError()
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
def progress_callback(sane_info, bytes_read):
#print float(bytes_read) / sane_info.total_bytes
pass
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
sane = SANE(logging.getLogger())
- sane.setup()
sane.update_devices()
for dev in sane.devices:
print dev.name
sane.devices[0].open()
print sane.devices[0].options.keys()
try:
sane.devices[0].options['mode'].value = 'Gray'
except SaneReloadOptionsError:
pass
try:
sane.devices[0].options['resolution'].value = 75
except SaneReloadOptionsError:
pass
try:
sane.devices[0].options['preview'].value = False
except SaneReloadOptionsError:
pass
sane.devices[0].scan(progress_callback).save('out.bmp')
- sane.devices[0].close()
- sane.shutdown()
\ No newline at end of file
+ sane.devices[0].close()
\ No newline at end of file
|
onyxfish/nostaples
|
51a303af48c26bf13c93ee5acf7b64785f9e63f8
|
Made it possible to import entire package with a single statement.
|
diff --git a/sane/__init__.py b/sane/__init__.py
index e69de29..60baab2 100644
--- a/sane/__init__.py
+++ b/sane/__init__.py
@@ -0,0 +1,2 @@
+# Allow importing this entire package as a single object
+from saneme import *
\ No newline at end of file
|
onyxfish/nostaples
|
e79354954571f95192fc02e75965013f41dd453c
|
Added license, readme, utils, and setup.py.
|
diff --git a/sane/COPYING b/sane/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/sane/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/sane/README b/sane/README
new file mode 100644
index 0000000..224dc4c
--- /dev/null
+++ b/sane/README
@@ -0,0 +1,8 @@
+Downloaded from:
+
+<http://www.etlafins.com/saneme>
+
+Send Questions/Comments to:
+
+Christopher Groskopf
+<[email protected]>
diff --git a/sane/epydoc.config b/sane/epydoc.config
new file mode 100644
index 0000000..bd3df7d
--- /dev/null
+++ b/sane/epydoc.config
@@ -0,0 +1,20 @@
+[epydoc]
+
+# Project
+name: saneme
+url: http://www.etlafins.com/saneme
+
+# Modules
+modules: saneme, saneh, errors
+
+# Output
+output: html
+target: epydoc/
+
+# Formatting
+docformat: epytext
+inheritance: grouped
+
+# Graphs
+graph: all
+dotpath: /usr/bin/dot
diff --git a/sane/pylint.config b/sane/pylint.config
new file mode 100644
index 0000000..0725cdd
--- /dev/null
+++ b/sane/pylint.config
@@ -0,0 +1,306 @@
+# lint Python modules using external checkers.
+#
+# This is the main checker controling the other ones and the reports
+# generation. It is itself both a raw checker and an astng checker in order
+# to:
+# * handle message activation / deactivation at the module level
+# * handle some basic but necessary stats'data (number of classes, methods...)
+#
+[MASTER]
+
+# Specify a configuration file.
+#rcfile=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Profiled execution.
+profile=no
+
+# Add <file or directory> to the black list. It should be a base name, not a
+# path. You may set this option multiple times.
+ignore=.git
+ignore=epydoc
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# Set the cache size for astng objects.
+cache-size=500
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+
+[MESSAGES CONTROL]
+
+# Enable only checker(s) with the given id(s). This option conflicts with the
+# disable-checker option
+#enable-checker=
+
+# Enable all checker(s) except those with the given id(s). This option
+# conflicts with the enable-checker option
+#disable-checker=
+
+# Enable all messages in the listed categories.
+#enable-msg-cat=
+
+# Disable all messages in the listed categories.
+#disable-msg-cat=
+
+# Enable the message(s) with the given id(s).
+#enable-msg=
+
+# Disable the message(s) with the given id(s).
+#disable-msg=
+
+
+[REPORTS]
+
+# set the output format. Available formats are text, parseable, colorized, msvs
+# (visual studio) and html
+output-format=html
+
+# Include message's id in output
+include-ids=yes
+
+# Put messages in a separate file for each module / package specified on the
+# command line instead of printing them on stdout. Reports (if any) will be
+# written in a file name "pylint_global.[txt|html]".
+files-output=no
+
+# Tells wether to display a full report or only the messages
+reports=yes
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note).You have access to the variables errors warning, statement which
+# respectivly contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (R0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Add a comment according to your evaluation note. This is used by the global
+# evaluation report (R0004).
+comment=yes
+
+# Enable the report(s) with the given id(s).
+#enable-report=
+
+# Disable the report(s) with the given id(s).
+#disable-report=
+
+
+# checks for
+# * unused variables / imports
+# * undefined variables
+# * redefinition of variable from builtins or from an outer scope
+# * use of variable before assigment
+#
+[VARIABLES]
+
+# Tells wether we should check for unused import in __init__ files.
+init-import=no
+
+# A regular expression matching names used for dummy variables (i.e. not used).
+dummy-variables-rgx=_|dummy
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid to define new builtins when possible.
+additional-builtins=
+
+
+# try to find bugs in the code using type inference
+#
+[TYPECHECK]
+
+# Tells wether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# When zope mode is activated, consider the acquired-members option to ignore
+# access to some undefined attributes.
+zope=no
+
+# List of members which are usually get through zope's acquisition mecanism and
+# so shouldn't trigger E0201 when accessed (need zope=yes to be considered).
+acquired-members=REQUEST,acl_users,aq_parent
+
+
+# checks for :
+# * doc strings
+# * modules / classes / functions / methods / arguments / variables name
+# * number of arguments, local variables, branchs, returns and statements in
+# functions, methods
+# * required module attributes
+# * dangerous default values as arguments
+# * redefinition of function / method / class
+# * uses of the global statement
+#
+[BASIC]
+
+# Required attributes for module, separated by a comma
+required-attributes=
+
+# Regular expression which should only match functions or classes name which do
+# not require a docstring
+no-docstring-rgx=__.*__
+
+# Regular expression which should only match correct module names
+module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
+
+# Regular expression which should only match correct module level names
+const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$
+
+# Regular expression which should only match correct class names
+class-rgx=[A-Z_][a-zA-Z0-9]+$
+
+# Regular expression which should only match correct function names
+function-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct method names
+method-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct instance attribute names
+attr-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct argument names
+argument-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct variable names
+variable-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct list comprehension /
+# generator expression variable names
+inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
+
+# Good variable names which should always be accepted, separated by a comma
+good-names=i,j,k,ex,Run,_
+
+# Bad variable names which should always be refused, separated by a comma
+bad-names=foo,bar,baz,toto,tutu,tata
+
+# List of builtins function names that should not be used, separated by a comma
+bad-functions=map,filter,apply,input
+
+
+# checks for
+# * external modules dependencies
+# * relative / wildcard imports
+# * cyclic imports
+# * uses of deprecated modules
+#
+[IMPORTS]
+
+# Deprecated modules which should not be used, separated by a comma
+deprecated-modules=regsub,string,TERMIOS,Bastion,rexec
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report R0402 must not be disabled)
+import-graph=
+
+# Create a graph of external dependencies in the given file (report R0402 must
+# not be disabled)
+ext-import-graph=
+
+# Create a graph of internal dependencies in the given file (report R0402 must
+# not be disabled)
+int-import-graph=
+
+
+# checks for sign of poor/misdesign:
+# * number of methods, attributes, local variables...
+# * size, complexity of functions, methods
+#
+[DESIGN]
+
+# Maximum number of arguments for function / method
+max-args=5
+
+# Maximum number of locals for function / method body
+max-locals=15
+
+# Maximum number of return / yield for function / method body
+max-returns=6
+
+# Maximum number of branch for function / method body
+max-branchs=12
+
+# Maximum number of statements in function / method body
+max-statements=50
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+
+# checks for :
+# * methods without self as first argument
+# * overridden methods signature
+# * access only to existant members via self
+# * attributes not defined in the __init__ method
+# * supported interfaces implementation
+# * unreachable code
+#
+[CLASSES]
+
+# List of interface methods to ignore, separated by a comma. This is used for
+# instance to not check methods defines in Zope's Interface base class.
+ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,__new__,setUp
+
+
+# checks for :
+# * unauthorized constructions
+# * strict indentation
+# * line length
+# * use of <> instead of !=
+#
+[FORMAT]
+
+# Maximum number of characters on a single line.
+max-line-length=80
+
+# Maximum number of lines in a module
+max-module-lines=1000
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string=' '
+
+
+# checks for:
+# * warning notes in the code like FIXME, XXX
+# * PEP 263: source code with non ascii character but no encoding declaration
+#
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,XXX,TODO
+
+
+# checks for similarities and duplicated code. This computation may be
+# memory / CPU intensive, so you should disable it if you experiments some
+# problems.
+#
+[SIMILARITIES]
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
diff --git a/sane/run-epydoc b/sane/run-epydoc
new file mode 100755
index 0000000..a7cf1a0
--- /dev/null
+++ b/sane/run-epydoc
@@ -0,0 +1,3 @@
+#!/bin/bash
+
+epydoc --config epydoc.config -v
diff --git a/sane/run-pylint b/sane/run-pylint
new file mode 100755
index 0000000..28871b7
--- /dev/null
+++ b/sane/run-pylint
@@ -0,0 +1,4 @@
+#!/bin/bash
+
+pylint --rcfile pylint.config *.py models/*.py controllers/*.py views/*.py utils/*.py > pylint.html
+
diff --git a/sane/saneme.py b/sane/saneme.py
index c18975a..503eda3 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,647 +1,647 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method
from array import *
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the end user
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SANE(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object. Note that all functional setup of the
- SANE object is deferred until the user explicitly calls L{init}.
+ SANE object is deferred until the user explicitly calls L{setup}.
@param log: an optional Python logging object to log to.
"""
self._log = log
def __del__(self):
"""
Verify that the SANE connectoin was terminated.
"""
assert self._version is None
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def __get_devices(self):
"""
Get the list of available devices, as of the most recent call
to L{update_devices}.
"""
return self._devices
devices = property(__get_devices)
# Public Methods
def setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
Optionally, set a logging object to receive debugging
information.
See L{exit} for an explanation of why this does not occur
- in __init__.
+ in L{__init__}.
TODO: handle the authentication callback... or not
"""
version_code = SANE_Int()
callback = SANE_Auth_Callback(sane_auth_callback)
status = sane_init(byref(version_code), callback)
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError(
'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def shutdown(self):
"""
Deinitialize SANE.
- This code would go in __del__, but it is not guaranteed that method
+ This code would go in L{__del__}, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. Thus
- the parallel L{init} method for consistency.
+ the parallel L{__init__} method for consistency.
TODO: close any open devices before exiting
"""
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
def update_devices(self):
"""
Poll for connected devices.
"""
assert self._version is not None
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_get_devices ran out of memory.')
else:
raise SaneUnknownError(
'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
assert type(ctypes_device.name) is StringType
assert type(ctypes_device.vendor) is StringType
assert type(ctypes_device.model) is StringType
assert type(ctypes_device.type) is StringType
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_options(self):
"""Get the list of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
# TODO: handle statuses/exceptions
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
"""
assert self._handle is None
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
# TODO - invalid device name? disconnected?
raise AssertionError(
'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_open requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_open returned an invalid status.')
assert self._handle != c_void_p(None)
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
"""
Scan a document using this device.
@param progress_callback: An optional callback that
will be called each time data is read from
the device. Has the format:
cancel = progress_callback(sane_info, bytes_read)
@return: A PIL image containing the scanned
page.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
# See SANE API 4.3.9
status = sane_start(self._handle)
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_CANCELLED.value:
raise AssertionError(
'sane_start reported cancelled status before it was set.')
elif status == SANE_STATUS_DEVICE_BUSY.value:
raise SaneDeviceBusyError(
'sane_start reported the device was in use.')
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_start reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_start reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_start reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_start encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_start ran out of memory.')
elif status == SANE_STATUS_INVAL.value:
#TODO - see docs
raise SaneInvalidDataError()
else:
raise SaneUnknownError(
'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
# See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
# Should be a multiple of three (for RGB data) and a reasonable size
# so that the progress callback will occur frequently without spamming.
bytes_per_read = 4800
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
while True:
# See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
raise SaneDeviceJammedError(
'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
raise SaneNoDocumentsError(
'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
raise SaneCoverOpenError(
'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
raise SaneIOError(
'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
raise SaneOutOfMemoryError(
'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
raise SaneAccessDeniedError(
'sane_read requires greater access to open the device.')
else:
raise SaneUnknownError(
'sane_read returned an invalid status.')
data_array.extend(temp_array[0:actual_size.value])
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
if not cancel:
sane_cancel(self._handle)
assert scan_info.total_bytes == len(data_array)
if sane_parameters.format == SANE_FRAME_GRAY.value:
pil_image = Image.frombuffer(
'L', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
pil_image = Image.frombuffer(
'RGB', (scan_info.width, scan_info.height),
data_array, 'raw', 'L', 0, 1)
else:
# TODO - seperate frames for R, G, and B
raise NotImplementedError()
return pil_image
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint_string_list = []
_constraint_word_list = []
_constraint_range = ()
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
assert type(ctypes_option.name) is StringType
assert type(ctypes_option.title) is StringType
assert type(ctypes_option.desc) is StringType
assert type(ctypes_option.type) is IntType
assert type(ctypes_option.unit) is IntType
assert type(ctypes_option.size) is IntType
assert type(ctypes_option.cap) is IntType
assert type(ctypes_option.constraint_type) is IntType
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
assert type(ctypes_option.constraint.range.contents.min) is IntType
assert type(ctypes_option.constraint.range.contents.max) is IntType
assert type(ctypes_option.constraint.range.contents.quant) is IntType
self._constraint_range = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
word_count = ctypes_option.constraint.word_list[0]
self._constraint_word_list = []
i = 1
while(i < word_count):
self._constraint_word_list.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
string_count = 0
self._constraint_string_list = []
while ctypes_option.constraint.string_list[string_count]:
self._constraint_string_list.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
# TODO: convert to Python types at creation?
return self._type
type = property(__get_type)
def __get_unit(self):
# TODO: convert to string representation at creation?
return self._unit
unit = property(__get_unit)
def __get_size(self):
# TODO: hide from user view?
return self._size
size = property(__get_size)
def __get_capability(self):
# TODO: recast into a dictionary?
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint_string_list(self):
"""
Get a list of strings which are valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_STRING_LIST.
"""
return self._constraint_string_list
constraint_string_list = property(__get_constraint_string_list)
def __get_constraint_word_list(self):
"""
Get a list of integers that are valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_WORD_LIST.
"""
return self._constraint_word_list
constraint_word_list = property(__get_constraint_word_list)
def __get_constraint_range(self):
"""
Get a tuple containing the (minimum, maximum, step) of
valid values for this option.
Only relevant if constraint_type is OPTION_CONSTRAINT_RANGE.
"""
return self._constraint_range
constraint_range = property(__get_constraint_range)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
diff --git a/sane/setup.py b/sane/setup.py
new file mode 100644
index 0000000..a42f6d1
--- /dev/null
+++ b/sane/setup.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+
+from distutils.core import setup
+
+setup(name='saneme',
+ version='0.1.0',
+ description='Pythonic interface to the SANE API.',
+ author='Christopher Groskopf',
+ author_email='[email protected]',
+ url='http://www.etlafins.com/saneme',
+ license='GPL',
+ packages=['saneme'],
+ package_dir={'saneme' : ''},
+ )
+
|
onyxfish/nostaples
|
b4dbe646cdfc8b56071ba58cca3a8166ea4d8d40
|
Lots of debugging, lots of error-checking, etc.
|
diff --git a/sane/errors.py b/sane/errors.py
index bfbf3a1..0fdef8b 100644
--- a/sane/errors.py
+++ b/sane/errors.py
@@ -1,130 +1,130 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Python exceptions which take the place
of SANE's status codes in the Pythonic reimplementation of the API.
These are the errors that users will need to handle.
"""
# TODO: add detail parameters, e.g.: SaneUnsupportedOperationError should include the device as an attribute
class SaneError(Exception):
"""
Base class for all SANE Errors.
"""
pass
class SaneUnknownError(SaneError):
"""
Exception denoting an error within the SANE library that could
not be categorized.
"""
pass
class SaneUnsupportedOperationError(SaneError):
"""
Exception denoting an unsupported operation was requested.
Corresponds to SANE status code SANE_STATUS_UNSUPPORTED.
"""
pass
-class SaneCancelledOperationError(SaneError):
- """
- TODO: when is this called
-
- Corresponds to SANE status code SANE_STATUS_CANCELLED.
- """
- pass
-
class SaneDeviceBusyError(SaneError):
"""
Exception denoting that the requested device is being
accessed by another process.
Corresponds to SANE status code SANE_STATUS_DEVICE_BUSY.
"""
pass
class SaneInvalidDataError(SaneError):
"""
Exception denoting that some data or argument was not
valid.
Corresponds to SANE status code SANE_STATUS_INVAL.
"""
pass
class SaneEndOfFileError(SaneError):
"""
TODO: Should the user ever see this? probably handled internally
Corresponds to SANE status code SANE_STATUS_EOF.
"""
pass
class SaneDeviceJammedError(SaneError):
"""
Exception denoting that the device is jammed.
Corresponds to SANE status code SANE_STATUS_JAMMED.
"""
pass
class SaneNoDocumentsError(SaneError):
"""
Exception denoting that there are pages in the document
feeder of the device.
Corresponds to SANE status code SANE_STATUS_NO_DOCS.
"""
pass
class SaneCoverOpenError(SaneError):
"""
Exception denoting that the cover of the device is open.
Corresponds to SANE status code SANE_STATUS_COVER_OPEN.
"""
pass
class SaneIOError(SaneError):
"""
Exception denoting that an IO error occurred while
communicating wtih the device.
Corresponds to the SANE status code SANE_STATUS_IO_ERROR.
"""
pass
class SaneOutOfMemoryError(SaneError):
"""
Exception denoting that SANE ran out of memory during an
operation.
Corresponds to the SANE status code SANE_STATUS_NO_MEM.
"""
pass
class SaneAccessDeniedError(SaneError):
"""
TODO: should this be handled in a special way?
Corresponds to the SANE status code SANE_STATUS_ACCESS_DENIED.
"""
- pass
\ No newline at end of file
+ pass
+
+class SaneReloadOptionsError(SaneError):
+ """
+ Exception denoting that a change to a SANE option has had
+ a cascade effect on other options and thus that they should
+ be read again to get the most up to date values.
+ """
+ pass
\ No newline at end of file
diff --git a/sane/saneme.py b/sane/saneme.py
index d199ae7..c18975a 100644
--- a/sane/saneme.py
+++ b/sane/saneme.py
@@ -1,733 +1,859 @@
#!/usr/bin/python
#~ This file is part of SaneMe.
#~ SaneMe is free software: you can redistribute it and/or modify
#~ it under the terms of the GNU General Public License as published by
#~ the Free Software Foundation, either version 3 of the License, or
#~ (at your option) any later version.
#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the Pythonic implementation of the SANE API.
The flat C functions have been wrapped in a set of objects and all
ctypes of the underlying implmentation have been hidden from the
user's view. This enumerations and definiations which are absolutely
necessary to the end user have been redeclared.
"""
# TODO: document what exceptions can be thrown by each method
from array import *
import ctypes
from types import *
from PIL import Image
from errors import *
from saneh import *
# Redeclare saneh enumerations which are visible to the end user
(OPTION_TYPE_BOOL,
OPTION_TYPE_INT,
OPTION_TYPE_FIXED,
OPTION_TYPE_STRING,
OPTION_TYPE_BUTTON,
OPTION_TYPE_GROUP) = xrange(6)
(OPTION_UNIT_NONE,
OPTION_UNIT_PIXEL,
OPTION_UNIT_BIT,
OPTION_UNIT_MM,
OPTION_UNIT_DPI,
OPTION_UNIT_PERCENT,
OPTION_UNIT_MICROSECOND) = xrange(7)
(OPTION_CONSTRAINT_NONE,
OPTION_CONSTRAINT_RANGE,
OPTION_CONSTRAINT_INTEGER_LIST,
OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
class SANE(object):
"""
The top-level object for interacting with the SANE API. Handles
polling for devices. This object should only be instantiated once.
"""
_log = None
_version = None # (major, minor, build)
_devices = []
def __init__(self, log=None):
"""
Create the SANE object. Note that all functional setup of the
SANE object is deferred until the user explicitly calls L{init}.
@param log: an optional Python logging object to log to.
"""
self._log = log
def __del__(self):
"""
Verify that the SANE connectoin was terminated.
"""
assert self._version is None
# Read only properties
def __get_version(self):
"""Get the current installed version of SANE."""
return self._version
version = property(__get_version)
def __get_devices(self):
"""
Get the list of available devices, as of the most recent call
to L{update_devices}.
"""
return self._devices
devices = property(__get_devices)
# Public Methods
def setup(self):
"""
Iniitalize SANE and retrieve the current installed version.
Optionally, set a logging object to receive debugging
information.
See L{exit} for an explanation of why this does not occur
in __init__.
- TODO: handle the authentication callback
-
- @raise SaneUnknownError: sane_init returned an invalid status.
+ TODO: handle the authentication callback... or not
"""
version_code = SANE_Int()
callback = SANE_Auth_Callback(sane_auth_callback)
status = sane_init(byref(version_code), callback)
if status != SANE_STATUS_GOOD.value:
- raise SaneUnknownError()
-
- # TODO: handle status/exceptions
+ raise SaneUnknownError(
+ 'sane_init returned an invalid status.')
self._version = (SANE_VERSION_MAJOR(version_code),
SANE_VERSION_MINOR(version_code),
SANE_VERSION_BUILD(version_code))
if self._log:
self._log.debug('SANE version %s initalized.', self._version)
def shutdown(self):
"""
Deinitialize SANE.
This code would go in __del__, but it is not guaranteed that method
will be called and sane_exit must be called to release resources. Thus
the parallel L{init} method for consistency.
TODO: close any open devices before exiting
"""
sane_exit()
self._version = None
if self._log:
self._log.debug('SANE deinitialized.')
def update_devices(self):
"""
Poll for connected devices.
-
- @raise SaneOutOfMemoryError: sane_get_devices ran out of memory.
- @raise SaneUnknownError: sane_get_devices returned an invalid status.
"""
assert self._version is not None
cdevices = POINTER(POINTER(SANE_Device))()
status = sane_get_devices(byref(cdevices), SANE_Bool(0))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_NO_MEM.value:
- raise SaneOutOfMemoryError()
+ raise SaneOutOfMemoryError(
+ 'sane_get_devices ran out of memory.')
else:
- raise SaneUnknownError()
+ raise SaneUnknownError(
+ 'sane_get_devices returned an invalid status.')
device_count = 0
self._devices = []
while cdevices[device_count]:
self._devices.append(Device(cdevices[device_count].contents))
device_count += 1
if self._log:
self._log.debug('SANE queried, %i device(s) found.', device_count)
class Device(object):
"""
This is the primary object for interacting with SANE. It represents
a single device and handles enumeration of options, getting and
setting of options, and starting and stopping of scanning jobs.
"""
_log = None
_handle = None
_name = ''
_vendor = ''
_model = ''
_type = ''
_options = {}
def __init__(self, ctypes_device, log=None):
"""
Sets the Devices properties from a ctypes SANE_Device and
queries for its available options.
"""
self._log = log
assert type(ctypes_device.name) is StringType
assert type(ctypes_device.vendor) is StringType
assert type(ctypes_device.model) is StringType
assert type(ctypes_device.type) is StringType
self._name = ctypes_device.name
self._vendor = ctypes_device.vendor
self._model = ctypes_device.model
self._type = ctypes_device.type
# Read only properties
def __get_name(self):
"""
Get the complete SANE identifier for this device,
e.g. 'lexmark:libusb:002:006'.
"""
return self._name
name = property(__get_name)
def __get_vendor(self):
"""Get the manufacturer of this device, e.g. 'Lexmark'."""
return self._vendor
vendor = property(__get_vendor)
def __get_model(self):
"""Get the specific model of this device, e.g. 'X1100/rev. B2'."""
return self._model
model = property(__get_model)
def __get_type(self):
"""Get the type of this device, e.g. 'flatbed scanner'."""
return self._type
type = property(__get_type)
def __get_options(self):
"""Get the list of options that this device has."""
return self._options
options = property(__get_options)
# Internal methods
def _update_options(self):
"""
Update the list of available options for this device. As these
are immutable, this should only need to be called when the Device
is first instantiated.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
option_value = pointer(c_int())
status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
# TODO: handle statuses/exceptions
option_count = option_value.contents.value
if self._log:
self._log.debug('Device queried, %i option(s) found.', option_count)
self._options.clear()
i = 1
while(i < option_count - 1):
coption = sane_get_option_descriptor(self._handle, i)
self._options[coption.contents.name] = Option(self, i, coption.contents)
i = i + 1
# Methods for use only by Options
def _get_handle(self):
"""
Verify that the device is open and get the current open handle.
To be called by Options of this device so that they may set themselves.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
return self._handle
# Public methods
def open(self):
"""
Open a new handle to this device.
Must be called before any operations (including setting options)
are performed on this device.
-
- @raise SaneDeviceBusyError: this device is in use by another process.
- @raise SaneInvalidDataError: the device has been disconnected.
- @raise SaneIOError: a communications error occurred with the device.
- @raise SaneOutOfMemoryError: ran out of memory while opening the device.
- @raise SaneAccessDeniedError: greater access is required to open the device.
- @raise SaneUnknownError: sane_open returned an invalid status.
"""
assert self._handle is None
self._handle = SANE_Handle()
status = sane_open(self.name, byref(self._handle))
if status == SANE_STATUS_GOOD.value:
pass
elif status == SANE_STATUS_DEVICE_BUSY.value:
- raise SaneDeviceBusyError()
+ raise SaneDeviceBusyError(
+ 'sane_open reported that the device was busy.')
elif status == SANE_STATUS_INVAL.value:
- raise SaneInvalidDataError()
+ # TODO - invalid device name? disconnected?
+ raise AssertionError(
+ 'sane_open reported that the device name was invalid.')
elif status == SANE_STATUS_IO_ERROR.value:
- raise SaneIOError()
+ raise SaneIOError(
+ 'sane_open reported a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
- raise SaneOutOfMemoryError()
+ raise SaneOutOfMemoryError(
+ 'sane_open ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
- # TODO
- raise SaneAccessDeniedError()
+ raise SaneAccessDeniedError(
+ 'sane_open requires greater access to open the device.')
else:
- raise SaneUnknownError()
+ raise SaneUnknownError(
+ 'sane_open returned an invalid status.')
assert self._handle != c_void_p(None)
if self._log:
self._log.debug('Device %s open.', self._name)
self._update_options()
def is_open(self):
"""
Return true if there is an active handle to this device.
"""
return (self._handle is not None)
def close(self):
"""
Close the current handle to this device. All changes made
to its options will be lost.
"""
assert self._handle is not None
assert self._handle != c_void_p(None)
sane_close(self._handle)
self._handle = None
if self._log:
self._log.debug('Device %s closed.', self._name)
def scan(self, progress_callback=None):
- #TODO
+ """
+ Scan a document using this device.
+
+ @param progress_callback: An optional callback that
+ will be called each time data is read from
+ the device. Has the format:
+ cancel = progress_callback(sane_info, bytes_read)
+ @return: A PIL image containing the scanned
+ page.
+ """
assert self._handle is not None
assert self._handle != c_void_p(None)
+ # See SANE API 4.3.9
status = sane_start(self._handle)
- print status
+
+ if status == SANE_STATUS_GOOD.value:
+ pass
+ elif status == SANE_STATUS_CANCELLED.value:
+ raise AssertionError(
+ 'sane_start reported cancelled status before it was set.')
+ elif status == SANE_STATUS_DEVICE_BUSY.value:
+ raise SaneDeviceBusyError(
+ 'sane_start reported the device was in use.')
+ elif status == SANE_STATUS_JAMMED.value:
+ raise SaneDeviceJammedError(
+ 'sane_start reported a paper jam.')
+ elif status == SANE_STATUS_NO_DOCS.value:
+ raise SaneNoDocumentsError(
+ 'sane_start reported that the document feeder was empty.')
+ elif status == SANE_STATUS_COVER_OPEN.value:
+ raise SaneCoverOpenError(
+ 'sane_start reported that the device cover was open.')
+ elif status == SANE_STATUS_IO_ERROR.value:
+ raise SaneIOError(
+ 'sane_start encountered a communications error.')
+ elif status == SANE_STATUS_NO_MEM.value:
+ raise SaneOutOfMemoryError(
+ 'sane_start ran out of memory.')
+ elif status == SANE_STATUS_INVAL.value:
+ #TODO - see docs
+ raise SaneInvalidDataError()
+ else:
+ raise SaneUnknownError(
+ 'sane_start returned an invalid status.')
sane_parameters = SANE_Parameters()
+ # See SANE API 4.3.8
status = sane_get_parameters(self._handle, byref(sane_parameters))
if status != SANE_STATUS_GOOD.value:
raise SaneUnknownError()
scan_info = ScanInfo(sane_parameters)
- bytes_per_read = 48 #should be multiple of 3 (for RGB)
+ # Should be a multiple of three (for RGB data) and a reasonable size
+ # so that the progress callback will occur frequently without spamming.
+ bytes_per_read = 4800
data_array = array('B')
temp_array = (SANE_Byte * bytes_per_read)()
actual_size = SANE_Int()
while True:
+ # See SANE API 4.3.10
status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
if status == SANE_STATUS_GOOD.value:
- data_array.extend(temp_array[0:actual_size.value])
+ pass
elif status == SANE_STATUS_EOF.value:
break
elif status == SANE_STATUS_CANCELLED.value:
return None
elif status == SANE_STATUS_JAMMED.value:
- #TODO
- pass
+ raise SaneDeviceJammedError(
+ 'sane_read reported a paper jam.')
elif status == SANE_STATUS_NO_DOCS.value:
- #TODO
- pass
+ raise SaneNoDocumentsError(
+ 'sane_read reported that the document feeder was empty.')
elif status == SANE_STATUS_COVER_OPEN.value:
- #TODO
- pass
+ raise SaneCoverOpenError(
+ 'sane_read reported that the device cover was open.')
elif status == SANE_STATUS_IO_ERROR.value:
- #TODO
- pass
+ raise SaneIOError(
+ 'sane_read encountered a communications error.')
elif status == SANE_STATUS_NO_MEM.value:
- #TODO
- pass
+ raise SaneOutOfMemoryError(
+ 'sane_read ran out of memory.')
elif status == SANE_STATUS_ACCESS_DENIED.value:
- #TODO
- pass
+ raise SaneAccessDeniedError(
+ 'sane_read requires greater access to open the device.')
else:
- raise SaneUnknownError()
+ raise SaneUnknownError(
+ 'sane_read returned an invalid status.')
+
+ data_array.extend(temp_array[0:actual_size.value])
- # TODO
if progress_callback:
cancel = progress_callback(scan_info, len(data_array))
if cancel:
sane_cancel(self._handle)
-
- sane_cancel(self._handle)
+
+ if not cancel:
+ sane_cancel(self._handle)
assert scan_info.total_bytes == len(data_array)
if sane_parameters.format == SANE_FRAME_GRAY.value:
- pil_image = Image.fromstring('L', (scan_info.width, scan_info.height), data_array.tostring())
+ pil_image = Image.frombuffer(
+ 'L', (scan_info.width, scan_info.height),
+ data_array, 'raw', 'L', 0, 1)
elif sane_parameters.format == SANE_FRAME_RGB.value:
- pil_image = Image.fromstring('RGB', (scan_info.width, scan_info.height), data_array.tostring())
+ pil_image = Image.frombuffer(
+ 'RGB', (scan_info.width, scan_info.height),
+ data_array, 'raw', 'L', 0, 1)
else:
- # TODO
+ # TODO - seperate frames for R, G, and B
raise NotImplementedError()
return pil_image
-
- def cancel_scan(self):
- #TODO
- assert self._handle is not None
- assert self._handle != c_void_p(None)
class Option(object):
"""
Represents a single option available for a device. Exposes
a variety of information designed to make it easy for a GUI
to render each arbitrary option in a user-friendly way.
"""
log = None
_device = None
_option_number = 0
_name = ''
_title = ''
_description = ''
_type = 0
_unit = 0
_size = 0
_capabilities = 0
_constraint_type = 0
_constraint_string_list = []
_constraint_word_list = []
_constraint_range = ()
def __init__(self, device, option_number, ctypes_option, log=None):
"""
Construct the option from a given ctypes SANE_Option_Descriptor.
Parse the necessary constraint information from the
SANE_Constraint and SANE_Range structures.
"""
self._log = log
self._device = device
self._option_number = option_number
assert type(ctypes_option.name) is StringType
assert type(ctypes_option.title) is StringType
assert type(ctypes_option.desc) is StringType
assert type(ctypes_option.type) is IntType
assert type(ctypes_option.unit) is IntType
assert type(ctypes_option.size) is IntType
assert type(ctypes_option.cap) is IntType
assert type(ctypes_option.constraint_type) is IntType
self._name = ctypes_option.name
self._title = ctypes_option.title
self._description = ctypes_option.desc
self._type = ctypes_option.type
self._unit = ctypes_option.unit
self._size = ctypes_option.size
self._capability = ctypes_option.cap
self._constraint_type = ctypes_option.constraint_type
if self._constraint_type == SANE_CONSTRAINT_NONE.value:
pass
elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
assert type(ctypes_option.constraint.range.contents.min) is IntType
assert type(ctypes_option.constraint.range.contents.max) is IntType
assert type(ctypes_option.constraint.range.contents.quant) is IntType
self._constraint_range = (
ctypes_option.constraint.range.contents.min,
ctypes_option.constraint.range.contents.max,
ctypes_option.constraint.range.contents.quant)
elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
word_count = ctypes_option.constraint.word_list[0]
self._constraint_word_list = []
i = 1
while(i < word_count):
self._constraint_word_list.append(ctypes_option.constraint.word_list[i])
i = i + 1
elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
-
+
string_count = 0
self._constraint_string_list = []
while ctypes_option.constraint.string_list[string_count]:
- self._constraint_word_list.append(ctypes_option.constraint.string_list[string_count])
+ self._constraint_string_list.append(ctypes_option.constraint.string_list[string_count])
string_count += 1
# Read only properties
def __get_name(self):
"""Get the short-form name of this option, e.g. 'mode'."""
return self._name
name = property(__get_name)
def __get_title(self):
"""Get the full name of this option, e.g. 'Scan mode'."""
return self._title
title = property(__get_title)
def __get_description(self):
"""
Get the full description of this option,
e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
"""
return self._description
description = property(__get_description)
def __get_type(self):
# TODO: convert to Python types at creation?
return self._type
type = property(__get_type)
def __get_unit(self):
# TODO: convert to string representation at creation?
return self._unit
unit = property(__get_unit)
def __get_size(self):
# TODO: hide from user view?
return self._size
size = property(__get_size)
def __get_capability(self):
- # TODO: hide from user view?
+ # TODO: recast into a dictionary?
return self._capability
capability = property(__get_capability)
def __get_constraint_type(self):
- # TODO: recast into a module-local Python enumeration?
return self._constraint_type
constraint_type = property(__get_constraint_type)
def __get_constraint_string_list(self):
- """Get a list of strings which are valid values for this option."""
- return self.__constraint_string_list
+ """
+ Get a list of strings which are valid values for this option.
+
+ Only relevant if constraint_type is OPTION_CONSTRAINT_STRING_LIST.
+ """
+ return self._constraint_string_list
constraint_string_list = property(__get_constraint_string_list)
def __get_constraint_word_list(self):
- """Get a list of integers that are valid values for this option."""
+ """
+ Get a list of integers that are valid values for this option.
+
+ Only relevant if constraint_type is OPTION_CONSTRAINT_WORD_LIST.
+ """
return self._constraint_word_list
constraint_word_list = property(__get_constraint_word_list)
def __get_constraint_range(self):
"""
Get a tuple containing the (minimum, maximum, step) of
valid values for this option.
+
+ Only relevant if constraint_type is OPTION_CONSTRAINT_RANGE.
"""
return self._constraint_range
constraint_range = property(__get_constraint_range)
def __get_value(self):
"""
Get the current value of this option.
"""
handle = self._device._get_handle()
if self._type == SANE_TYPE_BOOL.value:
option_value = pointer(SANE_Bool())
elif self._type == SANE_TYPE_INT.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Int())
elif self._type == SANE_TYPE_FIXED.value:
# TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
option_value = pointer(SANE_Fixed())
elif self._type == SANE_TYPE_STRING.value:
# sane_control_option expects a mutable string buffer
option_value = create_string_buffer(self._size)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
- # TODO: handle statuses/exceptions
+ if status == SANE_STATUS_GOOD.value:
+ pass
+ elif status == SANE_STATUS_UNSUPPORTED.value:
+ # TODO - should never happen if we check cap's before setting
+ pass
+ elif status == SANE_STATUS_INVAL.value:
+ raise AssertionError(
+ 'sane_control_option reported a value was invalid, but no values was being set.')
+ elif status == SANE_STATUS_IO_ERROR.value:
+ raise SaneIOError(
+ 'sane_control_option reported a communications error.')
+ elif status == SANE_STATUS_NO_MEM.value:
+ raise SaneOutOfMemoryError(
+ 'sane_control_option ran out of memory.')
+ elif status == SANE_STATUS_ACCESS_DENIED.value:
+ raise SaneAccessDeniedError(
+ 'sane_control_option requires greater access to open the device.')
+ else:
+ raise SaneUnknownError(
+ 'sane_control_option returned an invalid status.')
if self._type == SANE_TYPE_STRING.value:
option_value = option_value.value
else:
option_value = option_value.contents.value
if self._log:
self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
return option_value
def __set_value(self, value):
"""
Set the current value of this option.
"""
handle = self._device._get_handle()
+ c_value = None
+
+ # Type checking
if self._type == SANE_TYPE_BOOL.value:
- assert type(value) is BoolType
+ assert type(value) is BooleanType
+ c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_INT.value:
+ # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
+ c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_FIXED.value:
+ # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
assert type(value) is IntType
+ c_value = pointer(c_int(value))
elif self._type == SANE_TYPE_STRING.value:
assert type(value) is StringType
+ assert len(value) + 1 < self._size
+ c_value = c_char_p(value)
elif self._type == SANE_TYPE_BUTTON.value:
raise TypeError('SANE_TYPE_BUTTON has no value.')
elif self._type == SANE_TYPE_GROUP.value:
raise TypeError('SANE_TYPE_GROUP has no value.')
else:
raise TypeError('Option is of unknown type.')
+
+ # Constraint checking
+ if self._constraint_type == SANE_CONSTRAINT_NONE.value:
+ pass
+ elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
+ assert value >= self._constraint_range[0]
+ assert value <= self._constraint_range[1]
+ assert value % self._constraint_range[2] == 0
+ elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
+ assert value in self._constraint_word_list
+ elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
+ assert value in self._constraint_string_list
info_flags = SANE_Int()
- # TODO: When to use SANE_ACTION_SET_AUTO?
status = sane_control_option(
- handle, self._option_number, SANE_ACTION_SET_VALUE, value, byref(info_flags))
+ handle, self._option_number, SANE_ACTION_SET_VALUE, c_value, byref(info_flags))
- # TODO: handle statuses/exceptions
+ if status == SANE_STATUS_GOOD.value:
+ pass
+ elif status == SANE_STATUS_UNSUPPORTED.value:
+ # TODO - should never happen if we check cap's before setting
+ pass
+ elif status == SANE_STATUS_INVAL.value:
+ raise AssertionError(
+ 'sane_control_option reported that the value to be set was invalid, despite checks.')
+ elif status == SANE_STATUS_IO_ERROR.value:
+ raise SaneIOError(
+ 'sane_control_option reported a communications error.')
+ elif status == SANE_STATUS_NO_MEM.value:
+ raise SaneOutOfMemoryError(
+ 'sane_control_option ran out of memory.')
+ elif status == SANE_STATUS_ACCESS_DENIED.value:
+ raise SaneAccessDeniedError(
+ 'sane_control_option requires greater access to open the device.')
+ else:
+ raise SaneUnknownError(
+ 'sane_control_option returned an invalid status.')
- # TODO: parse and respond to flags, see SANE docs 4.3.7
- #print info_flags
+ # TODO: handle statuses/exceptions
if self._log:
self._log.debug('Option %s set to value %s.', self._name, value)
+ # See SANE API 4.3.7
+ if info_flags.value & SANE_INFO_RELOAD_OPTIONS:
+ raise SaneReloadOptionsError()
+
value = property(__get_value, __set_value)
class ScanInfo(object):
"""
Contains the parameters and progress of a scan in progress.
"""
_width = 0
_height = 0
_depth = 0
_total_bytes = 0
def __init__(self, sane_parameters):
"""
Initialize the ScanInfo object from the sane_parameters.
"""
self._width = sane_parameters.pixels_per_line
self._height = sane_parameters.lines
self._depth = sane_parameters.depth
self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
# Read only properties
def __get_width(self):
"""Get the width of the current scan, in pixels."""
return self._width
width = property(__get_width)
def __get_height(self):
"""Get the height of the current scan, in pixels."""
return self._height
height = property(__get_height)
def __get_depth(self):
"""Get the depth of the current scan, in bits."""
return self._depth
depth = property(__get_depth)
def __get_total_bytes(self):
"""Get the total number of bytes comprising this scan."""
return self._total_bytes
total_bytes = property(__get_total_bytes)
if __name__ == '__main__':
+ def progress_callback(sane_info, bytes_read):
+ #print float(bytes_read) / sane_info.total_bytes
+ pass
+
import logging
log_format = FORMAT = "%(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
sane = SANE(logging.getLogger())
sane.setup()
sane.update_devices()
for dev in sane.devices:
print dev.name
sane.devices[0].open()
print sane.devices[0].options.keys()
- print sane.devices[0].options['mode'].value
- sane.devices[0].options['mode'].value = 'Color'
- print sane.devices[0].options['mode'].value
+ try:
+ sane.devices[0].options['mode'].value = 'Gray'
+ except SaneReloadOptionsError:
+ pass
+
+ try:
+ sane.devices[0].options['resolution'].value = 75
+ except SaneReloadOptionsError:
+ pass
+
+ try:
+ sane.devices[0].options['preview'].value = False
+ except SaneReloadOptionsError:
+ pass
- sane.devices[0].scan().save('out.bmp')
+ sane.devices[0].scan(progress_callback).save('out.bmp')
sane.devices[0].close()
sane.shutdown()
\ No newline at end of file
|
onyxfish/nostaples
|
2a59a4d0c496bbf7bbb4c948b666debb9089ca85
|
Renamed to SaneMe (Scanner Access Now Even More Easy).
|
diff --git a/sane/__init__.py b/sane/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/sane/errors.py b/sane/errors.py
new file mode 100644
index 0000000..bfbf3a1
--- /dev/null
+++ b/sane/errors.py
@@ -0,0 +1,130 @@
+#!/usr/bin/python
+
+#~ This file is part of SaneMe.
+
+#~ SaneMe is free software: you can redistribute it and/or modify
+#~ it under the terms of the GNU General Public License as published by
+#~ the Free Software Foundation, either version 3 of the License, or
+#~ (at your option) any later version.
+
+#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
+
+"""
+This module contains the Python exceptions which take the place
+of SANE's status codes in the Pythonic reimplementation of the API.
+These are the errors that users will need to handle.
+"""
+
+# TODO: add detail parameters, e.g.: SaneUnsupportedOperationError should include the device as an attribute
+
+class SaneError(Exception):
+ """
+ Base class for all SANE Errors.
+ """
+ pass
+
+class SaneUnknownError(SaneError):
+ """
+ Exception denoting an error within the SANE library that could
+ not be categorized.
+ """
+ pass
+
+class SaneUnsupportedOperationError(SaneError):
+ """
+ Exception denoting an unsupported operation was requested.
+
+ Corresponds to SANE status code SANE_STATUS_UNSUPPORTED.
+ """
+ pass
+
+class SaneCancelledOperationError(SaneError):
+ """
+ TODO: when is this called
+
+ Corresponds to SANE status code SANE_STATUS_CANCELLED.
+ """
+ pass
+
+class SaneDeviceBusyError(SaneError):
+ """
+ Exception denoting that the requested device is being
+ accessed by another process.
+
+ Corresponds to SANE status code SANE_STATUS_DEVICE_BUSY.
+ """
+ pass
+
+class SaneInvalidDataError(SaneError):
+ """
+ Exception denoting that some data or argument was not
+ valid.
+
+ Corresponds to SANE status code SANE_STATUS_INVAL.
+ """
+ pass
+
+class SaneEndOfFileError(SaneError):
+ """
+ TODO: Should the user ever see this? probably handled internally
+
+ Corresponds to SANE status code SANE_STATUS_EOF.
+ """
+ pass
+
+class SaneDeviceJammedError(SaneError):
+ """
+ Exception denoting that the device is jammed.
+
+ Corresponds to SANE status code SANE_STATUS_JAMMED.
+ """
+ pass
+
+class SaneNoDocumentsError(SaneError):
+ """
+ Exception denoting that there are pages in the document
+ feeder of the device.
+
+ Corresponds to SANE status code SANE_STATUS_NO_DOCS.
+ """
+ pass
+
+class SaneCoverOpenError(SaneError):
+ """
+ Exception denoting that the cover of the device is open.
+
+ Corresponds to SANE status code SANE_STATUS_COVER_OPEN.
+ """
+ pass
+
+class SaneIOError(SaneError):
+ """
+ Exception denoting that an IO error occurred while
+ communicating wtih the device.
+
+ Corresponds to the SANE status code SANE_STATUS_IO_ERROR.
+ """
+ pass
+
+class SaneOutOfMemoryError(SaneError):
+ """
+ Exception denoting that SANE ran out of memory during an
+ operation.
+
+ Corresponds to the SANE status code SANE_STATUS_NO_MEM.
+ """
+ pass
+
+class SaneAccessDeniedError(SaneError):
+ """
+ TODO: should this be handled in a special way?
+
+ Corresponds to the SANE status code SANE_STATUS_ACCESS_DENIED.
+ """
+ pass
\ No newline at end of file
diff --git a/sane/saneh.py b/sane/saneh.py
new file mode 100644
index 0000000..4759eaa
--- /dev/null
+++ b/sane/saneh.py
@@ -0,0 +1,352 @@
+#!/bin/python
+
+#~ This file is part of SaneMe.
+
+#~ SaneMe is free software: you can redistribute it and/or modify
+#~ it under the terms of the GNU General Public License as published by
+#~ the Free Software Foundation, either version 3 of the License, or
+#~ (at your option) any later version.
+
+#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
+"""
+This module contains the apples to apples conversion of the sane.h
+header file to a Python/ctypes API. Pains have been taken to
+reproduce all typedefs, definitions, enumerations, structures, and
+function prototypes as faithfully as possible. Ctypes argtypes and
+restype attributes have been used to apply type checking to the
+function declarations.
+"""
+
+from ctypes import *
+from ctypes.util import find_library
+
+# LOAD LIBRARY
+
+sane_path = find_library('sane')
+libsane = cdll.LoadLibrary(sane_path)
+
+# DEFINITIONS
+
+#define SANE_VERSION_MAJOR(code) ((((SANE_Word)(code)) >> 24) & 0xff)
+def SANE_VERSION_MAJOR(code):
+ return (code.value >> 24) & 0xff
+
+#define SANE_VERSION_MINOR(code) ((((SANE_Word)(code)) >> 16) & 0xff)
+def SANE_VERSION_MINOR(code):
+ return (code.value >> 16) & 0xff
+
+#define SANE_VERSION_BUILD(code) ((((SANE_Word)(code)) >> 0) & 0xffff)
+def SANE_VERSION_BUILD(code):
+ return (code.value >> 0) & 0xffff
+
+#define SANE_FIXED_SCALE_SHIFT 16
+SANE_FIXED_SCALE_SHIFT = 16
+
+#define SANE_FIX(v) ((SANE_Word) ((v) * (1 << SANE_FIXED_SCALE_SHIFT)))
+def SANE_FIX(v):
+ return v * (1 << SANE_FIXED_SCALE_SHIFT)
+
+#define SANE_UNFIX(v) ((double)(v) / (1 << SANE_FIXED_SCALE_SHIFT))
+def SANE_UNFIX(v):
+ return v / (1 << SANE_FIXED_SCALE_SHIFT)
+
+#define SANE_CAP_SOFT_SELECT (1 << 0)
+SANE_CAP_SOFT_SELECT = 1 << 0
+
+#define SANE_CAP_HARD_SELECT (1 << 1)
+SANE_CAP_HARD_SELECT = 1 << 1
+
+#define SANE_CAP_SOFT_DETECT (1 << 2)
+SANE_CAP_SOFT_DETECT = 1 << 2
+
+#define SANE_CAP_EMULATED (1 << 3)
+SANE_CAP_EMULATED = 1 << 3
+
+#define SANE_CAP_AUTOMATIC (1 << 4)
+SANE_CAP_AUTOMATIC = 1 << 4
+
+#define SANE_CAP_INACTIVE (1 << 5)
+SANE_CAP_INACTIVE = 1 << 5
+
+#define SANE_CAP_ADVANCED (1 << 6)
+SANE_CAP_ADVANCED = 1 << 6
+
+#define SANE_CAP_ALWAYS_SETTABLE (1 << 7)
+SANE_CAP_ALWAYS_SETTABLE = 1 << 7
+
+#define SANE_OPTION_IS_ACTIVE(cap) (((cap) & SANE_CAP_INACTIVE) == 0)
+def SANE_OPTION_IS_ACTIVE(cap):
+ return ((cap & SANE_CAP_INACTIVE) == 0)
+
+#define SANE_OPTION_IS_SETTABLE(cap) (((cap) & SANE_CAP_SOFT_SELECT) != 0)
+def SANE_OPTION_IS_SETTABLE(cap):
+ return ((cap & SANE_CAP_SOFT_SELECT) != 0)
+
+#define SANE_INFO_INEXACT (1 << 0)
+SANE_INFO_INEXACT = 1 << 0
+
+#define SANE_INFO_RELOAD_OPTIONS (1 << 1)
+SANE_INFO_RELOAD_OPTIONS = 1 << 1
+
+#define SANE_INFO_RELOAD_PARAMS (1 << 2)
+SANE_INFO_RELOAD_PARAMS = 1 << 2
+
+#define SANE_MAX_USERNAME_LEN 128
+SANE_MAX_USERNAME_LEN = 128
+
+#define SANE_MAX_PASSWORD_LEN 128
+SANE_MAX_PASSWORD_LEN = 128
+
+# TYPEDEFS
+
+SANE_Byte = c_ubyte
+SANE_Word = c_int
+SANE_Bool = SANE_Word
+SANE_Int = SANE_Word
+SANE_Char = c_char
+SANE_String = c_char_p
+SANE_String_Const = c_char_p
+SANE_Handle = c_void_p
+SANE_Fixed = SANE_Word
+
+# ENUMERATIONS
+
+# SANE_Status
+SANE_Status = c_int
+
+(SANE_STATUS_GOOD,
+ SANE_STATUS_UNSUPPORTED,
+ SANE_STATUS_CANCELLED,
+ SANE_STATUS_DEVICE_BUSY,
+ SANE_STATUS_INVAL,
+ SANE_STATUS_EOF,
+ SANE_STATUS_JAMMED,
+ SANE_STATUS_NO_DOCS,
+ SANE_STATUS_COVER_OPEN,
+ SANE_STATUS_IO_ERROR,
+ SANE_STATUS_NO_MEM,
+ SANE_STATUS_ACCESS_DENIED) = map(c_int, xrange(12))
+
+# SANE_Value_Type
+SANE_Value_Type = c_int
+
+(SANE_TYPE_BOOL,
+ SANE_TYPE_INT,
+ SANE_TYPE_FIXED,
+ SANE_TYPE_STRING,
+ SANE_TYPE_BUTTON,
+ SANE_TYPE_GROUP) = map(c_int, xrange(6))
+
+# SANE_Unit
+SANE_Unit = c_int
+
+(SANE_UNIT_NONE,
+ SANE_UNIT_PIXEL,
+ SANE_UNIT_BIT,
+ SANE_UNIT_MM,
+ SANE_UNIT_DPI,
+ SANE_UNIT_PERCENT,
+ SANE_UNIT_MICROSECOND) = map(c_int, xrange(7))
+
+# SANE_Constraint_Type
+SANE_Constraint_Type = c_int
+
+(SANE_CONSTRAINT_NONE,
+ SANE_CONSTRAINT_RANGE,
+ SANE_CONSTRAINT_WORD_LIST,
+ SANE_CONSTRAINT_STRING_LIST) = map(c_int, xrange(4))
+
+# SANE_Action
+SANE_Action = c_int
+
+(SANE_ACTION_GET_VALUE ,
+ SANE_ACTION_SET_VALUE,
+ SANE_ACTION_SET_AUTO) = map(c_int, xrange(3))
+
+# SANE_Frame
+SANE_Frame = c_int
+
+(SANE_FRAME_GRAY,
+ SANE_FRAME_RGB,
+ SANE_FRAME_RED,
+ SANE_FRAME_GREEN,
+ SANE_FRAME_BLUE) = map(c_int, xrange(5))
+
+(SANE_FRAME_TEXT,
+ SANE_FRAME_JPEG,
+ SANE_FRAME_G31D,
+ SANE_FRAME_G32D,
+ SANE_FRAME_G42D,
+ SANE_FRAME_IR,
+ SANE_FRAME_RGBI,
+ SANE_FRAME_GRAYI) = map(c_int, xrange(10, 18))
+
+# STRUCTURES & UNIONS
+
+class SANE_Range(Structure):
+ _fields_ = [
+ ("min", SANE_Word),
+ ("max", SANE_Word),
+ ("quant", SANE_Word)]
+
+class SANE_Constraint(Union):
+ _fields_ = [
+ ("string_list", POINTER(SANE_String_Const)),
+ ("word_list", POINTER(SANE_Word)),
+ ("range", POINTER(SANE_Range))]
+
+class SANE_Option_Descriptor(Structure):
+ _fields_ = [
+ ("name", SANE_String_Const),
+ ("title", SANE_String_Const),
+ ("desc", SANE_String_Const),
+ ("type", SANE_Value_Type),
+ ("unit", SANE_Unit),
+ ("size", SANE_Int),
+ ("cap", SANE_Int),
+ ("constraint_type", SANE_Constraint_Type),
+ ("constraint", SANE_Constraint)]
+
+class SANE_Device(Structure):
+ _fields_ = [
+ ("name", SANE_String_Const),
+ ("vendor", SANE_String_Const),
+ ("model", SANE_String_Const),
+ ("type", SANE_String_Const)]
+
+class SANE_Parameters(Structure):
+ _fields_ = [
+ ("format", SANE_Frame),
+ ("last_frame", SANE_Bool),
+ ("bytes_per_line", SANE_Int),
+ ("pixels_per_line", SANE_Int),
+ ("lines", SANE_Int),
+ ("depth", SANE_Int)]
+
+# CALLBACKS
+
+#typedef void (*SANE_Auth_Callback) (SANE_String_Const resource, SANE_Char *username, SANE_Char *password);
+SANE_Auth_Callback = CFUNCTYPE(SANE_String_Const, POINTER(SANE_Char), POINTER(SANE_Char))
+
+# FUNCTION PROTOTYPES
+
+#extern SANE_Status sane_init (SANE_Int * version_code, SANE_Auth_Callback authorize);
+sane_init = libsane.sane_init
+sane_init.argtypes = [POINTER(SANE_Int), SANE_Auth_Callback]
+sane_init.restype = SANE_Status
+
+#extern void sane_exit (void);
+sane_exit = libsane.sane_exit
+
+#extern SANE_Status sane_get_devices (const SANE_Device *** device_list, SANE_Bool local_only);
+sane_get_devices = libsane.sane_get_devices
+sane_get_devices.argtypes = [POINTER(POINTER(POINTER(SANE_Device))), SANE_Bool]
+sane_get_devices.restype = SANE_Status
+
+#extern SANE_Status sane_open (SANE_String_Const devicename, SANE_Handle * handle);
+sane_open = libsane.sane_open
+sane_open.argtypes = [SANE_String_Const, POINTER(SANE_Handle)]
+sane_open.restype = SANE_Status
+
+#extern void sane_close (SANE_Handle handle);
+sane_close = libsane.sane_close
+sane_close.argtypes = [SANE_Handle]
+
+#extern const SANE_Option_Descriptor * sane_get_option_descriptor (SANE_Handle handle, SANE_Int option);
+sane_get_option_descriptor = libsane.sane_get_option_descriptor
+sane_get_option_descriptor.argtypes = [SANE_Handle, SANE_Int]
+sane_get_option_descriptor.restype = POINTER(SANE_Option_Descriptor)
+
+#extern SANE_Status sane_control_option (SANE_Handle handle, SANE_Int option, SANE_Action action, void *value, SANE_Int * info);
+sane_control_option = libsane.sane_control_option
+sane_control_option.argtypes = [SANE_Handle, SANE_Int, SANE_Action, c_void_p, POINTER(SANE_Int)]
+sane_control_restype = SANE_Status
+
+#extern SANE_Status sane_get_parameters (SANE_Handle handle, SANE_Parameters * params);
+sane_get_parameters = libsane.sane_get_parameters
+sane_get_parameters.argtypes = [SANE_Handle, POINTER(SANE_Parameters)]
+sane_get_parameters.restype = SANE_Status
+
+#extern SANE_Status sane_start (SANE_Handle handle);
+sane_start = libsane.sane_start
+sane_start.argtypes = [SANE_Handle]
+sane_start.restype = SANE_Status
+
+#extern SANE_Status sane_read (SANE_Handle handle, SANE_Byte * data, SANE_Int max_length, SANE_Int * length);
+sane_read = libsane.sane_read
+sane_read.argtypes = [SANE_Handle, POINTER(SANE_Byte), SANE_Int, POINTER(SANE_Int)]
+sane_read.restype = SANE_Status
+
+#extern void sane_cancel (SANE_Handle handle);
+sane_cancel = libsane.sane_cancel
+sane_cancel.argtypes = [SANE_Handle]
+
+#extern SANE_Status sane_set_io_mode (SANE_Handle handle, SANE_Bool non_blocking);
+sane_set_io_mode = libsane.sane_set_io_mode
+sane_set_io_mode.argtypes = [SANE_Handle, SANE_Bool]
+sane_set_io_mode.restype = SANE_Status
+
+#extern SANE_Status sane_get_select_fd (SANE_Handle handle, SANE_Int * fd);
+sane_get_select_fd = libsane.sane_get_select_fd
+sane_get_select_fd.argtypes = [SANE_Handle, POINTER(SANE_Int)]
+sane_get_select_fd.restype = SANE_Status
+
+#extern SANE_String_Const sane_strstatus (SANE_Status status);
+sane_strstatus = libsane.sane_strstatus
+sane_strstatus.argtypes = [SANE_Status]
+sane_strstatus.restype = SANE_String_Const
+
+# HELPER FUNCTIONS (TEMP)
+
+def sane_status_to_string(status):
+ sane_strstatus = libsane.sane_strstatus
+ sane_strstatus.restype = SANE_String_Const
+ return sane_strstatus(status)
+
+def sane_auth_callback(resource, username, password):
+ print resource, username, password
+
+if __name__ == "__main__":
+ version_code = SANE_Int(0)
+ callback = SANE_Auth_Callback(sane_auth_callback)
+ status = sane_init(byref(version_code), callback)
+
+ print sane_status_to_string(status)
+ print SANE_VERSION_MAJOR(version_code), SANE_VERSION_MINOR(version_code), SANE_VERSION_BUILD(version_code)
+
+ #it stores a pointer to a NULL terminated array of pointers to SANE_Device structures in *device_list.
+
+ devices = POINTER(POINTER(SANE_Device))()
+
+ status = sane_get_devices(byref(devices), SANE_Bool(0))
+
+ num_devices = 0
+ # Convert NULL-terminated C list into Python list
+ device_list = []
+ while devices[num_devices]:
+ device_list.append(devices[num_devices].contents) # use .contents here since each entry in the C list is itself a pointer
+ num_devices += 1
+
+ print device_list, len(device_list), device_list[0].name
+
+ handle = SANE_Handle()
+
+ status = sane_open(device_list[0].name, byref(handle))
+
+ print sane_status_to_string(status), handle
+
+ status = sane_start(handle)
+
+ print sane_status_to_string(status)
+
+
+
+ sane_close(handle)
+
+ sane_exit()
\ No newline at end of file
diff --git a/sane/saneme.py b/sane/saneme.py
new file mode 100644
index 0000000..d199ae7
--- /dev/null
+++ b/sane/saneme.py
@@ -0,0 +1,733 @@
+#!/usr/bin/python
+
+#~ This file is part of SaneMe.
+
+#~ SaneMe is free software: you can redistribute it and/or modify
+#~ it under the terms of the GNU General Public License as published by
+#~ the Free Software Foundation, either version 3 of the License, or
+#~ (at your option) any later version.
+
+#~ SaneMe 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 SaneMe. If not, see <http://www.gnu.org/licenses/>.
+
+"""
+This module contains the Pythonic implementation of the SANE API.
+The flat C functions have been wrapped in a set of objects and all
+ctypes of the underlying implmentation have been hidden from the
+user's view. This enumerations and definiations which are absolutely
+necessary to the end user have been redeclared.
+"""
+
+# TODO: document what exceptions can be thrown by each method
+
+from array import *
+import ctypes
+from types import *
+
+from PIL import Image
+
+from errors import *
+from saneh import *
+
+# Redeclare saneh enumerations which are visible to the end user
+(OPTION_TYPE_BOOL,
+ OPTION_TYPE_INT,
+ OPTION_TYPE_FIXED,
+ OPTION_TYPE_STRING,
+ OPTION_TYPE_BUTTON,
+ OPTION_TYPE_GROUP) = xrange(6)
+
+(OPTION_UNIT_NONE,
+ OPTION_UNIT_PIXEL,
+ OPTION_UNIT_BIT,
+ OPTION_UNIT_MM,
+ OPTION_UNIT_DPI,
+ OPTION_UNIT_PERCENT,
+ OPTION_UNIT_MICROSECOND) = xrange(7)
+
+(OPTION_CONSTRAINT_NONE,
+ OPTION_CONSTRAINT_RANGE,
+ OPTION_CONSTRAINT_INTEGER_LIST,
+ OPTION_CONSTRAINT_STRING_LIST) = xrange(4)
+
+class SANE(object):
+ """
+ The top-level object for interacting with the SANE API. Handles
+ polling for devices. This object should only be instantiated once.
+ """
+ _log = None
+
+ _version = None # (major, minor, build)
+ _devices = []
+
+ def __init__(self, log=None):
+ """
+ Create the SANE object. Note that all functional setup of the
+ SANE object is deferred until the user explicitly calls L{init}.
+
+ @param log: an optional Python logging object to log to.
+ """
+ self._log = log
+
+ def __del__(self):
+ """
+ Verify that the SANE connectoin was terminated.
+ """
+ assert self._version is None
+
+ # Read only properties
+
+ def __get_version(self):
+ """Get the current installed version of SANE."""
+ return self._version
+
+ version = property(__get_version)
+
+ def __get_devices(self):
+ """
+ Get the list of available devices, as of the most recent call
+ to L{update_devices}.
+ """
+ return self._devices
+
+ devices = property(__get_devices)
+
+ # Public Methods
+
+ def setup(self):
+ """
+ Iniitalize SANE and retrieve the current installed version.
+ Optionally, set a logging object to receive debugging
+ information.
+
+ See L{exit} for an explanation of why this does not occur
+ in __init__.
+
+ TODO: handle the authentication callback
+
+ @raise SaneUnknownError: sane_init returned an invalid status.
+ """
+ version_code = SANE_Int()
+ callback = SANE_Auth_Callback(sane_auth_callback)
+
+ status = sane_init(byref(version_code), callback)
+
+ if status != SANE_STATUS_GOOD.value:
+ raise SaneUnknownError()
+
+ # TODO: handle status/exceptions
+
+ self._version = (SANE_VERSION_MAJOR(version_code),
+ SANE_VERSION_MINOR(version_code),
+ SANE_VERSION_BUILD(version_code))
+
+ if self._log:
+ self._log.debug('SANE version %s initalized.', self._version)
+
+ def shutdown(self):
+ """
+ Deinitialize SANE.
+
+ This code would go in __del__, but it is not guaranteed that method
+ will be called and sane_exit must be called to release resources. Thus
+ the parallel L{init} method for consistency.
+
+ TODO: close any open devices before exiting
+ """
+ sane_exit()
+ self._version = None
+
+ if self._log:
+ self._log.debug('SANE deinitialized.')
+
+ def update_devices(self):
+ """
+ Poll for connected devices.
+
+ @raise SaneOutOfMemoryError: sane_get_devices ran out of memory.
+ @raise SaneUnknownError: sane_get_devices returned an invalid status.
+ """
+ assert self._version is not None
+
+ cdevices = POINTER(POINTER(SANE_Device))()
+
+ status = sane_get_devices(byref(cdevices), SANE_Bool(0))
+
+ if status == SANE_STATUS_GOOD.value:
+ pass
+ elif status == SANE_STATUS_NO_MEM.value:
+ raise SaneOutOfMemoryError()
+ else:
+ raise SaneUnknownError()
+
+ device_count = 0
+ self._devices = []
+
+ while cdevices[device_count]:
+ self._devices.append(Device(cdevices[device_count].contents))
+ device_count += 1
+
+ if self._log:
+ self._log.debug('SANE queried, %i device(s) found.', device_count)
+
+class Device(object):
+ """
+ This is the primary object for interacting with SANE. It represents
+ a single device and handles enumeration of options, getting and
+ setting of options, and starting and stopping of scanning jobs.
+ """
+ _log = None
+
+ _handle = None
+
+ _name = ''
+ _vendor = ''
+ _model = ''
+ _type = ''
+
+ _options = {}
+
+ def __init__(self, ctypes_device, log=None):
+ """
+ Sets the Devices properties from a ctypes SANE_Device and
+ queries for its available options.
+ """
+ self._log = log
+
+ assert type(ctypes_device.name) is StringType
+ assert type(ctypes_device.vendor) is StringType
+ assert type(ctypes_device.model) is StringType
+ assert type(ctypes_device.type) is StringType
+
+ self._name = ctypes_device.name
+ self._vendor = ctypes_device.vendor
+ self._model = ctypes_device.model
+ self._type = ctypes_device.type
+
+ # Read only properties
+
+ def __get_name(self):
+ """
+ Get the complete SANE identifier for this device,
+ e.g. 'lexmark:libusb:002:006'.
+ """
+ return self._name
+
+ name = property(__get_name)
+
+ def __get_vendor(self):
+ """Get the manufacturer of this device, e.g. 'Lexmark'."""
+ return self._vendor
+
+ vendor = property(__get_vendor)
+
+ def __get_model(self):
+ """Get the specific model of this device, e.g. 'X1100/rev. B2'."""
+ return self._model
+
+ model = property(__get_model)
+
+ def __get_type(self):
+ """Get the type of this device, e.g. 'flatbed scanner'."""
+ return self._type
+
+ type = property(__get_type)
+
+ def __get_options(self):
+ """Get the list of options that this device has."""
+ return self._options
+
+ options = property(__get_options)
+
+ # Internal methods
+
+ def _update_options(self):
+ """
+ Update the list of available options for this device. As these
+ are immutable, this should only need to be called when the Device
+ is first instantiated.
+ """
+ assert self._handle is not None
+ assert self._handle != c_void_p(None)
+
+ option_value = pointer(c_int())
+ status = sane_control_option(self._handle, 0, SANE_ACTION_GET_VALUE, option_value, None)
+
+ # TODO: handle statuses/exceptions
+
+ option_count = option_value.contents.value
+
+ if self._log:
+ self._log.debug('Device queried, %i option(s) found.', option_count)
+
+ self._options.clear()
+
+ i = 1
+ while(i < option_count - 1):
+ coption = sane_get_option_descriptor(self._handle, i)
+ self._options[coption.contents.name] = Option(self, i, coption.contents)
+ i = i + 1
+
+ # Methods for use only by Options
+
+ def _get_handle(self):
+ """
+ Verify that the device is open and get the current open handle.
+
+ To be called by Options of this device so that they may set themselves.
+ """
+ assert self._handle is not None
+ assert self._handle != c_void_p(None)
+
+ return self._handle
+
+ # Public methods
+
+ def open(self):
+ """
+ Open a new handle to this device.
+
+ Must be called before any operations (including setting options)
+ are performed on this device.
+
+ @raise SaneDeviceBusyError: this device is in use by another process.
+ @raise SaneInvalidDataError: the device has been disconnected.
+ @raise SaneIOError: a communications error occurred with the device.
+ @raise SaneOutOfMemoryError: ran out of memory while opening the device.
+ @raise SaneAccessDeniedError: greater access is required to open the device.
+ @raise SaneUnknownError: sane_open returned an invalid status.
+ """
+ assert self._handle is None
+ self._handle = SANE_Handle()
+
+ status = sane_open(self.name, byref(self._handle))
+
+ if status == SANE_STATUS_GOOD.value:
+ pass
+ elif status == SANE_STATUS_DEVICE_BUSY.value:
+ raise SaneDeviceBusyError()
+ elif status == SANE_STATUS_INVAL.value:
+ raise SaneInvalidDataError()
+ elif status == SANE_STATUS_IO_ERROR.value:
+ raise SaneIOError()
+ elif status == SANE_STATUS_NO_MEM.value:
+ raise SaneOutOfMemoryError()
+ elif status == SANE_STATUS_ACCESS_DENIED.value:
+ # TODO
+ raise SaneAccessDeniedError()
+ else:
+ raise SaneUnknownError()
+
+ assert self._handle != c_void_p(None)
+
+ if self._log:
+ self._log.debug('Device %s open.', self._name)
+
+ self._update_options()
+
+ def is_open(self):
+ """
+ Return true if there is an active handle to this device.
+ """
+ return (self._handle is not None)
+
+ def close(self):
+ """
+ Close the current handle to this device. All changes made
+ to its options will be lost.
+ """
+ assert self._handle is not None
+ assert self._handle != c_void_p(None)
+
+ sane_close(self._handle)
+ self._handle = None
+
+ if self._log:
+ self._log.debug('Device %s closed.', self._name)
+
+ def scan(self, progress_callback=None):
+ #TODO
+ assert self._handle is not None
+ assert self._handle != c_void_p(None)
+
+ status = sane_start(self._handle)
+ print status
+
+ sane_parameters = SANE_Parameters()
+
+ status = sane_get_parameters(self._handle, byref(sane_parameters))
+
+ if status != SANE_STATUS_GOOD.value:
+ raise SaneUnknownError()
+
+ scan_info = ScanInfo(sane_parameters)
+
+ bytes_per_read = 48 #should be multiple of 3 (for RGB)
+
+ data_array = array('B')
+ temp_array = (SANE_Byte * bytes_per_read)()
+ actual_size = SANE_Int()
+
+ while True:
+ status = sane_read(self._handle, temp_array, bytes_per_read, byref(actual_size))
+
+ if status == SANE_STATUS_GOOD.value:
+ data_array.extend(temp_array[0:actual_size.value])
+ elif status == SANE_STATUS_EOF.value:
+ break
+ elif status == SANE_STATUS_CANCELLED.value:
+ return None
+ elif status == SANE_STATUS_JAMMED.value:
+ #TODO
+ pass
+ elif status == SANE_STATUS_NO_DOCS.value:
+ #TODO
+ pass
+ elif status == SANE_STATUS_COVER_OPEN.value:
+ #TODO
+ pass
+ elif status == SANE_STATUS_IO_ERROR.value:
+ #TODO
+ pass
+ elif status == SANE_STATUS_NO_MEM.value:
+ #TODO
+ pass
+ elif status == SANE_STATUS_ACCESS_DENIED.value:
+ #TODO
+ pass
+ else:
+ raise SaneUnknownError()
+
+ # TODO
+ if progress_callback:
+ cancel = progress_callback(scan_info, len(data_array))
+
+ if cancel:
+ sane_cancel(self._handle)
+
+ sane_cancel(self._handle)
+
+ assert scan_info.total_bytes == len(data_array)
+
+ if sane_parameters.format == SANE_FRAME_GRAY.value:
+ pil_image = Image.fromstring('L', (scan_info.width, scan_info.height), data_array.tostring())
+ elif sane_parameters.format == SANE_FRAME_RGB.value:
+ pil_image = Image.fromstring('RGB', (scan_info.width, scan_info.height), data_array.tostring())
+ else:
+ # TODO
+ raise NotImplementedError()
+
+ return pil_image
+
+ def cancel_scan(self):
+ #TODO
+ assert self._handle is not None
+ assert self._handle != c_void_p(None)
+
+class Option(object):
+ """
+ Represents a single option available for a device. Exposes
+ a variety of information designed to make it easy for a GUI
+ to render each arbitrary option in a user-friendly way.
+ """
+ log = None
+
+ _device = None
+ _option_number = 0
+
+ _name = ''
+ _title = ''
+ _description = ''
+ _type = 0
+ _unit = 0
+ _size = 0
+ _capabilities = 0
+ _constraint_type = 0
+
+ _constraint_string_list = []
+ _constraint_word_list = []
+ _constraint_range = ()
+
+ def __init__(self, device, option_number, ctypes_option, log=None):
+ """
+ Construct the option from a given ctypes SANE_Option_Descriptor.
+ Parse the necessary constraint information from the
+ SANE_Constraint and SANE_Range structures.
+ """
+ self._log = log
+
+ self._device = device
+ self._option_number = option_number
+
+ assert type(ctypes_option.name) is StringType
+ assert type(ctypes_option.title) is StringType
+ assert type(ctypes_option.desc) is StringType
+ assert type(ctypes_option.type) is IntType
+ assert type(ctypes_option.unit) is IntType
+ assert type(ctypes_option.size) is IntType
+ assert type(ctypes_option.cap) is IntType
+ assert type(ctypes_option.constraint_type) is IntType
+
+ self._name = ctypes_option.name
+ self._title = ctypes_option.title
+ self._description = ctypes_option.desc
+ self._type = ctypes_option.type
+ self._unit = ctypes_option.unit
+ self._size = ctypes_option.size
+ self._capability = ctypes_option.cap
+ self._constraint_type = ctypes_option.constraint_type
+
+ if self._constraint_type == SANE_CONSTRAINT_NONE.value:
+ pass
+ elif self._constraint_type == SANE_CONSTRAINT_RANGE.value:
+ assert type(ctypes_option.constraint.range) is POINTER(SANE_Range)
+ assert type(ctypes_option.constraint.range.contents.min) is IntType
+ assert type(ctypes_option.constraint.range.contents.max) is IntType
+ assert type(ctypes_option.constraint.range.contents.quant) is IntType
+
+ self._constraint_range = (
+ ctypes_option.constraint.range.contents.min,
+ ctypes_option.constraint.range.contents.max,
+ ctypes_option.constraint.range.contents.quant)
+ elif self._constraint_type == SANE_CONSTRAINT_WORD_LIST.value:
+ assert type(ctypes_option.constraint.word_list) is POINTER(SANE_Word)
+
+ word_count = ctypes_option.constraint.word_list[0]
+ self._constraint_word_list = []
+
+ i = 1
+ while(i < word_count):
+ self._constraint_word_list.append(ctypes_option.constraint.word_list[i])
+ i = i + 1
+ elif self._constraint_type == SANE_CONSTRAINT_STRING_LIST.value:
+ assert type(ctypes_option.constraint.string_list) is POINTER(SANE_String_Const)
+
+ string_count = 0
+ self._constraint_string_list = []
+
+ while ctypes_option.constraint.string_list[string_count]:
+ self._constraint_word_list.append(ctypes_option.constraint.string_list[string_count])
+ string_count += 1
+
+ # Read only properties
+
+ def __get_name(self):
+ """Get the short-form name of this option, e.g. 'mode'."""
+ return self._name
+
+ name = property(__get_name)
+
+ def __get_title(self):
+ """Get the full name of this option, e.g. 'Scan mode'."""
+ return self._title
+
+ title = property(__get_title)
+
+ def __get_description(self):
+ """
+ Get the full description of this option,
+ e.g. 'Selects the scan mode (e.g., lineart, monochrome, or color).'
+ """
+ return self._description
+
+ description = property(__get_description)
+
+ def __get_type(self):
+ # TODO: convert to Python types at creation?
+ return self._type
+
+ type = property(__get_type)
+
+ def __get_unit(self):
+ # TODO: convert to string representation at creation?
+ return self._unit
+
+ unit = property(__get_unit)
+
+ def __get_size(self):
+ # TODO: hide from user view?
+ return self._size
+
+ size = property(__get_size)
+
+ def __get_capability(self):
+ # TODO: hide from user view?
+ return self._capability
+
+ capability = property(__get_capability)
+
+ def __get_constraint_type(self):
+ # TODO: recast into a module-local Python enumeration?
+ return self._constraint_type
+
+ constraint_type = property(__get_constraint_type)
+
+ def __get_constraint_string_list(self):
+ """Get a list of strings which are valid values for this option."""
+ return self.__constraint_string_list
+
+ constraint_string_list = property(__get_constraint_string_list)
+
+ def __get_constraint_word_list(self):
+ """Get a list of integers that are valid values for this option."""
+ return self._constraint_word_list
+
+ constraint_word_list = property(__get_constraint_word_list)
+
+ def __get_constraint_range(self):
+ """
+ Get a tuple containing the (minimum, maximum, step) of
+ valid values for this option.
+ """
+ return self._constraint_range
+
+ constraint_range = property(__get_constraint_range)
+
+ def __get_value(self):
+ """
+ Get the current value of this option.
+ """
+ handle = self._device._get_handle()
+
+ if self._type == SANE_TYPE_BOOL.value:
+ option_value = pointer(SANE_Bool())
+ elif self._type == SANE_TYPE_INT.value:
+ # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
+ option_value = pointer(SANE_Int())
+ elif self._type == SANE_TYPE_FIXED.value:
+ # TODO: these may not always be a single char wide, see SANE doc 4.2.9.6
+ option_value = pointer(SANE_Fixed())
+ elif self._type == SANE_TYPE_STRING.value:
+ # sane_control_option expects a mutable string buffer
+ option_value = create_string_buffer(self._size)
+ elif self._type == SANE_TYPE_BUTTON.value:
+ raise TypeError('SANE_TYPE_BUTTON has no value.')
+ elif self._type == SANE_TYPE_GROUP.value:
+ raise TypeError('SANE_TYPE_GROUP has no value.')
+ else:
+ raise TypeError('Option is of unknown type.')
+
+ status = sane_control_option(handle, self._option_number, SANE_ACTION_GET_VALUE, option_value, None)
+
+ # TODO: handle statuses/exceptions
+
+ if self._type == SANE_TYPE_STRING.value:
+ option_value = option_value.value
+ else:
+ option_value = option_value.contents.value
+
+ if self._log:
+ self._log.debug('Option %s queried, its current value is %s.', self._name, option_value)
+
+ return option_value
+
+ def __set_value(self, value):
+ """
+ Set the current value of this option.
+ """
+ handle = self._device._get_handle()
+
+ if self._type == SANE_TYPE_BOOL.value:
+ assert type(value) is BoolType
+ elif self._type == SANE_TYPE_INT.value:
+ assert type(value) is IntType
+ elif self._type == SANE_TYPE_FIXED.value:
+ assert type(value) is IntType
+ elif self._type == SANE_TYPE_STRING.value:
+ assert type(value) is StringType
+ elif self._type == SANE_TYPE_BUTTON.value:
+ raise TypeError('SANE_TYPE_BUTTON has no value.')
+ elif self._type == SANE_TYPE_GROUP.value:
+ raise TypeError('SANE_TYPE_GROUP has no value.')
+ else:
+ raise TypeError('Option is of unknown type.')
+
+ info_flags = SANE_Int()
+
+ # TODO: When to use SANE_ACTION_SET_AUTO?
+ status = sane_control_option(
+ handle, self._option_number, SANE_ACTION_SET_VALUE, value, byref(info_flags))
+
+ # TODO: handle statuses/exceptions
+
+ # TODO: parse and respond to flags, see SANE docs 4.3.7
+ #print info_flags
+
+ if self._log:
+ self._log.debug('Option %s set to value %s.', self._name, value)
+
+ value = property(__get_value, __set_value)
+
+class ScanInfo(object):
+ """
+ Contains the parameters and progress of a scan in progress.
+ """
+ _width = 0
+ _height = 0
+ _depth = 0
+ _total_bytes = 0
+
+ def __init__(self, sane_parameters):
+ """
+ Initialize the ScanInfo object from the sane_parameters.
+ """
+ self._width = sane_parameters.pixels_per_line
+ self._height = sane_parameters.lines
+ self._depth = sane_parameters.depth
+ self._total_bytes = sane_parameters.bytes_per_line * sane_parameters.lines
+
+ # Read only properties
+
+ def __get_width(self):
+ """Get the width of the current scan, in pixels."""
+ return self._width
+
+ width = property(__get_width)
+
+ def __get_height(self):
+ """Get the height of the current scan, in pixels."""
+ return self._height
+
+ height = property(__get_height)
+
+ def __get_depth(self):
+ """Get the depth of the current scan, in bits."""
+ return self._depth
+
+ depth = property(__get_depth)
+
+ def __get_total_bytes(self):
+ """Get the total number of bytes comprising this scan."""
+ return self._total_bytes
+
+ total_bytes = property(__get_total_bytes)
+
+if __name__ == '__main__':
+ import logging
+ log_format = FORMAT = "%(message)s"
+ logging.basicConfig(level=logging.DEBUG, format=log_format)
+
+ sane = SANE(logging.getLogger())
+ sane.setup()
+ sane.update_devices()
+
+ for dev in sane.devices:
+ print dev.name
+
+ sane.devices[0].open()
+
+ print sane.devices[0].options.keys()
+
+ print sane.devices[0].options['mode'].value
+ sane.devices[0].options['mode'].value = 'Color'
+ print sane.devices[0].options['mode'].value
+
+ sane.devices[0].scan().save('out.bmp')
+
+ sane.devices[0].close()
+ sane.shutdown()
\ No newline at end of file
|
dalloliogm/N-glycan-symbols-for-Dia
|
67739c00a7a62390ff518d613b9e4cdd6aebcd69
|
templates for the symbols
|
diff --git a/template.dia b/template.dia
new file mode 100644
index 0000000..2924016
Binary files /dev/null and b/template.dia differ
diff --git a/template.dia.autosave b/template.dia.autosave
new file mode 100644
index 0000000..0b62bbc
Binary files /dev/null and b/template.dia.autosave differ
diff --git a/template.dia~ b/template.dia~
new file mode 100644
index 0000000..fa59504
Binary files /dev/null and b/template.dia~ differ
diff --git a/template2.dia b/template2.dia
new file mode 100644
index 0000000..d4dd280
Binary files /dev/null and b/template2.dia differ
|
dalloliogm/N-glycan-symbols-for-Dia
|
fc6004c48edf22a506993bca0f445d3cf76b6971
|
included 60% of the symbols
|
diff --git a/Fuc.png b/Fuc.png
new file mode 100644
index 0000000..732025a
Binary files /dev/null and b/Fuc.png differ
diff --git a/Fuc.shape b/Fuc.shape
new file mode 100644
index 0000000..93321b1
--- /dev/null
+++ b/Fuc.shape
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - Fuc</name>
+ <icon>Fuc.png</icon>
+ <connections>
+ <point x="16.5835" y="8.24752"/>
+ <point x="15.3772" y="10.8413"/>
+ <point x="17.7835" y="10.8475"/>
+ <point x="15.9804" y="9.5444"/>
+ <point x="16.5804" y="10.8444"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:polygon style="fill: #d82727" points="16.5835,8.24752 15.3772,10.8413 17.7835,10.8475 "/>
+ <svg:polygon style="fill: none; fill-opacity:0; stroke-width: 0.05; stroke: #000000" points="16.5835,8.24752 15.3772,10.8413 17.7835,10.8475 "/>
+ </svg:svg>
+</shape>
diff --git a/Gal.png b/Gal.png
new file mode 100644
index 0000000..4a06079
Binary files /dev/null and b/Gal.png differ
diff --git a/Gal.shape b/Gal.shape
new file mode 100644
index 0000000..346f822
--- /dev/null
+++ b/Gal.shape
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - Gal</name>
+ <icon>Gal.png</icon>
+ <connections>
+ <point x="6.365" y="5.47"/>
+ <point x="6.365" y="3.02"/>
+ <point x="5.14" y="4.245"/>
+ <point x="7.59" y="4.245"/>
+ <point x="6.365" y="5.47"/>
+ <point x="6.365" y="3.02"/>
+ <point x="5.14" y="4.245"/>
+ <point x="7.59" y="4.245"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:ellipse style="fill: #ffff00" cx="6.365" cy="4.245" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="6.365" cy="4.245" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="6.365" cy="4.245" rx="1.225" ry="1.225"/>
+ </svg:svg>
+</shape>
diff --git a/GalN.png b/GalN.png
new file mode 100644
index 0000000..51ddc03
Binary files /dev/null and b/GalN.png differ
diff --git a/GalN.shape b/GalN.shape
new file mode 100644
index 0000000..6f7b68e
--- /dev/null
+++ b/GalN.shape
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - GalN</name>
+ <icon>GalN.png</icon>
+ <connections>
+ <point x="15.3478" y="8.26362"/>
+ <point x="17.8155" y="10.8136"/>
+ <point x="15.3478" y="10.8136"/>
+ <point x="15.3478" y="9.53862"/>
+ <point x="17.8155" y="8.26362"/>
+ <point x="17.8155" y="9.53862"/>
+ <point x="16.5816" y="10.8136"/>
+ <point x="16.5816" y="8.26362"/>
+ <point x="15.3478" y="8.26362"/>
+ <point x="17.8155" y="10.8136"/>
+ <point x="15.3478" y="10.8136"/>
+ <point x="15.3478" y="9.53862"/>
+ <point x="17.8155" y="8.26362"/>
+ <point x="17.8155" y="9.53862"/>
+ <point x="16.5816" y="10.8136"/>
+ <point x="16.5816" y="8.26362"/>
+ <point x="15.3595" y="8.29425"/>
+ <point x="17.8079" y="8.29425"/>
+ <point x="17.8167" y="10.7956"/>
+ <point x="16.5837" y="8.29425"/>
+ <point x="17.8123" y="9.54494"/>
+ <point x="15.3647" y="8.34127"/>
+ <point x="15.371" y="10.7975"/>
+ <point x="17.7772" y="10.8038"/>
+ <point x="15.3679" y="9.5694"/>
+ <point x="16.5741" y="10.8006"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="15.3478" y="8.26362" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="15.3478" y="8.26362" width="2.46774" height="2.55"/>
+ <svg:polygon style="fill: #ffff00" points="15.3595,8.29425 17.8079,8.29425 17.8167,10.7956 "/>
+ <svg:polygon style="fill: none; fill-opacity:0; stroke-width: 0.05; stroke: #000000" points="15.3595,8.29425 17.8079,8.29425 17.8167,10.7956 "/>
+ <svg:polygon style="fill: #ffffff" points="15.3647,8.34127 15.371,10.7975 17.7772,10.8038 "/>
+ <svg:polygon style="fill: none; fill-opacity:0; stroke-width: 0.05; stroke: #000000" points="15.3647,8.34127 15.371,10.7975 17.7772,10.8038 "/>
+ </svg:svg>
+</shape>
diff --git a/GalNAc.png b/GalNAc.png
new file mode 100644
index 0000000..44c7417
Binary files /dev/null and b/GalNAc.png differ
diff --git a/GalNAc.shape b/GalNAc.shape
new file mode 100644
index 0000000..2fcde1e
--- /dev/null
+++ b/GalNAc.shape
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - GalNAc</name>
+ <icon>GalNAc.png</icon>
+ <connections>
+ <point x="2.595" y="1.535"/>
+ <point x="5.06274" y="4.085"/>
+ <point x="2.595" y="4.085"/>
+ <point x="2.595" y="2.81"/>
+ <point x="5.06274" y="1.535"/>
+ <point x="5.06274" y="2.81"/>
+ <point x="3.82887" y="4.085"/>
+ <point x="3.82887" y="1.535"/>
+ <point x="2.595" y="1.535"/>
+ <point x="5.06274" y="4.085"/>
+ <point x="2.595" y="4.085"/>
+ <point x="2.595" y="2.81"/>
+ <point x="5.06274" y="1.535"/>
+ <point x="5.06274" y="2.81"/>
+ <point x="3.82887" y="4.085"/>
+ <point x="3.82887" y="1.535"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:rect style="fill: #ffff00" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ </svg:svg>
+</shape>
diff --git a/Glc.png b/Glc.png
new file mode 100644
index 0000000..1f9481c
Binary files /dev/null and b/Glc.png differ
diff --git a/Glc.shape b/Glc.shape
new file mode 100644
index 0000000..e84055f
--- /dev/null
+++ b/Glc.shape
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - Glc</name>
+ <icon>Glc.png</icon>
+ <connections>
+ <point x="12.52" y="8.685"/>
+ <point x="12.52" y="6.235"/>
+ <point x="11.295" y="7.46"/>
+ <point x="13.745" y="7.46"/>
+ <point x="12.52" y="8.685"/>
+ <point x="12.52" y="6.235"/>
+ <point x="11.295" y="7.46"/>
+ <point x="13.745" y="7.46"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:ellipse style="fill: #3837b7" cx="12.52" cy="7.46" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="12.52" cy="7.46" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="12.52" cy="7.46" rx="1.225" ry="1.225"/>
+ </svg:svg>
+</shape>
diff --git a/GlcNAc.png b/GlcNAc.png
new file mode 100644
index 0000000..187a728
Binary files /dev/null and b/GlcNAc.png differ
diff --git a/GlcNAc.shape b/GlcNAc.shape
new file mode 100644
index 0000000..5ad0d65
--- /dev/null
+++ b/GlcNAc.shape
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - GlcNAc</name>
+ <icon>GlcNAc.png</icon>
+ <connections>
+ <point x="2.595" y="1.535"/>
+ <point x="5.06274" y="4.085"/>
+ <point x="2.595" y="4.085"/>
+ <point x="2.595" y="2.81"/>
+ <point x="5.06274" y="1.535"/>
+ <point x="5.06274" y="2.81"/>
+ <point x="3.82887" y="4.085"/>
+ <point x="3.82887" y="1.535"/>
+ <point x="2.595" y="1.535"/>
+ <point x="5.06274" y="4.085"/>
+ <point x="2.595" y="4.085"/>
+ <point x="2.595" y="2.81"/>
+ <point x="5.06274" y="1.535"/>
+ <point x="5.06274" y="2.81"/>
+ <point x="3.82887" y="4.085"/>
+ <point x="3.82887" y="1.535"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:rect style="fill: #3837b7" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ </svg:svg>
+</shape>
diff --git a/GlnN.png b/GlnN.png
new file mode 100644
index 0000000..f353349
Binary files /dev/null and b/GlnN.png differ
diff --git a/GlnN.shape b/GlnN.shape
new file mode 100644
index 0000000..e0f0e85
--- /dev/null
+++ b/GlnN.shape
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - GlnN</name>
+ <icon>GlnN.png</icon>
+ <connections>
+ <point x="15.3478" y="8.26362"/>
+ <point x="17.8155" y="10.8136"/>
+ <point x="15.3478" y="10.8136"/>
+ <point x="15.3478" y="9.53862"/>
+ <point x="17.8155" y="8.26362"/>
+ <point x="17.8155" y="9.53862"/>
+ <point x="16.5816" y="10.8136"/>
+ <point x="16.5816" y="8.26362"/>
+ <point x="15.3478" y="8.26362"/>
+ <point x="17.8155" y="10.8136"/>
+ <point x="15.3478" y="10.8136"/>
+ <point x="15.3478" y="9.53862"/>
+ <point x="17.8155" y="8.26362"/>
+ <point x="17.8155" y="9.53862"/>
+ <point x="16.5816" y="10.8136"/>
+ <point x="16.5816" y="8.26362"/>
+ <point x="15.3595" y="8.29425"/>
+ <point x="17.8079" y="8.29425"/>
+ <point x="17.8167" y="10.7956"/>
+ <point x="16.5837" y="8.29425"/>
+ <point x="17.8123" y="9.54494"/>
+ <point x="15.3647" y="8.34127"/>
+ <point x="15.371" y="10.7975"/>
+ <point x="17.7772" y="10.8038"/>
+ <point x="15.3679" y="9.5694"/>
+ <point x="16.5741" y="10.8006"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="15.3478" y="8.26362" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="15.3478" y="8.26362" width="2.46774" height="2.55"/>
+ <svg:polygon style="fill: #3837b7" points="15.3595,8.29425 17.8079,8.29425 17.8167,10.7956 "/>
+ <svg:polygon style="fill: none; fill-opacity:0; stroke-width: 0.05; stroke: #000000" points="15.3595,8.29425 17.8079,8.29425 17.8167,10.7956 "/>
+ <svg:polygon style="fill: #ffffff" points="15.3647,8.34127 15.371,10.7975 17.7772,10.8038 "/>
+ <svg:polygon style="fill: none; fill-opacity:0; stroke-width: 0.05; stroke: #000000" points="15.3647,8.34127 15.371,10.7975 17.7772,10.8038 "/>
+ </svg:svg>
+</shape>
diff --git a/ManN.png b/ManN.png
new file mode 100644
index 0000000..a4f1e5b
Binary files /dev/null and b/ManN.png differ
diff --git a/ManN.shape b/ManN.shape
new file mode 100644
index 0000000..534e928
--- /dev/null
+++ b/ManN.shape
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - ManN</name>
+ <icon>ManN.png</icon>
+ <connections>
+ <point x="15.3478" y="8.26362"/>
+ <point x="17.8155" y="10.8136"/>
+ <point x="15.3478" y="10.8136"/>
+ <point x="15.3478" y="9.53862"/>
+ <point x="17.8155" y="8.26362"/>
+ <point x="17.8155" y="9.53862"/>
+ <point x="16.5816" y="10.8136"/>
+ <point x="16.5816" y="8.26362"/>
+ <point x="15.3478" y="8.26362"/>
+ <point x="17.8155" y="10.8136"/>
+ <point x="15.3478" y="10.8136"/>
+ <point x="15.3478" y="9.53862"/>
+ <point x="17.8155" y="8.26362"/>
+ <point x="17.8155" y="9.53862"/>
+ <point x="16.5816" y="10.8136"/>
+ <point x="16.5816" y="8.26362"/>
+ <point x="15.3595" y="8.29425"/>
+ <point x="17.8079" y="8.29425"/>
+ <point x="17.8167" y="10.7956"/>
+ <point x="16.5837" y="8.29425"/>
+ <point x="17.8123" y="9.54494"/>
+ <point x="15.3647" y="8.34127"/>
+ <point x="15.371" y="10.7975"/>
+ <point x="17.7772" y="10.8038"/>
+ <point x="15.3679" y="9.5694"/>
+ <point x="16.5741" y="10.8006"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="15.3478" y="8.26362" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="15.3478" y="8.26362" width="2.46774" height="2.55"/>
+ <svg:polygon style="fill: #25971d" points="15.3595,8.29425 17.8079,8.29425 17.8167,10.7956 "/>
+ <svg:polygon style="fill: none; fill-opacity:0; stroke-width: 0.05; stroke: #000000" points="15.3595,8.29425 17.8079,8.29425 17.8167,10.7956 "/>
+ <svg:polygon style="fill: #ffffff" points="15.3647,8.34127 15.371,10.7975 17.7772,10.8038 "/>
+ <svg:polygon style="fill: none; fill-opacity:0; stroke-width: 0.05; stroke: #000000" points="15.3647,8.34127 15.371,10.7975 17.7772,10.8038 "/>
+ </svg:svg>
+</shape>
diff --git a/ManNAc.png b/ManNAc.png
new file mode 100644
index 0000000..bb8efeb
Binary files /dev/null and b/ManNAc.png differ
diff --git a/ManNAc.shape b/ManNAc.shape
new file mode 100644
index 0000000..b372c45
--- /dev/null
+++ b/ManNAc.shape
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia shapes - ManNAc</name>
+ <icon>ManNAc.png</icon>
+ <connections>
+ <point x="2.595" y="1.535"/>
+ <point x="5.06274" y="4.085"/>
+ <point x="2.595" y="4.085"/>
+ <point x="2.595" y="2.81"/>
+ <point x="5.06274" y="1.535"/>
+ <point x="5.06274" y="2.81"/>
+ <point x="3.82887" y="4.085"/>
+ <point x="3.82887" y="1.535"/>
+ <point x="2.595" y="1.535"/>
+ <point x="5.06274" y="4.085"/>
+ <point x="2.595" y="4.085"/>
+ <point x="2.595" y="2.81"/>
+ <point x="5.06274" y="1.535"/>
+ <point x="5.06274" y="2.81"/>
+ <point x="3.82887" y="4.085"/>
+ <point x="3.82887" y="1.535"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:rect style="fill: #25971d" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="2.595" y="1.535" width="2.46774" height="2.55"/>
+ </svg:svg>
+</shape>
diff --git a/flipping.png b/flipping.png
new file mode 100644
index 0000000..20f3a40
Binary files /dev/null and b/flipping.png differ
diff --git a/flipping.shape b/flipping.shape
new file mode 100644
index 0000000..18c9b25
--- /dev/null
+++ b/flipping.shape
@@ -0,0 +1,330 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>dia - flipping</name>
+ <icon>flipping.png</icon>
+ <connections>
+ <point x="96.2024" y="30.5657"/>
+ <point x="138.709" y="30.5657"/>
+ <point x="117.456" y="30.5657"/>
+ <point x="139.084" y="30.5657"/>
+ <point x="138.584" y="30.8157"/>
+ <point x="138.709" y="30.5657"/>
+ <point x="138.584" y="30.3157"/>
+ <point x="138.834" y="30.6907"/>
+ <point x="138.646" y="30.6907"/>
+ <point x="138.646" y="30.4407"/>
+ <point x="169.015" y="28.1534"/>
+ <point x="169.015" y="25.7034"/>
+ <point x="167.79" y="26.9284"/>
+ <point x="170.24" y="26.9284"/>
+ <point x="169.015" y="28.1534"/>
+ <point x="169.015" y="25.7034"/>
+ <point x="167.79" y="26.9284"/>
+ <point x="170.24" y="26.9284"/>
+ <point x="163.015" y="36.1534"/>
+ <point x="163.015" y="33.7034"/>
+ <point x="161.79" y="34.9284"/>
+ <point x="164.24" y="34.9284"/>
+ <point x="163.015" y="36.1534"/>
+ <point x="163.015" y="33.7034"/>
+ <point x="161.79" y="34.9284"/>
+ <point x="164.24" y="34.9284"/>
+ <point x="174.015" y="32.1534"/>
+ <point x="174.015" y="29.7034"/>
+ <point x="172.79" y="30.9284"/>
+ <point x="175.24" y="30.9284"/>
+ <point x="174.015" y="32.1534"/>
+ <point x="174.015" y="29.7034"/>
+ <point x="172.79" y="30.9284"/>
+ <point x="175.24" y="30.9284"/>
+ <point x="169.015" y="36.1534"/>
+ <point x="169.015" y="33.7034"/>
+ <point x="167.79" y="34.9284"/>
+ <point x="170.24" y="34.9284"/>
+ <point x="169.015" y="36.1534"/>
+ <point x="169.015" y="33.7034"/>
+ <point x="167.79" y="34.9284"/>
+ <point x="170.24" y="34.9284"/>
+ <point x="157.015" y="36.1534"/>
+ <point x="157.015" y="33.7034"/>
+ <point x="155.79" y="34.9284"/>
+ <point x="158.24" y="34.9284"/>
+ <point x="157.015" y="36.1534"/>
+ <point x="157.015" y="33.7034"/>
+ <point x="155.79" y="34.9284"/>
+ <point x="158.24" y="34.9284"/>
+ <point x="173.029" y="30.1393"/>
+ <point x="170.002" y="27.7175"/>
+ <point x="171.516" y="28.9284"/>
+ <point x="161.74" y="34.9284"/>
+ <point x="158.291" y="34.9284"/>
+ <point x="160.016" y="34.9284"/>
+ <point x="167.74" y="34.9284"/>
+ <point x="164.291" y="34.9284"/>
+ <point x="166.016" y="34.9284"/>
+ <point x="173.029" y="31.7175"/>
+ <point x="170.002" y="34.1393"/>
+ <point x="171.516" y="32.9284"/>
+ <point x="178.79" y="29.7034"/>
+ <point x="181.258" y="32.2534"/>
+ <point x="178.79" y="32.2534"/>
+ <point x="178.79" y="30.9784"/>
+ <point x="181.258" y="29.7034"/>
+ <point x="181.258" y="30.9784"/>
+ <point x="180.024" y="32.2534"/>
+ <point x="180.024" y="29.7034"/>
+ <point x="178.79" y="29.7034"/>
+ <point x="181.258" y="32.2534"/>
+ <point x="178.79" y="32.2534"/>
+ <point x="178.79" y="30.9784"/>
+ <point x="181.258" y="29.7034"/>
+ <point x="181.258" y="30.9784"/>
+ <point x="180.024" y="32.2534"/>
+ <point x="180.024" y="29.7034"/>
+ <point x="184.79" y="29.7034"/>
+ <point x="187.258" y="32.2534"/>
+ <point x="184.79" y="32.2534"/>
+ <point x="184.79" y="30.9784"/>
+ <point x="187.258" y="29.7034"/>
+ <point x="187.258" y="30.9784"/>
+ <point x="186.024" y="32.2534"/>
+ <point x="186.024" y="29.7034"/>
+ <point x="184.79" y="29.7034"/>
+ <point x="187.258" y="32.2534"/>
+ <point x="184.79" y="32.2534"/>
+ <point x="184.79" y="30.9784"/>
+ <point x="187.258" y="29.7034"/>
+ <point x="187.258" y="30.9784"/>
+ <point x="186.024" y="32.2534"/>
+ <point x="186.024" y="29.7034"/>
+ <point x="178.74" y="30.9677"/>
+ <point x="175.291" y="30.939"/>
+ <point x="177.016" y="30.9534"/>
+ <point x="184.74" y="30.9784"/>
+ <point x="181.308" y="30.9784"/>
+ <point x="183.024" y="30.9784"/>
+ <point x="191.036" y="31.0013"/>
+ <point x="187.308" y="30.9843"/>
+ <point x="189.172" y="30.9928"/>
+ <point x="59.225" y="26.45"/>
+ <point x="59.225" y="24"/>
+ <point x="58" y="25.225"/>
+ <point x="60.45" y="25.225"/>
+ <point x="59.225" y="26.45"/>
+ <point x="59.225" y="24"/>
+ <point x="58" y="25.225"/>
+ <point x="60.45" y="25.225"/>
+ <point x="53.225" y="31.45"/>
+ <point x="53.225" y="29"/>
+ <point x="52" y="30.225"/>
+ <point x="54.45" y="30.225"/>
+ <point x="53.225" y="31.45"/>
+ <point x="53.225" y="29"/>
+ <point x="52" y="30.225"/>
+ <point x="54.45" y="30.225"/>
+ <point x="58.225" y="36.45"/>
+ <point x="58.225" y="34"/>
+ <point x="57" y="35.225"/>
+ <point x="59.45" y="35.225"/>
+ <point x="58.225" y="36.45"/>
+ <point x="58.225" y="34"/>
+ <point x="57" y="35.225"/>
+ <point x="59.45" y="35.225"/>
+ <point x="54.2042" y="29.409"/>
+ <point x="58.2458" y="26.041"/>
+ <point x="56.225" y="27.725"/>
+ <point x="54.1265" y="31.1265"/>
+ <point x="57.3235" y="34.3235"/>
+ <point x="55.725" y="32.725"/>
+ <point x="46" y="29"/>
+ <point x="48.4677" y="31.55"/>
+ <point x="46" y="31.55"/>
+ <point x="46" y="30.275"/>
+ <point x="48.4677" y="29"/>
+ <point x="48.4677" y="30.275"/>
+ <point x="47.2339" y="31.55"/>
+ <point x="47.2339" y="29"/>
+ <point x="46" y="29"/>
+ <point x="48.4677" y="31.55"/>
+ <point x="46" y="31.55"/>
+ <point x="46" y="30.275"/>
+ <point x="48.4677" y="29"/>
+ <point x="48.4677" y="30.275"/>
+ <point x="47.2339" y="31.55"/>
+ <point x="47.2339" y="29"/>
+ <point x="40" y="29"/>
+ <point x="42.4677" y="31.55"/>
+ <point x="40" y="31.55"/>
+ <point x="40" y="30.275"/>
+ <point x="42.4677" y="29"/>
+ <point x="42.4677" y="30.275"/>
+ <point x="41.2339" y="31.55"/>
+ <point x="41.2339" y="29"/>
+ <point x="40" y="29"/>
+ <point x="42.4677" y="31.55"/>
+ <point x="40" y="31.55"/>
+ <point x="40" y="30.275"/>
+ <point x="42.4677" y="29"/>
+ <point x="42.4677" y="30.275"/>
+ <point x="41.2339" y="31.55"/>
+ <point x="41.2339" y="29"/>
+ <point x="48.5166" y="30.2643"/>
+ <point x="51.9554" y="30.2356"/>
+ <point x="50.236" y="30.2499"/>
+ <point x="42.5178" y="30.275"/>
+ <point x="45.9499" y="30.275"/>
+ <point x="44.2339" y="30.275"/>
+ <point x="35.221" y="30.2607"/>
+ <point x="39.9501" y="30.2719"/>
+ <point x="37.5855" y="30.2663"/>
+ <point x="32" y="6"/>
+ <point x="32" y="29"/>
+ <point x="32" y="17.5"/>
+ <point x="32" y="32"/>
+ <point x="32" y="55"/>
+ <point x="32" y="43.5"/>
+ <point x="65.225" y="26.45"/>
+ <point x="65.225" y="24"/>
+ <point x="64" y="25.225"/>
+ <point x="66.45" y="25.225"/>
+ <point x="65.225" y="26.45"/>
+ <point x="65.225" y="24"/>
+ <point x="64" y="25.225"/>
+ <point x="66.45" y="25.225"/>
+ <point x="71.225" y="26.45"/>
+ <point x="71.225" y="24"/>
+ <point x="70" y="25.225"/>
+ <point x="72.45" y="25.225"/>
+ <point x="71.225" y="26.45"/>
+ <point x="71.225" y="24"/>
+ <point x="70" y="25.225"/>
+ <point x="72.45" y="25.225"/>
+ <point x="66.5001" y="25.225"/>
+ <point x="69.9499" y="25.225"/>
+ <point x="68.225" y="25.225"/>
+ <point x="60.45" y="25.225"/>
+ <point x="63.9508" y="25.225"/>
+ <point x="62.2004" y="25.225"/>
+ <point x="195.566" y="6.41421"/>
+ <point x="195.566" y="29.4142"/>
+ <point x="195.566" y="17.9142"/>
+ <point x="195.566" y="32.4142"/>
+ <point x="195.566" y="55.4142"/>
+ <point x="195.566" y="43.9142"/>
+ <point x="199.012" y="6.50175"/>
+ <point x="199.012" y="29.5017"/>
+ <point x="199.012" y="18.0017"/>
+ <point x="199.004" y="29.4835"/>
+ <point x="199.012" y="55.5017"/>
+ <point x="199.008" y="42.4926"/>
+ <point x="28.3854" y="6.14512"/>
+ <point x="28.3854" y="29.1451"/>
+ <point x="28.3854" y="17.6451"/>
+ <point x="28.378" y="29.2269"/>
+ <point x="28.3854" y="55.2451"/>
+ <point x="28.3817" y="42.236"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 0 cm; font-family: sans; font-style: normal; font-weight: normal" x="10.8877" y="20.9756"></svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 0 cm; font-family: sans; font-style: normal; font-weight: normal" x="10.8877" y="20.9756"></svg:text>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1; stroke: #000000" x1="96.2024" y1="30.5657" x2="138.709" y2="30.5657"/>
+ <svg:polygon style="fill: #000000" points="139.084,30.5657 138.584,30.8157 138.709,30.5657 138.584,30.3157 "/>
+ <svg:polygon style="fill: none; fill-opacity:0; stroke-width: 1; stroke: #000000" points="139.084,30.5657 138.584,30.8157 138.709,30.5657 138.584,30.3157 "/>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 21.8925 cm; font-family: sans; font-style: normal; font-weight: normal" x="105.002" y="34.3657">Flipping of the </svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 27.725 cm; font-family: sans; font-style: normal; font-weight: normal" x="105.002" y="38.3657">N-glycan precursor</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 26.23 cm; font-family: sans; font-style: normal; font-weight: normal" x="105.002" y="42.3657">on the membrane</svg:text>
+ <svg:ellipse style="fill: #25971d" cx="169.015" cy="26.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="169.015" cy="26.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="169.015" cy="26.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: #25971d" cx="163.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="163.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="163.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: #25971d" cx="174.015" cy="30.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="174.015" cy="30.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="174.015" cy="30.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: #25971d" cx="169.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="169.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="169.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: #25971d" cx="157.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="157.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="157.015" cy="34.9284" rx="1.225" ry="1.225"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="173.029" y1="30.1393" x2="170.002" y2="27.7175"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="161.74" y1="34.9284" x2="158.291" y2="34.9284"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="167.74" y1="34.9284" x2="164.291" y2="34.9284"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="173.029" y1="31.7175" x2="170.002" y2="34.1393"/>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3075 cm; font-family: sans; font-style: normal; font-weight: normal" x="181.258" y="32.2534">Ã 4</svg:text>
+ <svg:rect style="fill: #3837b7" x="178.79" y="29.7034" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="178.79" y="29.7034" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="178.79" y="29.7034" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: #3837b7" x="184.79" y="29.7034" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="184.79" y="29.7034" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="184.79" y="29.7034" width="2.46774" height="2.55"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="178.74" y1="30.9677" x2="175.291" y2="30.939"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="184.74" y1="30.9784" x2="181.308" y2="30.9784"/>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3075 cm; font-family: sans; font-style: normal; font-weight: normal" x="175.79" y="32.7034">Ã 4</svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3525 cm; font-family: sans; font-style: normal; font-weight: normal" x="164.79" y="36.7034">α 2</svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3525 cm; font-family: sans; font-style: normal; font-weight: normal" x="158.79" y="36.7034">α 2</svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3525 cm; font-family: sans; font-style: normal; font-weight: normal" x="171.79" y="34.7034">α 3</svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3525 cm; font-family: sans; font-style: normal; font-weight: normal" x="171.515" y="28.9284">α 6</svg:text>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="191.036" y1="31.0013" x2="187.308" y2="30.9843"/>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 4.6725 cm; font-family: sans; font-style: normal; font-weight: normal" x="191.414" y="31.4706">PP-Dol</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 46.64 cm; font-family: sans; font-style: normal; font-weight: normal" x="143.79" y="45.7034"> (GlcNAc)2(Man)5(PP-Dol)1</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 47.955 cm; font-family: sans; font-style: normal; font-weight: normal" x="143.79" y="49.7034"> [integral to the luminal side</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 39.6925 cm; font-family: sans; font-style: normal; font-weight: normal" x="143.79" y="53.7034"> of the ER membrane]</svg:text>
+ <svg:ellipse style="fill: #25971d" cx="59.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="59.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="59.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: #25971d" cx="53.225" cy="30.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="53.225" cy="30.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="53.225" cy="30.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: #25971d" cx="58.225" cy="35.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="58.225" cy="35.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="58.225" cy="35.225" rx="1.225" ry="1.225"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="54.2042" y1="29.409" x2="58.2458" y2="26.041"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="54.1265" y1="31.1265" x2="57.3235" y2="34.3235"/>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3075 cm; font-family: sans; font-style: normal; font-weight: normal" x="42.4677" y="30.275">Ã 4</svg:text>
+ <svg:rect style="fill: #3837b7" x="46" y="29" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="46" y="29" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="46" y="29" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: #3837b7" x="40" y="29" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x="40" y="29" width="2.46774" height="2.55"/>
+ <svg:rect style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" x="40" y="29" width="2.46774" height="2.55"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="48.5166" y1="30.2643" x2="51.9554" y2="30.2356"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="42.5178" y1="30.275" x2="45.9499" y2="30.275"/>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3075 cm; font-family: sans; font-style: normal; font-weight: normal" x="48.4677" y="30.275">Ã 4</svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 0 cm; font-family: sans; font-style: normal; font-weight: normal" x="52.888" y="22.9756"></svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 0 cm; font-family: sans; font-style: normal; font-weight: normal" x="52.888" y="22.9756"></svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3525 cm; font-family: sans; font-style: normal; font-weight: normal" x="61" y="24">α 2</svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3525 cm; font-family: sans; font-style: normal; font-weight: normal" x="67" y="24">α 2</svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3525 cm; font-family: sans; font-style: normal; font-weight: normal" x="54" y="27">α 3</svg:text>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 2.3525 cm; font-family: sans; font-style: normal; font-weight: normal" x="53" y="34">α 6</svg:text>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="35.221" y1="30.2607" x2="39.9501" y2="30.2719"/>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 4.705 cm; font-family: sans; font-style: normal; font-weight: normal" x="29.624" y="30.7672">Dol-PP</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 46.64 cm; font-family: sans; font-style: normal; font-weight: normal" x="40.2828" y="46.1314"> (GlcNAc)2(Man)5(PP-Dol)1</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 54.68 cm; font-family: sans; font-style: normal; font-weight: normal" x="40.2828" y="50.1314"> [integral to the cytoplasmic side</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 39.6925 cm; font-family: sans; font-style: normal; font-weight: normal" x="40.2828" y="54.1314"> of the ER membrane]</svg:text>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1.1; stroke-dasharray: 0.2; stroke: #000000" x1="32" y1="6" x2="32" y2="29"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1.1; stroke-dasharray: 0.2; stroke: #000000" x1="32" y1="32" x2="32" y2="55"/>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 16.2125 cm; font-family: sans; font-style: normal; font-weight: normal" x="10" y="10">[ER lumen]</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 17.775 cm; font-family: sans; font-style: normal; font-weight: normal" x="35" y="10">[Cytoplasm]</svg:text>
+ <svg:ellipse style="fill: #25971d" cx="65.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="65.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="65.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: #25971d" cx="71.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="71.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="71.225" cy="25.225" rx="1.225" ry="1.225"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="66.5001" y1="25.225" x2="69.9499" y2="25.225"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" x1="60.45" y1="25.225" x2="63.9508" y2="25.225"/>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 11.515 cm; font-family: sans; font-style: normal; font-weight: normal" x="33" y="54">[ER membrane]</svg:text>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1.1; stroke-dasharray: 0.2; stroke: #000000" x1="195.566" y1="6.41421" x2="195.566" y2="29.4142"/>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 17.775 cm; font-family: sans; font-style: normal; font-weight: normal" x="201.566" y="10.4142">[Cytoplasm]</svg:text>
+ <svg:text style="fill: #000000; font-size: 4 cm; length: 16.2125 cm; font-family: sans; font-style: normal; font-weight: normal" x="177.566" y="10.4142">[ER lumen]</svg:text>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1.1; stroke-dasharray: 0.2; stroke: #000000" x1="195.566" y1="32.4142" x2="195.566" y2="55.4142"/>
+ <svg:text style="fill: #000000; font-size: 2 cm; length: 11.515 cm; font-family: sans; font-style: normal; font-weight: normal" x="200.525" y="53.9799">[ER membrane]</svg:text>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1.1; stroke-dasharray: 0.2; stroke: #000000" x1="199.012" y1="6.50175" x2="199.012" y2="29.5017"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1.1; stroke-dasharray: 0.2; stroke: #000000" x1="199.004" y1="29.4835" x2="199.012" y2="55.5017"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1.1; stroke-dasharray: 0.2; stroke: #000000" x1="28.3854" y1="6.14512" x2="28.3854" y2="29.1451"/>
+ <svg:line style="fill: none; fill-opacity:0; stroke-width: 1.1; stroke-dasharray: 0.2; stroke: #000000" x1="28.378" y1="29.2269" x2="28.3854" y2="55.2451"/>
+ </svg:svg>
+</shape>
diff --git a/mannose.png b/mannose.png
new file mode 100644
index 0000000..8b6dfe1
Binary files /dev/null and b/mannose.png differ
diff --git a/mannose.shape b/mannose.shape
new file mode 100644
index 0000000..e2dc192
--- /dev/null
+++ b/mannose.shape
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns" xmlns:svg="http://www.w3.org/2000/svg">
+ <name>shapes - mannose</name>
+ <icon>mannose.png</icon>
+ <connections>
+ <point x="3.82" y="3.985"/>
+ <point x="3.82" y="1.535"/>
+ <point x="2.595" y="2.76"/>
+ <point x="5.045" y="2.76"/>
+ <point x="3.82" y="3.985"/>
+ <point x="3.82" y="1.535"/>
+ <point x="2.595" y="2.76"/>
+ <point x="5.045" y="2.76"/>
+ </connections>
+ <aspectratio type="fixed"/>
+ <svg:svg>
+ <svg:ellipse style="fill: #25971d" cx="3.82" cy="2.76" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.1; stroke: #000000" cx="3.82" cy="2.76" rx="1.225" ry="1.225"/>
+ <svg:ellipse style="fill: none; fill-opacity:0; stroke-width: 0.01; stroke: #000000" cx="3.82" cy="2.76" rx="1.225" ry="1.225"/>
+ </svg:svg>
+</shape>
|
andreas/studyplanner
|
1013a03e98839514729e66efb9cb1e556ff38b49
|
Added config folder.
|
diff --git a/config/.svn/entries b/config/.svn/entries
new file mode 100755
index 0000000..cbb211c
--- /dev/null
+++ b/config/.svn/entries
@@ -0,0 +1,79 @@
+8
+
+dir
+2
+svn+ssh://andreas%[email protected]/home/16742/users/andreas%25garnaes.dk/svn/studyplanner/trunk/config
+svn+ssh://andreas%[email protected]/home/16742/users/andreas%25garnaes.dk/svn/studyplanner
+
+
+
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
+
+svn:special svn:externals svn:needs-lock
+
+
+
+
+
+
+
+
+
+
+
+35ba3173-0730-0410-8f33-806d5331b7ff
+
+routes.rb
+file
+
+
+
+
+2007-05-09T20:29:22.453125Z
+f2fa41609d3ea8fb320bacb302579e71
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
+database.yml
+file
+
+
+
+
+2007-05-09T20:29:22.453125Z
+e4edf15f037e86f3bb6a52e9d7af31ea
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
+boot.rb
+file
+
+
+
+
+2007-05-09T20:29:22.453125Z
+051f2b77c29b10f8b2e06a7dfd26ab07
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
+environment.rb
+file
+
+
+
+
+2007-05-09T20:29:22.468750Z
+8429d50a1e56c0ba5edb60da97501864
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
+environments
+dir
+
diff --git a/config/.svn/format b/config/.svn/format
new file mode 100755
index 0000000..45a4fb7
--- /dev/null
+++ b/config/.svn/format
@@ -0,0 +1 @@
+8
diff --git a/config/.svn/text-base/boot.rb.svn-base b/config/.svn/text-base/boot.rb.svn-base
new file mode 100755
index 0000000..9a094cb
--- /dev/null
+++ b/config/.svn/text-base/boot.rb.svn-base
@@ -0,0 +1,44 @@
+# Don't change this file. Configuration is done in config/environment.rb and config/environments/*.rb
+
+unless defined?(RAILS_ROOT)
+ root_path = File.join(File.dirname(__FILE__), '..')
+
+ unless RUBY_PLATFORM =~ /mswin32/
+ require 'pathname'
+ root_path = Pathname.new(root_path).cleanpath(true).to_s
+ end
+
+ RAILS_ROOT = root_path
+end
+
+unless defined?(Rails::Initializer)
+ if File.directory?("#{RAILS_ROOT}/vendor/rails")
+ require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
+ else
+ require 'rubygems'
+
+ environment_without_comments = IO.readlines(File.dirname(__FILE__) + '/environment.rb').reject { |l| l =~ /^#/ }.join
+ environment_without_comments =~ /[^#]RAILS_GEM_VERSION = '([\d.]+)'/
+ rails_gem_version = $1
+
+ if version = defined?(RAILS_GEM_VERSION) ? RAILS_GEM_VERSION : rails_gem_version
+ rails_gem = Gem.cache.search('rails', "=#{version}").first
+
+ if rails_gem
+ require_gem "rails", "=#{version}"
+ require rails_gem.full_gem_path + '/lib/initializer'
+ else
+ STDERR.puts %(Cannot find gem for Rails =#{version}:
+ Install the missing gem with 'gem install -v=#{version} rails', or
+ change environment.rb to define RAILS_GEM_VERSION with your desired version.
+ )
+ exit 1
+ end
+ else
+ require_gem "rails"
+ require 'initializer'
+ end
+ end
+
+ Rails::Initializer.run(:set_load_path)
+end
\ No newline at end of file
diff --git a/config/.svn/text-base/database.yml.svn-base b/config/.svn/text-base/database.yml.svn-base
new file mode 100755
index 0000000..79d1ca7
--- /dev/null
+++ b/config/.svn/text-base/database.yml.svn-base
@@ -0,0 +1,35 @@
+# MySQL (default setup). Versions 4.1 and 5.0 are recommended.
+#
+# Install the MySQL driver:
+# gem install mysql
+# On MacOS X:
+# gem install mysql -- --include=/usr/local/lib
+# On Windows:
+# There is no gem for Windows. Install mysql.so from RubyForApache.
+# http://rubyforge.org/projects/rubyforapache
+#
+# And be sure to use new-style password hashing:
+# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
+development:
+ adapter: mysql
+ database: studyplanner_development
+ username: root
+ password: JgJoCt3_sql
+ host: localhost
+
+# Warning: The database defined as 'test' will be erased and
+# re-generated from your development database when you run 'rake'.
+# Do not set this db to the same as development or production.
+test:
+ adapter: mysql
+ database: studyplanner_test
+ username: jux
+ password:
+ host: localhost
+
+production:
+ adapter: mysql
+ database: studyplanner_production
+ username: prod
+ password: *63B39BB0B9450A54C3BC59DDB00DA6B0A0661338
+ host: localhost
diff --git a/config/.svn/text-base/environment.rb.svn-base b/config/.svn/text-base/environment.rb.svn-base
new file mode 100755
index 0000000..e848c06
--- /dev/null
+++ b/config/.svn/text-base/environment.rb.svn-base
@@ -0,0 +1,53 @@
+# Be sure to restart your web server when you modify this file.
+
+# Uncomment below to force Rails into production mode when
+# you don't control web/app server and can't set it the proper way
+# ENV['RAILS_ENV'] ||= 'production'
+
+# Specifies gem version of Rails to use when vendor/rails is not present
+RAILS_GEM_VERSION = '1.1.6'
+
+# Bootstrap the Rails environment, frameworks, and default configuration
+require File.join(File.dirname(__FILE__), 'boot')
+
+Rails::Initializer.run do |config|
+ # Settings in config/environments/* take precedence those specified here
+
+ # Skip frameworks you're not going to use (only works if using vendor/rails)
+ # config.frameworks -= [ :action_web_service, :action_mailer ]
+
+ # Add additional load paths for your own custom dirs
+ # config.load_paths += %W( #{RAILS_ROOT}/extras )
+
+ # Force all environments to use the same logger level
+ # (by default production uses :info, the others :debug)
+ # config.log_level = :debug
+
+ # Use the database for sessions instead of the file system
+ # (create the session table with 'rake db:sessions:create')
+ config.action_controller.session_store = :active_record_store
+
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ config.active_record.schema_format = :ruby
+
+ # Activate observers that should always be running
+ # config.active_record.observers = :cacher, :garbage_collector
+
+ # Make Active Record use UTC-base instead of local time
+ # config.active_record.default_timezone = :utc
+
+ # See Rails::Configuration for more options
+end
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
+
+# Include your application configuration below
\ No newline at end of file
diff --git a/config/.svn/text-base/routes.rb.svn-base b/config/.svn/text-base/routes.rb.svn-base
new file mode 100755
index 0000000..3837a7b
--- /dev/null
+++ b/config/.svn/text-base/routes.rb.svn-base
@@ -0,0 +1,26 @@
+ActionController::Routing::Routes.draw do |map|
+ # The priority is based upon order of creation: first created -> highest priority.
+
+ # Sample of regular route:
+ # map.connect 'products/:id', :controller => 'catalog', :action => 'view'
+ # Keep in mind you can assign values other than :controller and :action
+
+ # Sample of named route:
+ # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
+ # This route can be invoked with purchase_url(:id => product.id)
+
+ # You can have the root of your site routed by hooking up ''
+ # -- just remember to delete public/index.html.
+ # map.connect '', :controller => "welcome"
+
+ # Allow downloading Web Service WSDL as a file with an extension
+ # instead of a file named 'wsdl'
+ map.connect ':controller/service.wsdl', :action => 'wsdl'
+
+ map.resources :studyplans, :users, :course_registrations
+
+ # Install the default route as the lowest priority.
+ map.connect ':controller/:action/:id'
+
+ map.home '', :controller => 'studyplans'
+end
diff --git a/config/boot.rb b/config/boot.rb
new file mode 100755
index 0000000..9a094cb
--- /dev/null
+++ b/config/boot.rb
@@ -0,0 +1,44 @@
+# Don't change this file. Configuration is done in config/environment.rb and config/environments/*.rb
+
+unless defined?(RAILS_ROOT)
+ root_path = File.join(File.dirname(__FILE__), '..')
+
+ unless RUBY_PLATFORM =~ /mswin32/
+ require 'pathname'
+ root_path = Pathname.new(root_path).cleanpath(true).to_s
+ end
+
+ RAILS_ROOT = root_path
+end
+
+unless defined?(Rails::Initializer)
+ if File.directory?("#{RAILS_ROOT}/vendor/rails")
+ require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
+ else
+ require 'rubygems'
+
+ environment_without_comments = IO.readlines(File.dirname(__FILE__) + '/environment.rb').reject { |l| l =~ /^#/ }.join
+ environment_without_comments =~ /[^#]RAILS_GEM_VERSION = '([\d.]+)'/
+ rails_gem_version = $1
+
+ if version = defined?(RAILS_GEM_VERSION) ? RAILS_GEM_VERSION : rails_gem_version
+ rails_gem = Gem.cache.search('rails', "=#{version}").first
+
+ if rails_gem
+ require_gem "rails", "=#{version}"
+ require rails_gem.full_gem_path + '/lib/initializer'
+ else
+ STDERR.puts %(Cannot find gem for Rails =#{version}:
+ Install the missing gem with 'gem install -v=#{version} rails', or
+ change environment.rb to define RAILS_GEM_VERSION with your desired version.
+ )
+ exit 1
+ end
+ else
+ require_gem "rails"
+ require 'initializer'
+ end
+ end
+
+ Rails::Initializer.run(:set_load_path)
+end
\ No newline at end of file
diff --git a/config/database.yml b/config/database.yml
new file mode 100755
index 0000000..d9e5824
--- /dev/null
+++ b/config/database.yml
@@ -0,0 +1,35 @@
+# MySQL (default setup). Versions 4.1 and 5.0 are recommended.
+#
+# Install the MySQL driver:
+# gem install mysql
+# On MacOS X:
+# gem install mysql -- --include=/usr/local/lib
+# On Windows:
+# There is no gem for Windows. Install mysql.so from RubyForApache.
+# http://rubyforge.org/projects/rubyforapache
+#
+# And be sure to use new-style password hashing:
+# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
+development:
+ adapter: mysql
+ database: studyplanner_development
+ username: root
+ password:
+ host: localhost
+
+# Warning: The database defined as 'test' will be erased and
+# re-generated from your development database when you run 'rake'.
+# Do not set this db to the same as development or production.
+test:
+ adapter: mysql
+ database: studyplanner_test
+ username: root
+ password:
+ host: localhost
+
+production:
+ adapter: mysql
+ database: studyplanner_production
+ username: root
+ password:
+ host: localhost
diff --git a/config/database.yml.example b/config/database.yml.example
new file mode 100755
index 0000000..d9e5824
--- /dev/null
+++ b/config/database.yml.example
@@ -0,0 +1,35 @@
+# MySQL (default setup). Versions 4.1 and 5.0 are recommended.
+#
+# Install the MySQL driver:
+# gem install mysql
+# On MacOS X:
+# gem install mysql -- --include=/usr/local/lib
+# On Windows:
+# There is no gem for Windows. Install mysql.so from RubyForApache.
+# http://rubyforge.org/projects/rubyforapache
+#
+# And be sure to use new-style password hashing:
+# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
+development:
+ adapter: mysql
+ database: studyplanner_development
+ username: root
+ password:
+ host: localhost
+
+# Warning: The database defined as 'test' will be erased and
+# re-generated from your development database when you run 'rake'.
+# Do not set this db to the same as development or production.
+test:
+ adapter: mysql
+ database: studyplanner_test
+ username: root
+ password:
+ host: localhost
+
+production:
+ adapter: mysql
+ database: studyplanner_production
+ username: root
+ password:
+ host: localhost
diff --git a/config/environment.rb b/config/environment.rb
new file mode 100755
index 0000000..e848c06
--- /dev/null
+++ b/config/environment.rb
@@ -0,0 +1,53 @@
+# Be sure to restart your web server when you modify this file.
+
+# Uncomment below to force Rails into production mode when
+# you don't control web/app server and can't set it the proper way
+# ENV['RAILS_ENV'] ||= 'production'
+
+# Specifies gem version of Rails to use when vendor/rails is not present
+RAILS_GEM_VERSION = '1.1.6'
+
+# Bootstrap the Rails environment, frameworks, and default configuration
+require File.join(File.dirname(__FILE__), 'boot')
+
+Rails::Initializer.run do |config|
+ # Settings in config/environments/* take precedence those specified here
+
+ # Skip frameworks you're not going to use (only works if using vendor/rails)
+ # config.frameworks -= [ :action_web_service, :action_mailer ]
+
+ # Add additional load paths for your own custom dirs
+ # config.load_paths += %W( #{RAILS_ROOT}/extras )
+
+ # Force all environments to use the same logger level
+ # (by default production uses :info, the others :debug)
+ # config.log_level = :debug
+
+ # Use the database for sessions instead of the file system
+ # (create the session table with 'rake db:sessions:create')
+ config.action_controller.session_store = :active_record_store
+
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ config.active_record.schema_format = :ruby
+
+ # Activate observers that should always be running
+ # config.active_record.observers = :cacher, :garbage_collector
+
+ # Make Active Record use UTC-base instead of local time
+ # config.active_record.default_timezone = :utc
+
+ # See Rails::Configuration for more options
+end
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
+
+# Include your application configuration below
\ No newline at end of file
diff --git a/config/environments/.svn/entries b/config/environments/.svn/entries
new file mode 100755
index 0000000..2d8e941
--- /dev/null
+++ b/config/environments/.svn/entries
@@ -0,0 +1,64 @@
+8
+
+dir
+2
+svn+ssh://andreas%[email protected]/home/16742/users/andreas%25garnaes.dk/svn/studyplanner/trunk/config/environments
+svn+ssh://andreas%[email protected]/home/16742/users/andreas%25garnaes.dk/svn/studyplanner
+
+
+
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
+
+svn:special svn:externals svn:needs-lock
+
+
+
+
+
+
+
+
+
+
+
+35ba3173-0730-0410-8f33-806d5331b7ff
+
+test.rb
+file
+
+
+
+
+2007-05-09T20:29:22.281250Z
+5d77b56f8a9fb3d3cbdd282a850b8eb4
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
+development.rb
+file
+
+
+
+
+2007-05-09T20:29:22.375000Z
+e8b28b6942e649e4a7766c3bed33fb63
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
+production.rb
+file
+
+
+
+
+2007-05-09T20:29:22.375000Z
+bb689b1559ca76304f418adbeb38750b
+2007-05-09T12:13:44.681812Z
+2
+andreas%garnaes.dk
+
diff --git a/config/environments/.svn/format b/config/environments/.svn/format
new file mode 100755
index 0000000..45a4fb7
--- /dev/null
+++ b/config/environments/.svn/format
@@ -0,0 +1 @@
+8
diff --git a/config/environments/.svn/text-base/development.rb.svn-base b/config/environments/.svn/text-base/development.rb.svn-base
new file mode 100755
index 0000000..0589aa9
--- /dev/null
+++ b/config/environments/.svn/text-base/development.rb.svn-base
@@ -0,0 +1,21 @@
+# Settings specified here will take precedence over those in config/environment.rb
+
+# In the development environment your application's code is reloaded on
+# every request. This slows down response time but is perfect for development
+# since you don't have to restart the webserver when you make code changes.
+config.cache_classes = false
+
+# Log error messages when you accidentally call methods on nil.
+config.whiny_nils = true
+
+# Enable the breakpoint server that script/breakpointer connects to
+config.breakpoint_server = true
+
+# Show full error reports and disable caching
+config.action_controller.consider_all_requests_local = true
+config.action_controller.perform_caching = false
+config.action_view.cache_template_extensions = false
+config.action_view.debug_rjs = true
+
+# Don't care if the mailer can't send
+config.action_mailer.raise_delivery_errors = false
diff --git a/config/environments/.svn/text-base/production.rb.svn-base b/config/environments/.svn/text-base/production.rb.svn-base
new file mode 100755
index 0000000..5a4e2b1
--- /dev/null
+++ b/config/environments/.svn/text-base/production.rb.svn-base
@@ -0,0 +1,18 @@
+# Settings specified here will take precedence over those in config/environment.rb
+
+# The production environment is meant for finished, "live" apps.
+# Code is not reloaded between requests
+config.cache_classes = true
+
+# Use a different logger for distributed setups
+# config.logger = SyslogLogger.new
+
+# Full error reports are disabled and caching is turned on
+config.action_controller.consider_all_requests_local = false
+config.action_controller.perform_caching = true
+
+# Enable serving of images, stylesheets, and javascripts from an asset server
+# config.action_controller.asset_host = "http://assets.example.com"
+
+# Disable delivery errors if you bad email addresses should just be ignored
+# config.action_mailer.raise_delivery_errors = false
diff --git a/config/environments/.svn/text-base/test.rb.svn-base b/config/environments/.svn/text-base/test.rb.svn-base
new file mode 100755
index 0000000..f0689b9
--- /dev/null
+++ b/config/environments/.svn/text-base/test.rb.svn-base
@@ -0,0 +1,19 @@
+# Settings specified here will take precedence over those in config/environment.rb
+
+# The test environment is used exclusively to run your application's
+# test suite. You never need to work with it otherwise. Remember that
+# your test database is "scratch space" for the test suite and is wiped
+# and recreated between test runs. Don't rely on the data there!
+config.cache_classes = true
+
+# Log error messages when you accidentally call methods on nil.
+config.whiny_nils = true
+
+# Show full error reports and disable caching
+config.action_controller.consider_all_requests_local = true
+config.action_controller.perform_caching = false
+
+# Tell ActionMailer not to deliver emails to the real world.
+# The :test delivery method accumulates sent emails in the
+# ActionMailer::Base.deliveries array.
+config.action_mailer.delivery_method = :test
\ No newline at end of file
diff --git a/config/environments/development.rb b/config/environments/development.rb
new file mode 100755
index 0000000..0589aa9
--- /dev/null
+++ b/config/environments/development.rb
@@ -0,0 +1,21 @@
+# Settings specified here will take precedence over those in config/environment.rb
+
+# In the development environment your application's code is reloaded on
+# every request. This slows down response time but is perfect for development
+# since you don't have to restart the webserver when you make code changes.
+config.cache_classes = false
+
+# Log error messages when you accidentally call methods on nil.
+config.whiny_nils = true
+
+# Enable the breakpoint server that script/breakpointer connects to
+config.breakpoint_server = true
+
+# Show full error reports and disable caching
+config.action_controller.consider_all_requests_local = true
+config.action_controller.perform_caching = false
+config.action_view.cache_template_extensions = false
+config.action_view.debug_rjs = true
+
+# Don't care if the mailer can't send
+config.action_mailer.raise_delivery_errors = false
diff --git a/config/environments/production.rb b/config/environments/production.rb
new file mode 100755
index 0000000..5a4e2b1
--- /dev/null
+++ b/config/environments/production.rb
@@ -0,0 +1,18 @@
+# Settings specified here will take precedence over those in config/environment.rb
+
+# The production environment is meant for finished, "live" apps.
+# Code is not reloaded between requests
+config.cache_classes = true
+
+# Use a different logger for distributed setups
+# config.logger = SyslogLogger.new
+
+# Full error reports are disabled and caching is turned on
+config.action_controller.consider_all_requests_local = false
+config.action_controller.perform_caching = true
+
+# Enable serving of images, stylesheets, and javascripts from an asset server
+# config.action_controller.asset_host = "http://assets.example.com"
+
+# Disable delivery errors if you bad email addresses should just be ignored
+# config.action_mailer.raise_delivery_errors = false
diff --git a/config/environments/test.rb b/config/environments/test.rb
new file mode 100755
index 0000000..f0689b9
--- /dev/null
+++ b/config/environments/test.rb
@@ -0,0 +1,19 @@
+# Settings specified here will take precedence over those in config/environment.rb
+
+# The test environment is used exclusively to run your application's
+# test suite. You never need to work with it otherwise. Remember that
+# your test database is "scratch space" for the test suite and is wiped
+# and recreated between test runs. Don't rely on the data there!
+config.cache_classes = true
+
+# Log error messages when you accidentally call methods on nil.
+config.whiny_nils = true
+
+# Show full error reports and disable caching
+config.action_controller.consider_all_requests_local = true
+config.action_controller.perform_caching = false
+
+# Tell ActionMailer not to deliver emails to the real world.
+# The :test delivery method accumulates sent emails in the
+# ActionMailer::Base.deliveries array.
+config.action_mailer.delivery_method = :test
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
new file mode 100755
index 0000000..3837a7b
--- /dev/null
+++ b/config/routes.rb
@@ -0,0 +1,26 @@
+ActionController::Routing::Routes.draw do |map|
+ # The priority is based upon order of creation: first created -> highest priority.
+
+ # Sample of regular route:
+ # map.connect 'products/:id', :controller => 'catalog', :action => 'view'
+ # Keep in mind you can assign values other than :controller and :action
+
+ # Sample of named route:
+ # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
+ # This route can be invoked with purchase_url(:id => product.id)
+
+ # You can have the root of your site routed by hooking up ''
+ # -- just remember to delete public/index.html.
+ # map.connect '', :controller => "welcome"
+
+ # Allow downloading Web Service WSDL as a file with an extension
+ # instead of a file named 'wsdl'
+ map.connect ':controller/service.wsdl', :action => 'wsdl'
+
+ map.resources :studyplans, :users, :course_registrations
+
+ # Install the default route as the lowest priority.
+ map.connect ':controller/:action/:id'
+
+ map.home '', :controller => 'studyplans'
+end
|
robrix/hammerc
|
47a14ee68dc9d3e039a41501aacfded310b5a6b5
|
Moved some functionality into the compiler visitor.
|
diff --git a/Classes/HammerRuleCompiler.h b/Classes/HammerRuleCompiler.h
index 25a7c95..72eb3bc 100644
--- a/Classes/HammerRuleCompiler.h
+++ b/Classes/HammerRuleCompiler.h
@@ -1,32 +1,28 @@
// HammerRuleCompiler.h
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import <Foundation/Foundation.h>
#import "Hammer.h"
#import "ARXModule.h"
@class ARXContext, ARXFunction;
@interface HammerRuleCompiler : HammerRuleVisitor {
ARXContext *context;
ARXModule *module;
HammerRulePrinter *printer;
}
+(id)compiler;
@property (nonatomic, readonly) ARXModule *module;
-(NSString *)nameForRule:(HammerRuleRef)rule;
--(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule;
--(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrule:(ARXFunction *)subrule;
--(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules;
-
-(ARXModuleFunctionDefinitionBlock)rangeOfMatchSkippingIgnorableCharactersDefinitionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(ARXFunction *)lengthOfMatch;
-(HammerRuleRef)compileRule:(HammerRuleRef)rule;
@end
diff --git a/Classes/HammerRuleCompiler.m b/Classes/HammerRuleCompiler.m
index 72e6b9a..ccaf2e1 100644
--- a/Classes/HammerRuleCompiler.m
+++ b/Classes/HammerRuleCompiler.m
@@ -1,287 +1,286 @@
// HammerRuleCompiler.m
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import "HammerBlockRuleVisitor.h"
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
#import "HammerRuleCompilerVisitor.h"
#import "Auspicion.h"
#import "Hammer.h"
#import "ARXModule+RuntimeTypeEncodings.h"
@implementation HammerRuleCompiler
@synthesize module;
+(id)compiler {
return [[self alloc] init];
}
-(id)init {
if(self = [super init]) {
context = [[ARXContext context] retain];
module = [[ARXModule moduleWithName: @"HammerRuleCompilerModule" inContext: context] retain];
printer = [[HammerRulePrinter alloc] init];
ARXModuleImportType(module, HammerIndex);
ARXModuleImportType(module, CFIndex);
[module setType: context.int1Type forName: @"Boolean"];
ARXModuleImportType(module, UniChar);
CFCharacterSetRef characterSet = NULL;
CFStringRef string = NULL;
[module setObjCType: @encode(__typeof__(characterSet)) forName: @"CFCharacterSetRef"];
[module setObjCType: @encode(__typeof__(string)) forName: @"CFStringRef"];
ARXStructureType *rangeType = (ARXStructureType *)ARXModuleImportType(module, NSRange);
[rangeType declareElementNames: [NSArray arrayWithObjects:
@"location",
@"length",
nil]];
ARXModuleImportType(module, HammerRuleRef);
ARXModuleImportType(module, HammerSequenceRef);
ARXModuleImportType(module, HammerMatchRef);
ARXModuleImportType(module, NSString *);
ARXStructureType *parserStateType = (ARXStructureType *)ARXModuleImportType(module, HammerParserState);
[parserStateType declareElementNames: [NSArray arrayWithObjects:
@"sequence",
@"errorContext",
@"matchContext",
@"ruleGraph",
@"isIgnoringMatches",
nil]];
- [module setType: [ARXType pointerTypeToType: parserStateType] forName: @"HammerParserState *"];
+ [module setType: [ARXType pointerTypeToType: parserStateType] forName: @"HammerParserState*"];
ARXFunctionType *lengthOfMatch = [ARXType functionType: context.integerType,
[module typeNamed: @"HammerIndex"],
- [module typeNamed: @"HammerParserState *"],
+ [module typeNamed: @"HammerParserState*"],
nil];
[lengthOfMatch declareArgumentNames: [NSArray arrayWithObjects: @"initial", @"state", nil]];
[module setType: lengthOfMatch forName: @"lengthOfMatch"];
ARXFunctionType *rangeOfMatch = [ARXType functionType: context.int1Type,
[ARXType pointerTypeToType: [module typeNamed: @"NSRange"]],
[module typeNamed: @"HammerIndex"],
- [module typeNamed: @"HammerParserState *"],
+ [module typeNamed: @"HammerParserState*"],
nil];
[rangeOfMatch declareArgumentNames: [NSArray arrayWithObjects: @"outrange", @"initial", @"state", nil]];
[module setType: rangeOfMatch forName: @"rangeOfMatch"];
}
return self;
}
-(HammerRuleRef)compileRule:(HammerRuleRef)rule {
HammerBuiltRuleFunctions *builtFunctions = nil;
ARXFunction *initializer = nil;
@try {
HammerBlockRuleVisitor *ruleVisitor = [[HammerBlockRuleVisitor alloc] init];
[ruleVisitor visitRule: rule withVisitBlock: ^(HammerRuleRef rule, NSString *shortName) {
SEL declarator = NSSelectorFromString([NSString stringWithFormat: @"declareGlobalDataFor%@:", shortName]);
if([self respondsToSelector: declarator]) {
[self performSelector: declarator withObject: rule];
}
}];
initializer = [module functionWithName: [NSString stringWithFormat: @"%@ initialize", [self nameForRule: rule]] type: [ARXType functionType: context.voidType, nil] definition: ^(ARXFunctionBuilder *function){
[ruleVisitor visitRule: rule withVisitBlock: ^(HammerRuleRef rule, NSString *shortName) {
SEL selector = NSSelectorFromString([NSString stringWithFormat: @"initializeDataFor%@:", shortName]);
if([self respondsToSelector: selector]) {
[self performSelector: selector withObject: rule];
}
}];
[function return];
}];
HammerRuleCompilerVisitor *visitor = [[HammerRuleCompilerVisitor alloc] initWithCompiler: self];
builtFunctions = HammerRuleAcceptVisitor(rule, visitor);
}
@catch(NSException *exception) {
NSLog(@"%@", [[exception callStackSymbols] componentsJoinedByString: @"\n"]);
@throw exception;
}
NSError *error = nil;
if(![module verifyWithError: &error]) {
// LLVMDumpModule([module moduleRef]);
NSLog(@"Error in module: %@", error.localizedDescription);
return nil;
}
ARXCompiler *compiler = [ARXCompiler compilerWithContext: context];
[compiler addModule: module];
ARXOptimizer *optimizer = [ARXOptimizer optimizerWithCompiler: compiler];
[optimizer addConstantPropagationPass];
[optimizer addInstructionCombiningPass];
[optimizer addPromoteMemoryToRegisterPass];
// [optimizer addGVNPass];
[optimizer addCFGSimplificationPass];
[optimizer optimizeModule: module];
void (*initialize)() = [compiler compiledFunction: initializer];
initialize();
HammerCompiledRuleRef compiledRule = HammerCompiledRuleCreate(rule, [compiler compiledFunction: builtFunctions.lengthOfMatch], [compiler compiledFunction: builtFunctions.rangeOfMatch]);
return compiledRule;
}
-(NSString *)nameForRule:(HammerRuleRef)rule {
return [NSString stringWithFormat: @"%s(%@)", RXObjectTypeGetName(RXGetType(rule)), [printer printRule: rule]];
}
-(ARXFunction *)lengthOfIgnorableCharactersFunction {
- return [module externalFunctionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"], nil]];
-/*
- return [module functionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"], nil] definition: ^(ARXFunctionBuilder *function) {
- ARXPointerValue
- *length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]],
- *ignorableRule = [function allocateVariableOfType: [module typeNamed: @"HammerRuleRef"] value: [[self ruleGraphGetRuleForNameFunction] call: ((ARXPointerValue *)[function argumentNamed: @"state"]).value elementNamed: @"ruleGraph"]];
-
- }];
-*/
-}
-
--(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule {
- return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:", (NSString *)HammerRuleGetShortTypeName(rule)]) withObject: rule];
-}
-
--(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrule:(ARXFunction *)subrule {
- return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrule:", (NSString *)HammerRuleGetShortTypeName(rule), subrule]) withObject: rule withObject: subrule];
-}
-
--(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
- return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrules:", (NSString *)HammerRuleGetShortTypeName(rule), subrules]) withObject: rule withObject: subrules];
+ return [module externalFunctionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState*"], [module typeNamed: @"HammerIndex"], nil]];
}
-(ARXModuleFunctionDefinitionBlock)rangeOfMatchSkippingIgnorableCharactersDefinitionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(ARXFunction *)lengthOfMatch {
return [^(ARXFunctionBuilder *function) {
ARXPointerValue
*length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]],
*ignorable = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]];
[[length.value equals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
ignorable.value = [[self lengthOfIgnorableCharactersFunction] call: [function argumentNamed: @"state"], [function argumentNamed: @"initial"]];
[[ignorable.value notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
length.value = [lengthOfMatch call: [[function argumentNamed: @"initial"] plus: ignorable.value], [function argumentNamed: @"state"]];
}];
}];
[function structureArgumentNamed: @"outrange"].elements = [NSArray arrayWithObjects:
[[function argumentNamed: @"initial"] plus: [[ignorable.value equals: [context constantUnsignedInteger: NSNotFound]] select: [context constantUnsignedInteger: 0] or: ignorable.value]],
length.value,
nil];
[function return: [length.value notEquals: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForAlternationRule:(HammerAlternationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
return [^(ARXFunctionBuilder *function) {
ARXPointerValue *length = [function allocateVariableOfType: context.integerType value: [context constantUnsignedInteger: NSNotFound]];
ARXBlock *returnBlock = [function addBlockWithName: @"return"];
for(HammerBuiltRuleFunctions *subrule in subrules) {
[[(length.value = [subrule.lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]) notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
[function goto: returnBlock];
}];
}
[function goto: returnBlock];
[returnBlock define: ^{
[function return: length.value];
}];
} copy];
}
--(ARXModuleFunctionDefinitionBlock)rangeOfMatchFunctionForAlternationRule:(HammerAlternationRuleRef)rule {
- NSLog(@"type of a function: %s", @encode(HammerRuleLengthOfMatchMethod));
- return nil;
+-(ARXFunction *)rulesShouldBuildMatchesFunction {
+ return [module externalFunctionWithName: @"HammerParserStateRulesShouldBuildMatches" type: [ARXType functionType: context.int1Type, [module typeNamed: @"HammerParserState*"], nil]];
+}
+
+-(ARXModuleFunctionDefinitionBlock)rangeOfMatchDefinitionForAlternationRule:(HammerAlternationRuleRef)rule withLengthOfMatchFunction:(ARXFunction *)lengthOfMatch {
+ return [^(ARXFunctionBuilder *function) {
+ ARXStructureValue *innerState = (ARXStructureValue *)[function allocateVariableOfType: [module typeNamed: @"HammerParserState"]];
+ NSLog(@"%@", [function structureArgumentNamed: @"state"]);
+ NSLog(@"%@", [[function structureArgumentNamed: @"state"] type]);
+ innerState.elements = [function structureArgumentNamed: @"state"].elements;
+ NSLog(@"%@", innerState);
+ ARXPointerValue *result = [function allocateVariableOfType: context.int1Type value: [[self rangeOfMatchSkippingIgnorableCharactersDefinitionForRule: rule withLengthOfMatchFunction: lengthOfMatch] call: [function argumentNamed: @"outrange"], [function argumentNamed: @"initial"], innerState]];
+
+ [[[result.value invert] and: [self.rulesShouldBuildMatchesFunction call: [function argumentNamed: @"state"]]] ifTrue: ^{
+ [[function structureArgumentNamed: @"state"] setElement:
+ [[[[innerState structureElementNamed: @"errorContext"] elementNamed: @"rule"] notEquals: [context constantNullOfType: [module typeNamed: @"HammerRuleRef"]]]
+ select: [innerState structureElementNamed: @"errorContext"]
+ or: [context constantStructure: [function argumentNamed: @"initial"], rule, nil]]
+ forName: @"errorContext"];
+ }];
+ [function return: result.value];
+ } copy];
}
-(ARXFunction *)sequenceGetLengthFunction {
return [module externalFunctionWithName: @"HammerSequenceGetLength" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerSequenceRef"], nil]];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForCharacterRule:(HammerCharacterRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
[function return: [[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction
call: [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"]]]
select: [context constantUnsignedInteger: 1]
or: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
-(ARXFunction *)characterIsMemberFunction {
return [module externalFunctionWithName: @"CFCharacterSetIsCharacterMember" type: [ARXType functionType: [module typeNamed: @"Boolean"], [module typeNamed: @"CFCharacterSetRef"], [module typeNamed: @"UniChar"], nil]];
}
-(ARXFunction *)getCharacterAtIndexFunction {
return [module externalFunctionWithName: @"CFStringGetCharacterAtIndex" type: [ARXType functionType: [module typeNamed: @"UniChar"], [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"CFIndex"], nil]];
}
-(ARXFunction *)sequenceGetStringFunction {
return [module externalFunctionWithName: @"HammerSequenceGetString" type: [ARXType functionType: [module typeNamed: @"CFStringRef"], [module typeNamed: @"HammerSequenceRef"], nil]];
}
-(void)declareGlobalDataForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
[module declareGlobalOfType: [module typeNamed: @"CFCharacterSetRef"] forName: [self nameForRule: rule]];
}
-(void)initializeDataForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
// fixme: constant pointers are only viable for JIT
// fixme: actually call the initializers from a function
[module setGlobal: [context constantPointer: (void *)HammerCharacterSetRuleGetCharacterSet(rule) ofType: [module typeNamed: @"CFCharacterSetRef"]] forName: [self nameForRule: rule]];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
ARXValue *sequence = [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"];
[function return: [[[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction call: sequence]]
and: [self.characterIsMemberFunction call: [module globalNamed: [self nameForRule: rule]], [self.getCharacterAtIndexFunction call: [self.sequenceGetStringFunction call: sequence], [function argumentNamed: @"initial"], nil], nil]
] select: [context constantUnsignedInteger: 1]
or: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
// -(ARXModuleFunctionDefinitionBlock)rangeOfMatchDefinitionForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
//
// }
-(ARXFunction *)sequenceContainsSequenceAtIndexFunction {
return [module externalFunctionWithName: @"HammerSequenceContainsSequenceAtIndex" type: [ARXType functionType: context.int1Type, [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"HammerIndex"], nil]];
}
-(void)declareGlobalDataForLiteralRule:(HammerLiteralRuleRef)rule {
[module declareGlobalOfType: [module typeNamed: @"HammerSequenceRef"] forName: [self nameForRule: rule]];
}
-(void)initializeDataForLiteralRule:(HammerLiteralRuleRef)rule {
// fixme: constant pointers are only viable for JIT
// fixme: actually call the initializers from a function
[module setGlobal: [context constantPointer: (void *)HammerLiteralRuleGetSequence(rule) ofType: [module typeNamed: @"HammerSequenceRef"]] forName: [self nameForRule: rule]];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForLiteralRule:(HammerLiteralRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
ARXValue *sequence = [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"];
[function return: [[[self.sequenceContainsSequenceAtIndexFunction call: sequence, [module globalNamed: [self nameForRule: rule]], [function argumentNamed: @"initial"]] toBoolean]
select: [context constantUnsignedInteger: HammerSequenceGetLength(HammerLiteralRuleGetSequence(rule))]
or: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
@end
diff --git a/Classes/HammerRuleCompilerVisitor.m b/Classes/HammerRuleCompilerVisitor.m
index 54f4dc0..b854f6a 100644
--- a/Classes/HammerRuleCompilerVisitor.m
+++ b/Classes/HammerRuleCompilerVisitor.m
@@ -1,66 +1,78 @@
// HammerRuleCompilerVisitor.m
// Created by Rob Rix on 2010-06-12
// Copyright 2010 Monochrome Industries
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
#import "HammerRuleCompilerVisitor.h"
@implementation HammerRuleCompilerVisitor
-(id)initWithCompiler:(HammerRuleCompiler *)_compiler {
if(self = [super init]) {
compiler = _compiler;
}
return self;
}
-(void)visitRule:(HammerRuleRef)rule {}
-(NSString *)nameForFunction:(NSString *)function forRule:(HammerRuleRef)rule {
return [NSString stringWithFormat: @"%@ %@", [compiler nameForRule: rule], function];
}
-(id)lengthOfMatchFunctionForRule:(HammerRuleRef)rule withDefinition:(ARXModuleFunctionDefinitionBlock)definition {
return [compiler.module functionWithName: [self nameForFunction: @"lengthOfMatch" forRule: rule] type: [compiler.module typeNamed: @"lengthOfMatch"] definition: definition];
}
-(id)rangeOfMatchFunctionForRule:(HammerRuleRef)rule withDefinition:(ARXModuleFunctionDefinitionBlock)definition {
return [compiler.module functionWithName: [self nameForFunction: @"rangeOfMatch" forRule: rule] type: [compiler.module typeNamed: @"rangeOfMatch"] definition: definition];
}
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule {
+ return [compiler performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:", (NSString *)HammerRuleGetShortTypeName(rule)]) withObject: rule];
+}
+
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrule:(ARXFunction *)subrule {
+ return [compiler performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrule:", (NSString *)HammerRuleGetShortTypeName(rule), subrule]) withObject: rule withObject: subrule];
+}
+
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
+ return [compiler performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrules:", (NSString *)HammerRuleGetShortTypeName(rule), subrules]) withObject: rule withObject: subrules];
+}
+
+
+-(ARXModuleFunctionDefinitionBlock)rangeOfMatchDefinitionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(ARXFunction *)lengthOfMatch {
+ SEL selector = NSSelectorFromString([NSString stringWithFormat: @"rangeOfMatchDefinitionFor%@:withLengthOfMatchFunction:", (NSString *)HammerRuleGetShortTypeName(rule)]);
+ return [compiler respondsToSelector: selector]
+ ? (ARXModuleFunctionDefinitionBlock)[compiler performSelector: selector withObject: rule withObject: lengthOfMatch]
+ : [compiler rangeOfMatchSkippingIgnorableCharactersDefinitionForRule: rule withLengthOfMatchFunction: lengthOfMatch];
+}
+
+
-(id)leaveRule:(HammerRuleRef)rule {
- SEL selector = NSSelectorFromString([NSString stringWithFormat: @"rangeOfMatchDefinitionFor%@:", (NSString *)HammerRuleGetShortTypeName(rule)]);
HammerBuiltRuleFunctions *functions = [[HammerBuiltRuleFunctions alloc] init];
- functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [compiler lengthOfMatchDefinitionForRule: rule]];
- functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [compiler respondsToSelector: selector]
- ? [compiler performSelector: selector withObject: rule]
- : [compiler rangeOfMatchSkippingIgnorableCharactersDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
+ functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [self lengthOfMatchDefinitionForRule: rule]];
+ functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [self rangeOfMatchDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
return functions;
}
-(id)leaveRule:(HammerRuleRef)rule withVisitedSubrule:(id)subrule {
- SEL selector = NSSelectorFromString([NSString stringWithFormat: @"rangeOfMatchDefinitionFor%@:withVisitedSubrule:", (NSString *)HammerRuleGetShortTypeName(rule)]);
HammerBuiltRuleFunctions *functions = [[HammerBuiltRuleFunctions alloc] init];
- functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [compiler lengthOfMatchDefinitionForRule: rule withVisitedSubrule: subrule]];
- functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [compiler respondsToSelector: selector]
- ? [compiler performSelector: selector withObject: rule withObject: subrule]
- : [compiler rangeOfMatchSkippingIgnorableCharactersDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
+ functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [self lengthOfMatchDefinitionForRule: rule withVisitedSubrule: subrule]];
+ functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [self rangeOfMatchDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
return functions;
}
-(id)leaveRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
- SEL selector = NSSelectorFromString([NSString stringWithFormat: @"rangeOfMatchDefinitionFor%@:withVisitedSubrules:", (NSString *)HammerRuleGetShortTypeName(rule)]);
HammerBuiltRuleFunctions *functions = [[HammerBuiltRuleFunctions alloc] init];
- functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [compiler lengthOfMatchDefinitionForRule: rule withVisitedSubrules: subrules]];
- functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [compiler respondsToSelector: selector]
- ? [compiler performSelector: selector withObject: rule withObject: subrules]
- : [compiler rangeOfMatchSkippingIgnorableCharactersDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
+ functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [self lengthOfMatchDefinitionForRule: rule withVisitedSubrules: subrules]];
+ functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [self rangeOfMatchDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
return functions;
}
@end
diff --git a/External/Auspicion b/External/Auspicion
index 831e37a..292a001 160000
--- a/External/Auspicion
+++ b/External/Auspicion
@@ -1 +1 @@
-Subproject commit 831e37a6ae58712217f582f1132d0e01c13f752c
+Subproject commit 292a001df2d2abdc632d669bbbbaf583b05e5ea9
diff --git a/External/Hammer b/External/Hammer
index 82f8413..804ab49 160000
--- a/External/Hammer
+++ b/External/Hammer
@@ -1 +1 @@
-Subproject commit 82f8413dbb051876c44e28bbd66f6673d5addd2e
+Subproject commit 804ab49d850825e5f0fe5adf9b78bc95a70d2ea5
|
robrix/hammerc
|
eeb273847919978b771bebe0896ac416bb8c03b9
|
HammerCompiledRule wasnât keeping a strong reference to its source rule, and wasnât importing RXObjectâs fields.
|
diff --git a/Classes/HammerCompiledRule.m b/Classes/HammerCompiledRule.m
index 263940f..26ff43a 100644
--- a/Classes/HammerCompiledRule.m
+++ b/Classes/HammerCompiledRule.m
@@ -1,78 +1,80 @@
// HammerCompiledRule.m
// Created by Rob Rix on 2009-12-23
// Copyright 2009 Monochrome Industries
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
#import <Auspicion/Auspicion.h>
@implementation HammerBuiltRuleFunctions
@synthesize lengthOfMatch, rangeOfMatch;
@end
static struct HammerRuleType HammerCompiledRuleType;
typedef struct HammerCompiledRule {
- HammerRuleRef sourceRule;
+ RX_FIELDS_FROM(HammerRule, HammerRuleType);
+
+ __strong HammerRuleRef sourceRule;
HammerCompiledRuleLengthOfMatchFunction lengthOfMatch;
HammerCompiledRuleRangeOfMatchFunction rangeOfMatch;
} HammerCompiledRule;
HammerCompiledRuleRef HammerCompiledRuleCreate(HammerRuleRef sourceRule, HammerCompiledRuleLengthOfMatchFunction lengthOfMatch, HammerCompiledRuleRangeOfMatchFunction rangeOfMatch) {
HammerCompiledRuleRef self = RXCreate(sizeof(HammerCompiledRule), &HammerCompiledRuleType);
self->sourceRule = HammerRuleRetain(sourceRule);
self->lengthOfMatch = lengthOfMatch;
self->rangeOfMatch = rangeOfMatch;
return self;
}
void HammerCompiledRuleDeallocate(HammerCompiledRuleRef self) {
HammerRuleRelease(self->sourceRule);
}
bool HammerCompiledRuleIsEqual(HammerCompiledRuleRef self, HammerCompiledRuleRef other) {
return
(RXGetType(self) == RXGetType(other))
&& RXEquals(self->sourceRule, other->sourceRule);
}
HammerRuleRef HammerCompiledRuleGetSourceRule(HammerCompiledRuleRef self) {
return self->sourceRule;
}
HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleGetLengthOfMatchFunction(HammerCompiledRuleRef self) {
return self->lengthOfMatch;
}
HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleGetRangeOfMatchFunction(HammerCompiledRuleRef self) {
return self->rangeOfMatch;
}
HammerIndex HammerCompiledRuleLengthOfMatch(HammerCompiledRuleRef self, HammerIndex initial, HammerParserState *state) {
return self->lengthOfMatch(initial, state);
}
HammerIndex HammerCompiledRuleRangeOfMatch(HammerCompiledRuleRef self, NSRange *outrange, HammerIndex initial, HammerParserState *state) {
return self->rangeOfMatch(outrange, initial, state);
}
id HammerCompiledRuleAcceptVisitor(HammerCompiledRuleRef self, id<HammerRuleVisitor> visitor) {
return HammerRuleAcceptVisitor(self->sourceRule, visitor);
}
static struct HammerRuleType HammerCompiledRuleType = {
.name = "HammerCompiledRule",
.deallocate = (RXDeallocateMethod)HammerCompiledRuleDeallocate,
.isEqual = (RXIsEqualMethod)HammerCompiledRuleIsEqual,
.lengthOfMatch = (HammerRuleLengthOfMatchMethod)HammerCompiledRuleLengthOfMatch,
.rangeOfMatch = (HammerRuleRangeOfMatchMethod)HammerCompiledRuleRangeOfMatch,
.acceptVisitor = (HammerRuleAcceptVisitorMethod)HammerCompiledRuleAcceptVisitor,
};
|
robrix/hammerc
|
fe2014ab9066dcc67b2acfbd5512b5292d7e207d
|
Removed references to tests removed from Hammer.
|
diff --git a/hammerc.xcodeproj/project.pbxproj b/hammerc.xcodeproj/project.pbxproj
index 03ac387..a52fed2 100644
--- a/hammerc.xcodeproj/project.pbxproj
+++ b/hammerc.xcodeproj/project.pbxproj
@@ -1,970 +1,962 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 45;
objects = {
/* Begin PBXBuildFile section */
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859EA3029092ED04C91782 /* hammerc.1 */; };
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */; };
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */; };
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */; };
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */; };
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */; };
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */; };
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */; };
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */; };
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */; };
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */; };
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */; };
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E51113F5FEF0086F21C /* hammerc.m */; };
D4551E82113F85830086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EBA113F88300086F21C /* bootstrap-hammerc.m */; };
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551EE3113F88700086F21C /* digit.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC3113F88700086F21C /* digit.grammar */; };
D4551EE4113F88700086F21C /* letter.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC4113F88700086F21C /* letter.grammar */; };
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */; };
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC7113F88700086F21C /* HammerBuilderTests.m */; };
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */; };
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */; };
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */; };
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */; };
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */; };
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */; };
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */; };
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */; };
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */; };
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */; };
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDE113F88700086F21C /* HammerRuleTests.m */; };
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */; };
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EF7113F88A00086F21C /* Hammer.grammar */; };
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D48B23EB11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
D48B23EC11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
D48B23ED11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
D48B23EE11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B24BC11B25720007CBBB4 /* RXAssertions.m */; };
D4D74F1511C38023002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F1611C38031002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F1711C38034002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F2411C3817B002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
D4D74F2511C38195002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
D4D74F2611C38196002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
D4D74F3011C38209002FF2F1 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
D4D74F3111C3820E002FF2F1 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
D4D750E211C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
D4D750E311C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
D4D750FF11C3D8E8002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
D4D753B211C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */; };
D4D753B311C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */; };
D4D753B411C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D4551DFE113E48B20086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
proxyType = 1;
remoteGlobalIDString = D4551DF9113E48A90086F21C;
remoteInfo = "bootstrap-hammerc";
};
D4551E7A113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4041AB1113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D4551E7E113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4DB11D60D138C7400C730A3;
remoteInfo = Tests;
};
D4551E80113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D404EB4610F5791C007612E9;
remoteInfo = "Measure Performance";
};
D4551E9C113F85D70086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D2AAC046055464E500DB518D;
remoteInfo = Polymorph;
};
D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4AB04351180335A0048BBA1;
remoteInfo = Tests;
};
D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D2AAC07E0554694100DB518D;
remoteInfo = RXAssertions;
};
D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D442A488106FD94900944F07;
remoteInfo = Tests;
};
D4D74F0B11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D2AAC07E0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4D74F0D11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4D9DE5510EB5F4F003EEE90;
remoteInfo = AuspicionLLVM;
};
D4D74F0F11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4CF603311C32F8000C9DD15;
remoteInfo = Tests;
};
D4D74F1111C38010002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D2AAC07D0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4D74F1311C3801B002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D2AAC07D0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
8DD76F9E0486AA7600D96B5E /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 8;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
8DD76FA10486AA7600D96B5E /* hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = hammerc; sourceTree = BUILT_PRODUCTS_DIR; };
C6859EA3029092ED04C91782 /* hammerc.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = hammerc.1; sourceTree = "<group>"; };
D4551DFA113E48A90086F21C /* bootstrap-hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "bootstrap-hammerc"; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E28113F5F6D0086F21C /* Tests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Tests.octest; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E29113F5F6D0086F21C /* Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Tests-Info.plist"; sourceTree = "<group>"; };
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledAlternationRuleTests.m; sourceTree = "<group>"; };
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterRuleTests.m; sourceTree = "<group>"; };
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralRuleTests.m; sourceTree = "<group>"; };
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledNamedRuleTests.m; sourceTree = "<group>"; };
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledReferenceRuleTests.m; sourceTree = "<group>"; };
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompilerTests.m; sourceTree = "<group>"; };
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCompiledRule.h; sourceTree = "<group>"; };
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRule.m; sourceTree = "<group>"; };
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleCompiler.h; sourceTree = "<group>"; };
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompiler.m; sourceTree = "<group>"; };
D4551E51113F5FEF0086F21C /* hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = hammerc.m; sourceTree = "<group>"; };
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hammerc_Prefix.pch; sourceTree = "<group>"; };
D4551E6E113F85780086F21C /* Hammer.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Hammer.xcodeproj; sourceTree = "<group>"; };
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "bootstrap-hammerc.m"; sourceTree = "<group>"; };
D4551EC3113F88700086F21C /* digit.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = digit.grammar; sourceTree = "<group>"; };
D4551EC4113F88700086F21C /* letter.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = letter.grammar; sourceTree = "<group>"; };
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerAlternationRuleTests.h; sourceTree = "<group>"; };
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerAlternationRuleTests.m; sourceTree = "<group>"; };
D4551EC7113F88700086F21C /* HammerBuilderTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerBuilderTests.m; sourceTree = "<group>"; };
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterRuleTests.h; sourceTree = "<group>"; };
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterRuleTests.m; sourceTree = "<group>"; };
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterSetRuleTests.h; sourceTree = "<group>"; };
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerConcatenationRuleTests.m; sourceTree = "<group>"; };
- D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerContainerRuleTests.m; sourceTree = "<group>"; };
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralRuleTests.h; sourceTree = "<group>"; };
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralRuleTests.m; sourceTree = "<group>"; };
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLookaheadRuleTests.h; sourceTree = "<group>"; };
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerNamedRuleTests.h; sourceTree = "<group>"; };
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerNamedRuleTests.m; sourceTree = "<group>"; };
- D4551ED7113F88700086F21C /* HammerParserTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerParserTests.m; sourceTree = "<group>"; };
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerReferenceRuleTests.h; sourceTree = "<group>"; };
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerReferenceRuleTests.m; sourceTree = "<group>"; };
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRepetitionRuleTests.h; sourceTree = "<group>"; };
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRulePrinterTests.m; sourceTree = "<group>"; };
D4551EDD113F88700086F21C /* HammerRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleTests.h; sourceTree = "<group>"; };
D4551EDE113F88700086F21C /* HammerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleTests.m; sourceTree = "<group>"; };
- D4551EDF113F88700086F21C /* HammerTestParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestParser.h; sourceTree = "<group>"; };
- D4551EE0113F88700086F21C /* HammerTestParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestParser.m; sourceTree = "<group>"; };
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestRuleVisitor.h; sourceTree = "<group>"; };
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestRuleVisitor.m; sourceTree = "<group>"; };
D4551EF7113F88A00086F21C /* Hammer.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = Hammer.grammar; path = "../Other Sources/Hammer.grammar"; sourceTree = "<group>"; };
D48B23E711B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARXModule+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "ARXModule+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
D48B23E911B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARXType+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "ARXType+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
D48B247911B25720007CBBB4 /* RXAllocation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAllocation.h; sourceTree = "<group>"; };
D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXCoreFoundationIntegration.h; sourceTree = "<group>"; };
D48B247D11B25720007CBBB4 /* RXObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObject.h; sourceTree = "<group>"; };
D48B248011B25720007CBBB4 /* RXObjectType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObjectType.h; sourceTree = "<group>"; };
D48B248111B25720007CBBB4 /* RXShadowObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXShadowObject.h; sourceTree = "<group>"; };
D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Polymorph.xcodeproj; sourceTree = "<group>"; };
D48B24BB11B25720007CBBB4 /* RXAssertions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAssertions.h; sourceTree = "<group>"; };
D48B24BC11B25720007CBBB4 /* RXAssertions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RXAssertions.m; sourceTree = "<group>"; };
D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = RXAssertions.xcodeproj; sourceTree = "<group>"; };
D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Auspicion.xcodeproj; sourceTree = "<group>"; };
D4D74F2211C3817B002FF2F1 /* NSObject+UniqueFactory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSObject+UniqueFactory.h"; path = "Classes/NSObject+UniqueFactory.h"; sourceTree = "<group>"; };
D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSObject+UniqueFactory.m"; path = "Classes/NSObject+UniqueFactory.m"; sourceTree = "<group>"; };
D4D750E011C3BE90002FF2F1 /* HammerRuleCompilerVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleCompilerVisitor.h; sourceTree = "<group>"; };
D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompilerVisitor.m; sourceTree = "<group>"; };
D4D753B011C670DC002FF2F1 /* HammerBlockRuleVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerBlockRuleVisitor.h; sourceTree = "<group>"; };
D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerBlockRuleVisitor.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
8DD76F9B0486AA7600D96B5E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1611C38031002FF2F1 /* libAuspicion.a in Frameworks */,
D4551E82113F85830086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF8113E48A90086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1711C38034002FF2F1 /* libAuspicion.a in Frameworks */,
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E25113F5F6D0086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1511C38023002FF2F1 /* libAuspicion.a in Frameworks */,
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
08FB7794FE84155DC02AAC07 /* hammerc */ = {
isa = PBXGroup;
children = (
D48B23E611B24D5E007CBBB4 /* Categories */,
08FB7795FE84155DC02AAC07 /* Classes */,
D4551E50113F5FEF0086F21C /* Other Sources */,
D4551E30113F5FB10086F21C /* Tests */,
C6859EA2029092E104C91782 /* Documentation */,
D4551E6B113F85410086F21C /* External */,
D4551E2F113F5F7D0086F21C /* Resources */,
1AB674ADFE9D54B511CA2CBB /* Products */,
);
name = hammerc;
sourceTree = "<group>";
};
08FB7795FE84155DC02AAC07 /* Classes */ = {
isa = PBXGroup;
children = (
D4D753B011C670DC002FF2F1 /* HammerBlockRuleVisitor.h */,
D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */,
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */,
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */,
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */,
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */,
D4D750E011C3BE90002FF2F1 /* HammerRuleCompilerVisitor.h */,
D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */,
);
path = Classes;
sourceTree = "<group>";
};
1AB674ADFE9D54B511CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
8DD76FA10486AA7600D96B5E /* hammerc */,
D4551DFA113E48A90086F21C /* bootstrap-hammerc */,
D4551E28113F5F6D0086F21C /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
C6859EA2029092E104C91782 /* Documentation */ = {
isa = PBXGroup;
children = (
C6859EA3029092ED04C91782 /* hammerc.1 */,
);
path = Documentation;
sourceTree = "<group>";
};
D4551E2F113F5F7D0086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551E29113F5F6D0086F21C /* Tests-Info.plist */,
);
path = Resources;
sourceTree = "<group>";
};
D4551E30113F5FB10086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */,
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */,
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */,
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */,
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */,
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */,
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */,
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */,
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */,
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */,
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551E50113F5FEF0086F21C /* Other Sources */ = {
isa = PBXGroup;
children = (
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */,
D4551E51113F5FEF0086F21C /* hammerc.m */,
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */,
);
path = "Other Sources";
sourceTree = "<group>";
};
D4551E6B113F85410086F21C /* External */ = {
isa = PBXGroup;
children = (
D4551E6D113F855E0086F21C /* Auspicion */,
D4551E6C113F85530086F21C /* Hammer */,
);
path = External;
sourceTree = "<group>";
};
D4551E6C113F85530086F21C /* Hammer */ = {
isa = PBXGroup;
children = (
D4551E6E113F85780086F21C /* Hammer.xcodeproj */,
D48B244C11B25720007CBBB4 /* External */,
D4551EF6113F88930086F21C /* Resources */,
D4551EC1113F88700086F21C /* Tests */,
);
path = Hammer;
sourceTree = "<group>";
};
D4551E6D113F855E0086F21C /* Auspicion */ = {
isa = PBXGroup;
children = (
D4D74F2211C3817B002FF2F1 /* NSObject+UniqueFactory.h */,
D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */,
D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */,
);
path = Auspicion;
sourceTree = "<group>";
};
D4551E6F113F85780086F21C /* Products */ = {
isa = PBXGroup;
children = (
D4551E7B113F85780086F21C /* libHammer.a */,
D4551E7F113F85780086F21C /* Tests.octest */,
D4551E81113F85780086F21C /* Measure Performance */,
);
name = Products;
sourceTree = "<group>";
};
D4551EC1113F88700086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551EC2113F88700086F21C /* Fixtures */,
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */,
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */,
D4551EC7113F88700086F21C /* HammerBuilderTests.m */,
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */,
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */,
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */,
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */,
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */,
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */,
- D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */,
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */,
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */,
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */,
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */,
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */,
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */,
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */,
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */,
- D4551ED7113F88700086F21C /* HammerParserTests.m */,
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */,
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */,
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */,
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */,
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */,
D4551EDD113F88700086F21C /* HammerRuleTests.h */,
D4551EDE113F88700086F21C /* HammerRuleTests.m */,
- D4551EDF113F88700086F21C /* HammerTestParser.h */,
- D4551EE0113F88700086F21C /* HammerTestParser.m */,
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */,
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551EC2113F88700086F21C /* Fixtures */ = {
isa = PBXGroup;
children = (
D4551EC3113F88700086F21C /* digit.grammar */,
D4551EC4113F88700086F21C /* letter.grammar */,
);
path = Fixtures;
sourceTree = "<group>";
};
D4551EF6113F88930086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551EF7113F88A00086F21C /* Hammer.grammar */,
);
path = Resources;
sourceTree = "<group>";
};
D48B23E611B24D5E007CBBB4 /* Categories */ = {
isa = PBXGroup;
children = (
D48B23E711B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.h */,
D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */,
D48B23E911B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.h */,
D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */,
);
path = Categories;
sourceTree = "<group>";
};
D48B244C11B25720007CBBB4 /* External */ = {
isa = PBXGroup;
children = (
D48B244D11B25720007CBBB4 /* Polymorph */,
D48B249111B25720007CBBB4 /* RXAssertions */,
);
path = External;
sourceTree = "<group>";
};
D48B244D11B25720007CBBB4 /* Polymorph */ = {
isa = PBXGroup;
children = (
D48B247811B25720007CBBB4 /* Classes */,
D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */,
);
path = Polymorph;
sourceTree = "<group>";
};
D48B247811B25720007CBBB4 /* Classes */ = {
isa = PBXGroup;
children = (
D48B247911B25720007CBBB4 /* RXAllocation.h */,
D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */,
D48B247D11B25720007CBBB4 /* RXObject.h */,
D48B248011B25720007CBBB4 /* RXObjectType.h */,
D48B248111B25720007CBBB4 /* RXShadowObject.h */,
);
path = Classes;
sourceTree = "<group>";
};
D48B248B11B25720007CBBB4 /* Products */ = {
isa = PBXGroup;
children = (
D48B24E211B25721007CBBB4 /* libPolymorph.a */,
D48B24E411B25721007CBBB4 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
D48B249111B25720007CBBB4 /* RXAssertions */ = {
isa = PBXGroup;
children = (
D48B24BB11B25720007CBBB4 /* RXAssertions.h */,
D48B24BC11B25720007CBBB4 /* RXAssertions.m */,
D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */,
);
path = RXAssertions;
sourceTree = "<group>";
};
D48B24BF11B25720007CBBB4 /* Products */ = {
isa = PBXGroup;
children = (
D48B24EB11B25721007CBBB4 /* libRXAssertions.a */,
D48B24ED11B25721007CBBB4 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
D4D74F0611C37FFC002FF2F1 /* Products */ = {
isa = PBXGroup;
children = (
D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */,
D4D74F0E11C37FFC002FF2F1 /* libAuspicionLLVM.a */,
D4D74F1011C37FFC002FF2F1 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
8DD76F960486AA7600D96B5E /* hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */;
buildPhases = (
8DD76F990486AA7600D96B5E /* Sources */,
8DD76F9B0486AA7600D96B5E /* Frameworks */,
8DD76F9E0486AA7600D96B5E /* CopyFiles */,
);
buildRules = (
);
dependencies = (
D4551DFF113E48B20086F21C /* PBXTargetDependency */,
);
name = hammerc;
productInstallPath = "$(HOME)/bin";
productName = hammerc;
productReference = 8DD76FA10486AA7600D96B5E /* hammerc */;
productType = "com.apple.product-type.tool";
};
D4551DF9113E48A90086F21C /* bootstrap-hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */;
buildPhases = (
D4551DF7113E48A90086F21C /* Sources */,
D4551DF8113E48A90086F21C /* Frameworks */,
);
buildRules = (
);
dependencies = (
D4551E9D113F85D70086F21C /* PBXTargetDependency */,
D4D74F1211C38010002FF2F1 /* PBXTargetDependency */,
);
name = "bootstrap-hammerc";
productName = "bootstrap-hammerc";
productReference = D4551DFA113E48A90086F21C /* bootstrap-hammerc */;
productType = "com.apple.product-type.tool";
};
D4551E27113F5F6D0086F21C /* Tests */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */;
buildPhases = (
D4551E24113F5F6D0086F21C /* Sources */,
D4551E23113F5F6D0086F21C /* Resources */,
D4551E25113F5F6D0086F21C /* Frameworks */,
D4551E26113F5F6D0086F21C /* ShellScript */,
);
buildRules = (
);
dependencies = (
D4551F00113F88CA0086F21C /* PBXTargetDependency */,
D4D74F1411C3801B002FF2F1 /* PBXTargetDependency */,
);
name = Tests;
productName = Tests;
productReference = D4551E28113F5F6D0086F21C /* Tests.octest */;
productType = "com.apple.product-type.bundle";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
08FB7793FE84155DC02AAC07 /* Project object */ = {
isa = PBXProject;
buildConfigurationList = 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */;
compatibilityVersion = "Xcode 3.1";
hasScannedForEncodings = 1;
mainGroup = 08FB7794FE84155DC02AAC07 /* hammerc */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = D4D74F0611C37FFC002FF2F1 /* Products */;
ProjectRef = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
},
{
ProductGroup = D4551E6F113F85780086F21C /* Products */;
ProjectRef = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
},
{
ProductGroup = D48B248B11B25720007CBBB4 /* Products */;
ProjectRef = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
},
{
ProductGroup = D48B24BF11B25720007CBBB4 /* Products */;
ProjectRef = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
},
);
projectRoot = "";
targets = (
8DD76F960486AA7600D96B5E /* hammerc */,
D4551DF9113E48A90086F21C /* bootstrap-hammerc */,
D4551E27113F5F6D0086F21C /* Tests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
D4551E7B113F85780086F21C /* libHammer.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libHammer.a;
remoteRef = D4551E7A113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E7F113F85780086F21C /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D4551E7E113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E81113F85780086F21C /* Measure Performance */ = {
isa = PBXReferenceProxy;
fileType = "compiled.mach-o.executable";
path = "Measure Performance";
remoteRef = D4551E80113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24E211B25721007CBBB4 /* libPolymorph.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libPolymorph.a;
remoteRef = D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24E411B25721007CBBB4 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24EB11B25721007CBBB4 /* libRXAssertions.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRXAssertions.a;
remoteRef = D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24ED11B25721007CBBB4 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libAuspicion.a;
remoteRef = D4D74F0B11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F0E11C37FFC002FF2F1 /* libAuspicionLLVM.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libAuspicionLLVM.a;
remoteRef = D4D74F0D11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F1011C37FFC002FF2F1 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D4D74F0F11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
D4551E23113F5F6D0086F21C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551EE3113F88700086F21C /* digit.grammar in Resources */,
D4551EE4113F88700086F21C /* letter.grammar in Resources */,
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
D4551E26113F5F6D0086F21C /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
8DD76F990486AA7600D96B5E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */,
D48B23ED11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
D48B23EE11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */,
D4D74F2611C38196002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
D4D750E311C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
D4D753B311C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF7113E48A90086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */,
D48B23EB11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
D48B23EC11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */,
D4D74F2511C38195002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
D4D750E211C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
D4D753B211C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E24113F5F6D0086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */,
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */,
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */,
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */,
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */,
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */,
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */,
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */,
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */,
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */,
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */,
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */,
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */,
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */,
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */,
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */,
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */,
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */,
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */,
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */,
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */,
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */,
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */,
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */,
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */,
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */,
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */,
D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */,
D4D74F2411C3817B002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
D4D74F3011C38209002FF2F1 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
D4D74F3111C3820E002FF2F1 /* ARXType+RuntimeTypeEncodings.m in Sources */,
D4D750FF11C3D8E8002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
D4D753B411C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D4551DFF113E48B20086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D4551DF9113E48A90086F21C /* bootstrap-hammerc */;
targetProxy = D4551DFE113E48B20086F21C /* PBXContainerItemProxy */;
};
D4551E9D113F85D70086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551E9C113F85D70086F21C /* PBXContainerItemProxy */;
};
D4551F00113F88CA0086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */;
};
D4D74F1211C38010002FF2F1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
targetProxy = D4D74F1111C38010002FF2F1 /* PBXContainerItemProxy */;
};
D4D74F1411C3801B002FF2F1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
targetProxy = D4D74F1311C3801B002FF2F1 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
1DEB927508733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_FIX_AND_CONTINUE = YES;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Debug;
};
1DEB927608733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_MODEL_TUNING = G5;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Release;
};
1DEB927908733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_GC = required;
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "External/Include/**";
ONLY_ACTIVE_ARCH = YES;
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = macosx10.6;
};
name = Debug;
};
1DEB927A08733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_GC = required;
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "External/Include/**";
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = macosx10.5;
};
name = Release;
};
D4551DFC113E48A90086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
};
name = Debug;
};
D4551DFD113E48A90086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = YES;
|
robrix/hammerc
|
d0c6e8df3df0241e68cbd78b1954dcd18f965ceb
|
Character rules were not being compiled correctly.
|
diff --git a/Classes/HammerRuleCompiler.m b/Classes/HammerRuleCompiler.m
index c8af658..72e6b9a 100644
--- a/Classes/HammerRuleCompiler.m
+++ b/Classes/HammerRuleCompiler.m
@@ -1,285 +1,287 @@
// HammerRuleCompiler.m
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import "HammerBlockRuleVisitor.h"
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
#import "HammerRuleCompilerVisitor.h"
#import "Auspicion.h"
#import "Hammer.h"
#import "ARXModule+RuntimeTypeEncodings.h"
@implementation HammerRuleCompiler
@synthesize module;
+(id)compiler {
return [[self alloc] init];
}
-(id)init {
if(self = [super init]) {
context = [[ARXContext context] retain];
module = [[ARXModule moduleWithName: @"HammerRuleCompilerModule" inContext: context] retain];
printer = [[HammerRulePrinter alloc] init];
ARXModuleImportType(module, HammerIndex);
ARXModuleImportType(module, CFIndex);
[module setType: context.int1Type forName: @"Boolean"];
ARXModuleImportType(module, UniChar);
CFCharacterSetRef characterSet = NULL;
CFStringRef string = NULL;
[module setObjCType: @encode(__typeof__(characterSet)) forName: @"CFCharacterSetRef"];
[module setObjCType: @encode(__typeof__(string)) forName: @"CFStringRef"];
ARXStructureType *rangeType = (ARXStructureType *)ARXModuleImportType(module, NSRange);
[rangeType declareElementNames: [NSArray arrayWithObjects:
@"location",
@"length",
nil]];
ARXModuleImportType(module, HammerRuleRef);
ARXModuleImportType(module, HammerSequenceRef);
ARXModuleImportType(module, HammerMatchRef);
ARXModuleImportType(module, NSString *);
ARXStructureType *parserStateType = (ARXStructureType *)ARXModuleImportType(module, HammerParserState);
[parserStateType declareElementNames: [NSArray arrayWithObjects:
@"sequence",
@"errorContext",
@"matchContext",
@"ruleGraph",
@"isIgnoringMatches",
nil]];
[module setType: [ARXType pointerTypeToType: parserStateType] forName: @"HammerParserState *"];
ARXFunctionType *lengthOfMatch = [ARXType functionType: context.integerType,
[module typeNamed: @"HammerIndex"],
[module typeNamed: @"HammerParserState *"],
nil];
[lengthOfMatch declareArgumentNames: [NSArray arrayWithObjects: @"initial", @"state", nil]];
[module setType: lengthOfMatch forName: @"lengthOfMatch"];
ARXFunctionType *rangeOfMatch = [ARXType functionType: context.int1Type,
[ARXType pointerTypeToType: [module typeNamed: @"NSRange"]],
[module typeNamed: @"HammerIndex"],
[module typeNamed: @"HammerParserState *"],
nil];
[rangeOfMatch declareArgumentNames: [NSArray arrayWithObjects: @"outrange", @"initial", @"state", nil]];
[module setType: rangeOfMatch forName: @"rangeOfMatch"];
}
return self;
}
-(HammerRuleRef)compileRule:(HammerRuleRef)rule {
HammerBuiltRuleFunctions *builtFunctions = nil;
ARXFunction *initializer = nil;
@try {
HammerBlockRuleVisitor *ruleVisitor = [[HammerBlockRuleVisitor alloc] init];
[ruleVisitor visitRule: rule withVisitBlock: ^(HammerRuleRef rule, NSString *shortName) {
SEL declarator = NSSelectorFromString([NSString stringWithFormat: @"declareGlobalDataFor%@:", shortName]);
if([self respondsToSelector: declarator]) {
[self performSelector: declarator withObject: rule];
}
}];
initializer = [module functionWithName: [NSString stringWithFormat: @"%@ initialize", [self nameForRule: rule]] type: [ARXType functionType: context.voidType, nil] definition: ^(ARXFunctionBuilder *function){
[ruleVisitor visitRule: rule withVisitBlock: ^(HammerRuleRef rule, NSString *shortName) {
SEL selector = NSSelectorFromString([NSString stringWithFormat: @"initializeDataFor%@:", shortName]);
if([self respondsToSelector: selector]) {
[self performSelector: selector withObject: rule];
}
}];
[function return];
}];
HammerRuleCompilerVisitor *visitor = [[HammerRuleCompilerVisitor alloc] initWithCompiler: self];
builtFunctions = HammerRuleAcceptVisitor(rule, visitor);
}
@catch(NSException *exception) {
NSLog(@"%@", [[exception callStackSymbols] componentsJoinedByString: @"\n"]);
@throw exception;
}
NSError *error = nil;
if(![module verifyWithError: &error]) {
- LLVMDumpModule([module moduleRef]);
+ // LLVMDumpModule([module moduleRef]);
NSLog(@"Error in module: %@", error.localizedDescription);
return nil;
}
ARXCompiler *compiler = [ARXCompiler compilerWithContext: context];
[compiler addModule: module];
ARXOptimizer *optimizer = [ARXOptimizer optimizerWithCompiler: compiler];
[optimizer addConstantPropagationPass];
[optimizer addInstructionCombiningPass];
[optimizer addPromoteMemoryToRegisterPass];
// [optimizer addGVNPass];
- // [optimizer addCFGSimplificationPass];
+ [optimizer addCFGSimplificationPass];
[optimizer optimizeModule: module];
+
void (*initialize)() = [compiler compiledFunction: initializer];
initialize();
+
HammerCompiledRuleRef compiledRule = HammerCompiledRuleCreate(rule, [compiler compiledFunction: builtFunctions.lengthOfMatch], [compiler compiledFunction: builtFunctions.rangeOfMatch]);
return compiledRule;
}
-(NSString *)nameForRule:(HammerRuleRef)rule {
return [NSString stringWithFormat: @"%s(%@)", RXObjectTypeGetName(RXGetType(rule)), [printer printRule: rule]];
}
-(ARXFunction *)lengthOfIgnorableCharactersFunction {
return [module externalFunctionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"], nil]];
/*
return [module functionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"], nil] definition: ^(ARXFunctionBuilder *function) {
ARXPointerValue
*length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]],
*ignorableRule = [function allocateVariableOfType: [module typeNamed: @"HammerRuleRef"] value: [[self ruleGraphGetRuleForNameFunction] call: ((ARXPointerValue *)[function argumentNamed: @"state"]).value elementNamed: @"ruleGraph"]];
}];
*/
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule {
return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:", (NSString *)HammerRuleGetShortTypeName(rule)]) withObject: rule];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrule:(ARXFunction *)subrule {
return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrule:", (NSString *)HammerRuleGetShortTypeName(rule), subrule]) withObject: rule withObject: subrule];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrules:", (NSString *)HammerRuleGetShortTypeName(rule), subrules]) withObject: rule withObject: subrules];
}
-(ARXModuleFunctionDefinitionBlock)rangeOfMatchSkippingIgnorableCharactersDefinitionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(ARXFunction *)lengthOfMatch {
return [^(ARXFunctionBuilder *function) {
ARXPointerValue
*length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]],
*ignorable = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]];
[[length.value equals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
ignorable.value = [[self lengthOfIgnorableCharactersFunction] call: [function argumentNamed: @"state"], [function argumentNamed: @"initial"]];
[[ignorable.value notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
length.value = [lengthOfMatch call: [[function argumentNamed: @"initial"] plus: ignorable.value], [function argumentNamed: @"state"]];
}];
}];
[function structureArgumentNamed: @"outrange"].elements = [NSArray arrayWithObjects:
[[function argumentNamed: @"initial"] plus: [[ignorable.value equals: [context constantUnsignedInteger: NSNotFound]] select: [context constantUnsignedInteger: 0] or: ignorable.value]],
length.value,
nil];
[function return: [length.value notEquals: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForAlternationRule:(HammerAlternationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
return [^(ARXFunctionBuilder *function) {
ARXPointerValue *length = [function allocateVariableOfType: context.integerType value: [context constantUnsignedInteger: NSNotFound]];
ARXBlock *returnBlock = [function addBlockWithName: @"return"];
for(HammerBuiltRuleFunctions *subrule in subrules) {
[[(length.value = [subrule.lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]) notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
[function goto: returnBlock];
}];
}
[function goto: returnBlock];
[returnBlock define: ^{
[function return: length.value];
}];
} copy];
}
-(ARXModuleFunctionDefinitionBlock)rangeOfMatchFunctionForAlternationRule:(HammerAlternationRuleRef)rule {
NSLog(@"type of a function: %s", @encode(HammerRuleLengthOfMatchMethod));
return nil;
}
-(ARXFunction *)sequenceGetLengthFunction {
return [module externalFunctionWithName: @"HammerSequenceGetLength" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerSequenceRef"], nil]];
}
--(ARXModuleFunctionDefinitionBlock)lengthOfMatchFunctionForCharacterRule:(HammerCharacterRuleRef)rule {
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForCharacterRule:(HammerCharacterRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
- [[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction
- call: [[function pointerArgumentNamed: @"state"].structureValue elementNamed: @"sequence"]]]
+ [function return: [[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction
+ call: [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"]]]
select: [context constantUnsignedInteger: 1]
- or: [context constantUnsignedInteger: NSNotFound]];
+ or: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
-(ARXFunction *)characterIsMemberFunction {
return [module externalFunctionWithName: @"CFCharacterSetIsCharacterMember" type: [ARXType functionType: [module typeNamed: @"Boolean"], [module typeNamed: @"CFCharacterSetRef"], [module typeNamed: @"UniChar"], nil]];
}
-(ARXFunction *)getCharacterAtIndexFunction {
return [module externalFunctionWithName: @"CFStringGetCharacterAtIndex" type: [ARXType functionType: [module typeNamed: @"UniChar"], [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"CFIndex"], nil]];
}
-(ARXFunction *)sequenceGetStringFunction {
return [module externalFunctionWithName: @"HammerSequenceGetString" type: [ARXType functionType: [module typeNamed: @"CFStringRef"], [module typeNamed: @"HammerSequenceRef"], nil]];
}
-(void)declareGlobalDataForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
[module declareGlobalOfType: [module typeNamed: @"CFCharacterSetRef"] forName: [self nameForRule: rule]];
}
-(void)initializeDataForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
// fixme: constant pointers are only viable for JIT
// fixme: actually call the initializers from a function
[module setGlobal: [context constantPointer: (void *)HammerCharacterSetRuleGetCharacterSet(rule) ofType: [module typeNamed: @"CFCharacterSetRef"]] forName: [self nameForRule: rule]];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
ARXValue *sequence = [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"];
[function return: [[[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction call: sequence]]
and: [self.characterIsMemberFunction call: [module globalNamed: [self nameForRule: rule]], [self.getCharacterAtIndexFunction call: [self.sequenceGetStringFunction call: sequence], [function argumentNamed: @"initial"], nil], nil]
] select: [context constantUnsignedInteger: 1]
or: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
// -(ARXModuleFunctionDefinitionBlock)rangeOfMatchDefinitionForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
//
// }
-(ARXFunction *)sequenceContainsSequenceAtIndexFunction {
return [module externalFunctionWithName: @"HammerSequenceContainsSequenceAtIndex" type: [ARXType functionType: context.int1Type, [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"HammerIndex"], nil]];
}
-(void)declareGlobalDataForLiteralRule:(HammerLiteralRuleRef)rule {
[module declareGlobalOfType: [module typeNamed: @"HammerSequenceRef"] forName: [self nameForRule: rule]];
}
-(void)initializeDataForLiteralRule:(HammerLiteralRuleRef)rule {
// fixme: constant pointers are only viable for JIT
// fixme: actually call the initializers from a function
[module setGlobal: [context constantPointer: (void *)HammerLiteralRuleGetSequence(rule) ofType: [module typeNamed: @"HammerSequenceRef"]] forName: [self nameForRule: rule]];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForLiteralRule:(HammerLiteralRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
ARXValue *sequence = [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"];
[function return: [[[self.sequenceContainsSequenceAtIndexFunction call: sequence, [module globalNamed: [self nameForRule: rule]], [function argumentNamed: @"initial"]] toBoolean]
select: [context constantUnsignedInteger: HammerSequenceGetLength(HammerLiteralRuleGetSequence(rule))]
or: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
@end
|
robrix/hammerc
|
a5fbbe146ed36048b8848aa01b0bcdf7a9da2616
|
Compilation now succeeds! Now if only it wouldnât crash on the first test.
|
diff --git a/Classes/HammerBlockRuleVisitor.h b/Classes/HammerBlockRuleVisitor.h
new file mode 100644
index 0000000..84033b1
--- /dev/null
+++ b/Classes/HammerBlockRuleVisitor.h
@@ -0,0 +1,21 @@
+// HammerBlockRuleVisitor.h
+// Created by Rob Rix on 2010-06-14
+// Copyright 2010 Monochrome Industries
+
+#import <Foundation/Foundation.h>
+
+typedef void (^HammerBlockRuleVisitorVisitBlock)(HammerRuleRef rule, NSString *shortName);
+typedef id (^HammerBlockRuleVisitorNullaryLeaveBlock)(HammerRuleRef rule, NSString *shortName);
+typedef id (^HammerBlockRuleVisitorUnaryLeaveBlock)(HammerRuleRef rule, id subrule, NSString *shortName);
+typedef id (^HammerBlockRuleVisitorNAryLeaveBlock)(HammerRuleRef rule, NSArray *subrules, NSString *shortName);
+
+@interface HammerBlockRuleVisitor : NSObject {
+ HammerBlockRuleVisitorVisitBlock visit;
+ HammerBlockRuleVisitorNullaryLeaveBlock leave;
+ HammerBlockRuleVisitorUnaryLeaveBlock leaveUnary;
+ HammerBlockRuleVisitorNAryLeaveBlock leaveNAry;
+}
+
+-(void)visitRule:(HammerRuleRef)rule withVisitBlock:(HammerBlockRuleVisitorVisitBlock)block;
+
+@end
diff --git a/Classes/HammerBlockRuleVisitor.m b/Classes/HammerBlockRuleVisitor.m
new file mode 100644
index 0000000..8732382
--- /dev/null
+++ b/Classes/HammerBlockRuleVisitor.m
@@ -0,0 +1,45 @@
+// HammerBlockRuleVisitor.m
+// Created by Rob Rix on 2010-06-14
+// Copyright 2010 Monochrome Industries
+
+#import "HammerBlockRuleVisitor.h"
+
+@interface HammerBlockRuleVisitor () <HammerRuleVisitor>
+@end
+
+
+@implementation HammerBlockRuleVisitor
+
+-(void)visitRule:(HammerRuleRef)rule withVisitBlock:(HammerBlockRuleVisitorVisitBlock)block {
+ visit = block;
+ HammerRuleAcceptVisitor(rule, self);
+ visit = NULL;
+}
+
+
+-(void)visitRule:(HammerRuleRef)rule {
+ if(visit) {
+ visit(rule, (NSString *)HammerRuleGetShortTypeName(rule));
+ }
+}
+
+
+-(id)leaveRule:(HammerRuleRef)rule {
+ return leave
+ ? leave(rule, (NSString *)HammerRuleGetShortTypeName(rule))
+ : rule;
+}
+
+-(id)leaveRule:(HammerRuleRef)rule withVisitedSubrule:(id)subrule {
+ return leaveUnary
+ ? leaveUnary(rule, subrule, (NSString *)HammerRuleGetShortTypeName(rule))
+ : rule;
+}
+
+-(id)leaveRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
+ return leaveNAry
+ ? leaveNAry(rule, subrules, (NSString *)HammerRuleGetShortTypeName(rule))
+ : rule;
+}
+
+@end
diff --git a/Classes/HammerRuleCompiler.m b/Classes/HammerRuleCompiler.m
index 46e1b59..c8af658 100644
--- a/Classes/HammerRuleCompiler.m
+++ b/Classes/HammerRuleCompiler.m
@@ -1,260 +1,285 @@
// HammerRuleCompiler.m
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
+#import "HammerBlockRuleVisitor.h"
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
#import "HammerRuleCompilerVisitor.h"
#import "Auspicion.h"
#import "Hammer.h"
#import "ARXModule+RuntimeTypeEncodings.h"
@implementation HammerRuleCompiler
@synthesize module;
+(id)compiler {
return [[self alloc] init];
}
-(id)init {
if(self = [super init]) {
context = [[ARXContext context] retain];
module = [[ARXModule moduleWithName: @"HammerRuleCompilerModule" inContext: context] retain];
printer = [[HammerRulePrinter alloc] init];
ARXModuleImportType(module, HammerIndex);
ARXModuleImportType(module, CFIndex);
[module setType: context.int1Type forName: @"Boolean"];
ARXModuleImportType(module, UniChar);
CFCharacterSetRef characterSet = NULL;
CFStringRef string = NULL;
[module setObjCType: @encode(__typeof__(characterSet)) forName: @"CFCharacterSetRef"];
[module setObjCType: @encode(__typeof__(string)) forName: @"CFStringRef"];
ARXStructureType *rangeType = (ARXStructureType *)ARXModuleImportType(module, NSRange);
[rangeType declareElementNames: [NSArray arrayWithObjects:
@"location",
@"length",
nil]];
ARXModuleImportType(module, HammerRuleRef);
ARXModuleImportType(module, HammerSequenceRef);
ARXModuleImportType(module, HammerMatchRef);
ARXModuleImportType(module, NSString *);
ARXStructureType *parserStateType = (ARXStructureType *)ARXModuleImportType(module, HammerParserState);
[parserStateType declareElementNames: [NSArray arrayWithObjects:
@"sequence",
@"errorContext",
@"matchContext",
@"ruleGraph",
@"isIgnoringMatches",
nil]];
[module setType: [ARXType pointerTypeToType: parserStateType] forName: @"HammerParserState *"];
ARXFunctionType *lengthOfMatch = [ARXType functionType: context.integerType,
[module typeNamed: @"HammerIndex"],
[module typeNamed: @"HammerParserState *"],
nil];
[lengthOfMatch declareArgumentNames: [NSArray arrayWithObjects: @"initial", @"state", nil]];
[module setType: lengthOfMatch forName: @"lengthOfMatch"];
ARXFunctionType *rangeOfMatch = [ARXType functionType: context.int1Type,
[ARXType pointerTypeToType: [module typeNamed: @"NSRange"]],
[module typeNamed: @"HammerIndex"],
[module typeNamed: @"HammerParserState *"],
nil];
[rangeOfMatch declareArgumentNames: [NSArray arrayWithObjects: @"outrange", @"initial", @"state", nil]];
[module setType: rangeOfMatch forName: @"rangeOfMatch"];
}
return self;
}
-(HammerRuleRef)compileRule:(HammerRuleRef)rule {
HammerBuiltRuleFunctions *builtFunctions = nil;
+ ARXFunction *initializer = nil;
@try {
+ HammerBlockRuleVisitor *ruleVisitor = [[HammerBlockRuleVisitor alloc] init];
+
+ [ruleVisitor visitRule: rule withVisitBlock: ^(HammerRuleRef rule, NSString *shortName) {
+ SEL declarator = NSSelectorFromString([NSString stringWithFormat: @"declareGlobalDataFor%@:", shortName]);
+ if([self respondsToSelector: declarator]) {
+ [self performSelector: declarator withObject: rule];
+ }
+ }];
+
+ initializer = [module functionWithName: [NSString stringWithFormat: @"%@ initialize", [self nameForRule: rule]] type: [ARXType functionType: context.voidType, nil] definition: ^(ARXFunctionBuilder *function){
+ [ruleVisitor visitRule: rule withVisitBlock: ^(HammerRuleRef rule, NSString *shortName) {
+ SEL selector = NSSelectorFromString([NSString stringWithFormat: @"initializeDataFor%@:", shortName]);
+ if([self respondsToSelector: selector]) {
+ [self performSelector: selector withObject: rule];
+ }
+ }];
+ [function return];
+ }];
+
HammerRuleCompilerVisitor *visitor = [[HammerRuleCompilerVisitor alloc] initWithCompiler: self];
builtFunctions = HammerRuleAcceptVisitor(rule, visitor);
}
@catch(NSException *exception) {
NSLog(@"%@", [[exception callStackSymbols] componentsJoinedByString: @"\n"]);
@throw exception;
}
NSError *error = nil;
if(![module verifyWithError: &error]) {
- // LLVMDumpModule([module moduleRef]);
+ LLVMDumpModule([module moduleRef]);
NSLog(@"Error in module: %@", error.localizedDescription);
return nil;
}
ARXCompiler *compiler = [ARXCompiler compilerWithContext: context];
[compiler addModule: module];
ARXOptimizer *optimizer = [ARXOptimizer optimizerWithCompiler: compiler];
[optimizer addConstantPropagationPass];
[optimizer addInstructionCombiningPass];
[optimizer addPromoteMemoryToRegisterPass];
// [optimizer addGVNPass];
// [optimizer addCFGSimplificationPass];
[optimizer optimizeModule: module];
-
+ void (*initialize)() = [compiler compiledFunction: initializer];
+ initialize();
HammerCompiledRuleRef compiledRule = HammerCompiledRuleCreate(rule, [compiler compiledFunction: builtFunctions.lengthOfMatch], [compiler compiledFunction: builtFunctions.rangeOfMatch]);
return compiledRule;
}
-(NSString *)nameForRule:(HammerRuleRef)rule {
return [NSString stringWithFormat: @"%s(%@)", RXObjectTypeGetName(RXGetType(rule)), [printer printRule: rule]];
}
-(ARXFunction *)lengthOfIgnorableCharactersFunction {
return [module externalFunctionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"], nil]];
/*
return [module functionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"], nil] definition: ^(ARXFunctionBuilder *function) {
ARXPointerValue
*length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]],
*ignorableRule = [function allocateVariableOfType: [module typeNamed: @"HammerRuleRef"] value: [[self ruleGraphGetRuleForNameFunction] call: ((ARXPointerValue *)[function argumentNamed: @"state"]).value elementNamed: @"ruleGraph"]];
}];
*/
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule {
return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:", (NSString *)HammerRuleGetShortTypeName(rule)]) withObject: rule];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrule:(ARXFunction *)subrule {
return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrule:", (NSString *)HammerRuleGetShortTypeName(rule), subrule]) withObject: rule withObject: subrule];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrules:", (NSString *)HammerRuleGetShortTypeName(rule), subrules]) withObject: rule withObject: subrules];
}
-(ARXModuleFunctionDefinitionBlock)rangeOfMatchSkippingIgnorableCharactersDefinitionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(ARXFunction *)lengthOfMatch {
return [^(ARXFunctionBuilder *function) {
ARXPointerValue
*length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]],
*ignorable = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]];
[[length.value equals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
ignorable.value = [[self lengthOfIgnorableCharactersFunction] call: [function argumentNamed: @"state"], [function argumentNamed: @"initial"]];
[[ignorable.value notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
length.value = [lengthOfMatch call: [[function argumentNamed: @"initial"] plus: ignorable.value], [function argumentNamed: @"state"]];
}];
}];
[function structureArgumentNamed: @"outrange"].elements = [NSArray arrayWithObjects:
[[function argumentNamed: @"initial"] plus: [[ignorable.value equals: [context constantUnsignedInteger: NSNotFound]] select: [context constantUnsignedInteger: 0] or: ignorable.value]],
length.value,
nil];
[function return: [length.value notEquals: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForAlternationRule:(HammerAlternationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
return [^(ARXFunctionBuilder *function) {
ARXPointerValue *length = [function allocateVariableOfType: context.integerType value: [context constantUnsignedInteger: NSNotFound]];
ARXBlock *returnBlock = [function addBlockWithName: @"return"];
for(HammerBuiltRuleFunctions *subrule in subrules) {
[[(length.value = [subrule.lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]) notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
[function goto: returnBlock];
}];
}
[function goto: returnBlock];
[returnBlock define: ^{
[function return: length.value];
}];
} copy];
}
-(ARXModuleFunctionDefinitionBlock)rangeOfMatchFunctionForAlternationRule:(HammerAlternationRuleRef)rule {
NSLog(@"type of a function: %s", @encode(HammerRuleLengthOfMatchMethod));
return nil;
}
-(ARXFunction *)sequenceGetLengthFunction {
return [module externalFunctionWithName: @"HammerSequenceGetLength" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerSequenceRef"], nil]];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchFunctionForCharacterRule:(HammerCharacterRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
[[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction
call: [[function pointerArgumentNamed: @"state"].structureValue elementNamed: @"sequence"]]]
select: [context constantUnsignedInteger: 1]
or: [context constantUnsignedInteger: NSNotFound]];
} copy];
}
-(ARXFunction *)characterIsMemberFunction {
return [module externalFunctionWithName: @"CFCharacterSetIsCharacterMember" type: [ARXType functionType: [module typeNamed: @"Boolean"], [module typeNamed: @"CFCharacterSetRef"], [module typeNamed: @"UniChar"], nil]];
}
-(ARXFunction *)getCharacterAtIndexFunction {
return [module externalFunctionWithName: @"CFStringGetCharacterAtIndex" type: [ARXType functionType: [module typeNamed: @"UniChar"], [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"CFIndex"], nil]];
}
-(ARXFunction *)sequenceGetStringFunction {
return [module externalFunctionWithName: @"HammerSequenceGetString" type: [ARXType functionType: [module typeNamed: @"CFStringRef"], [module typeNamed: @"HammerSequenceRef"], nil]];
}
+-(void)declareGlobalDataForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
+ [module declareGlobalOfType: [module typeNamed: @"CFCharacterSetRef"] forName: [self nameForRule: rule]];
+}
+
-(void)initializeDataForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
// fixme: constant pointers are only viable for JIT
// fixme: actually call the initializers from a function
- [module initializeGlobal: [context constantPointer: (void *)HammerCharacterSetRuleGetCharacterSet(rule) ofType: [module typeNamed: @"CFCharacterSetRef"]] forName: [self nameForRule: rule]];
+ [module setGlobal: [context constantPointer: (void *)HammerCharacterSetRuleGetCharacterSet(rule) ofType: [module typeNamed: @"CFCharacterSetRef"]] forName: [self nameForRule: rule]];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
- [self initializeDataForCharacterSetRule: rule];
-
ARXValue *sequence = [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"];
[function return: [[[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction call: sequence]]
and: [self.characterIsMemberFunction call: [module globalNamed: [self nameForRule: rule]], [self.getCharacterAtIndexFunction call: [self.sequenceGetStringFunction call: sequence], [function argumentNamed: @"initial"], nil], nil]
] select: [context constantUnsignedInteger: 1]
or: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
// -(ARXModuleFunctionDefinitionBlock)rangeOfMatchDefinitionForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
//
// }
-(ARXFunction *)sequenceContainsSequenceAtIndexFunction {
return [module externalFunctionWithName: @"HammerSequenceContainsSequenceAtIndex" type: [ARXType functionType: context.int1Type, [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"HammerIndex"], nil]];
}
+-(void)declareGlobalDataForLiteralRule:(HammerLiteralRuleRef)rule {
+ [module declareGlobalOfType: [module typeNamed: @"HammerSequenceRef"] forName: [self nameForRule: rule]];
+}
+
-(void)initializeDataForLiteralRule:(HammerLiteralRuleRef)rule {
// fixme: constant pointers are only viable for JIT
// fixme: actually call the initializers from a function
- [module initializeGlobal: [context constantPointer: (void *)HammerLiteralRuleGetSequence(rule) ofType: [module typeNamed: @"HammerSequenceRef"]] forName: [self nameForRule: rule]];
+ [module setGlobal: [context constantPointer: (void *)HammerLiteralRuleGetSequence(rule) ofType: [module typeNamed: @"HammerSequenceRef"]] forName: [self nameForRule: rule]];
}
-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForLiteralRule:(HammerLiteralRuleRef)rule {
return [^(ARXFunctionBuilder *function) {
- [self initializeDataForLiteralRule: rule];
-
ARXValue *sequence = [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"];
[function return: [[[self.sequenceContainsSequenceAtIndexFunction call: sequence, [module globalNamed: [self nameForRule: rule]], [function argumentNamed: @"initial"]] toBoolean]
select: [context constantUnsignedInteger: HammerSequenceGetLength(HammerLiteralRuleGetSequence(rule))]
or: [context constantUnsignedInteger: NSNotFound]]];
} copy];
}
-
@end
diff --git a/Classes/HammerRuleCompilerVisitor.h b/Classes/HammerRuleCompilerVisitor.h
index 5fc1e50..d632049 100644
--- a/Classes/HammerRuleCompilerVisitor.h
+++ b/Classes/HammerRuleCompilerVisitor.h
@@ -1,15 +1,15 @@
// HammerRuleCompilerVisitor.h
// Created by Rob Rix on 2010-06-12
// Copyright 2010 Monochrome Industries
#import <Foundation/Foundation.h>
-@class HammerRuleCompiler, HammerRulePrinter;
+@class HammerRuleCompiler;
@interface HammerRuleCompilerVisitor : NSObject <HammerRuleVisitor> {
HammerRuleCompiler *compiler;
}
-(id)initWithCompiler:(HammerRuleCompiler *)_compiler;
@end
diff --git a/External/Auspicion b/External/Auspicion
index d18afcd..831e37a 160000
--- a/External/Auspicion
+++ b/External/Auspicion
@@ -1 +1 @@
-Subproject commit d18afcd7f058886d5a94a0a70eed51295cb906e9
+Subproject commit 831e37a6ae58712217f582f1132d0e01c13f752c
diff --git a/Tasks.taskpaper b/Tasks.taskpaper
index 7d855fc..108d8de 100644
--- a/Tasks.taskpaper
+++ b/Tasks.taskpaper
@@ -1,18 +1,17 @@
Compiler:
- write a parser for `@encode()` directive strings. @done(2010-06-14)
- provide JIT-compiled implementations of the match methods for rules, written in Auspicion. Use those in Hammer, and use them in hammerc as the components of the static compilation.
Is that even possible, i.e. resolving function calls and replacing them with static ones?
- inline everything.
- compile the rule graph rather than just individual rules.
- replace reference rules with the (compiled) rules they reference.
- build functions for the clients to call:
- rule graph (parser) initialization
- calls -initializeDataFor<rule>: on each rule
- parse
- free
- frees the globals created in -initializeDataFor<rule>:.
-
Tools:
- Xcode plugin with a build rule for .grammar files.
- header generator.
- Generation Gap builder scaffold tool (like mogenerator but based on a grammar).
diff --git a/hammerc.xcodeproj/project.pbxproj b/hammerc.xcodeproj/project.pbxproj
index a51d771..03ac387 100644
--- a/hammerc.xcodeproj/project.pbxproj
+++ b/hammerc.xcodeproj/project.pbxproj
@@ -1,1073 +1,1083 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 45;
objects = {
/* Begin PBXBuildFile section */
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859EA3029092ED04C91782 /* hammerc.1 */; };
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */; };
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */; };
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */; };
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */; };
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */; };
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */; };
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */; };
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */; };
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */; };
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */; };
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */; };
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E51113F5FEF0086F21C /* hammerc.m */; };
D4551E82113F85830086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EBA113F88300086F21C /* bootstrap-hammerc.m */; };
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551EE3113F88700086F21C /* digit.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC3113F88700086F21C /* digit.grammar */; };
D4551EE4113F88700086F21C /* letter.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC4113F88700086F21C /* letter.grammar */; };
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */; };
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC7113F88700086F21C /* HammerBuilderTests.m */; };
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */; };
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */; };
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */; };
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */; };
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */; };
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */; };
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */; };
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */; };
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */; };
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */; };
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDE113F88700086F21C /* HammerRuleTests.m */; };
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */; };
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EF7113F88A00086F21C /* Hammer.grammar */; };
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D48B23EB11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
D48B23EC11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
D48B23ED11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
D48B23EE11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B24BC11B25720007CBBB4 /* RXAssertions.m */; };
D4D74F1511C38023002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F1611C38031002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F1711C38034002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F2411C3817B002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
D4D74F2511C38195002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
D4D74F2611C38196002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
D4D74F3011C38209002FF2F1 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
D4D74F3111C3820E002FF2F1 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
D4D750E211C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
D4D750E311C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
D4D750FF11C3D8E8002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
+ D4D753B211C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */; };
+ D4D753B311C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */; };
+ D4D753B411C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D4551DFE113E48B20086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
proxyType = 1;
remoteGlobalIDString = D4551DF9113E48A90086F21C;
remoteInfo = "bootstrap-hammerc";
};
D4551E7A113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4041AB1113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D4551E7E113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4DB11D60D138C7400C730A3;
remoteInfo = Tests;
};
D4551E80113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D404EB4610F5791C007612E9;
remoteInfo = "Measure Performance";
};
D4551E9C113F85D70086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D2AAC046055464E500DB518D;
remoteInfo = Polymorph;
};
D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4AB04351180335A0048BBA1;
remoteInfo = Tests;
};
D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D2AAC07E0554694100DB518D;
remoteInfo = RXAssertions;
};
D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D442A488106FD94900944F07;
remoteInfo = Tests;
};
D4D74F0B11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D2AAC07E0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4D74F0D11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4D9DE5510EB5F4F003EEE90;
remoteInfo = AuspicionLLVM;
};
D4D74F0F11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4CF603311C32F8000C9DD15;
remoteInfo = Tests;
};
D4D74F1111C38010002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D2AAC07D0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4D74F1311C3801B002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D2AAC07D0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
8DD76F9E0486AA7600D96B5E /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 8;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
8DD76FA10486AA7600D96B5E /* hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = hammerc; sourceTree = BUILT_PRODUCTS_DIR; };
C6859EA3029092ED04C91782 /* hammerc.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = hammerc.1; sourceTree = "<group>"; };
D4551DFA113E48A90086F21C /* bootstrap-hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "bootstrap-hammerc"; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E28113F5F6D0086F21C /* Tests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Tests.octest; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E29113F5F6D0086F21C /* Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Tests-Info.plist"; sourceTree = "<group>"; };
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledAlternationRuleTests.m; sourceTree = "<group>"; };
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterRuleTests.m; sourceTree = "<group>"; };
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralRuleTests.m; sourceTree = "<group>"; };
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledNamedRuleTests.m; sourceTree = "<group>"; };
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledReferenceRuleTests.m; sourceTree = "<group>"; };
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompilerTests.m; sourceTree = "<group>"; };
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCompiledRule.h; sourceTree = "<group>"; };
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRule.m; sourceTree = "<group>"; };
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleCompiler.h; sourceTree = "<group>"; };
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompiler.m; sourceTree = "<group>"; };
D4551E51113F5FEF0086F21C /* hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = hammerc.m; sourceTree = "<group>"; };
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hammerc_Prefix.pch; sourceTree = "<group>"; };
D4551E6E113F85780086F21C /* Hammer.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Hammer.xcodeproj; sourceTree = "<group>"; };
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "bootstrap-hammerc.m"; sourceTree = "<group>"; };
D4551EC3113F88700086F21C /* digit.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = digit.grammar; sourceTree = "<group>"; };
D4551EC4113F88700086F21C /* letter.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = letter.grammar; sourceTree = "<group>"; };
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerAlternationRuleTests.h; sourceTree = "<group>"; };
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerAlternationRuleTests.m; sourceTree = "<group>"; };
D4551EC7113F88700086F21C /* HammerBuilderTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerBuilderTests.m; sourceTree = "<group>"; };
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterRuleTests.h; sourceTree = "<group>"; };
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterRuleTests.m; sourceTree = "<group>"; };
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterSetRuleTests.h; sourceTree = "<group>"; };
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerContainerRuleTests.m; sourceTree = "<group>"; };
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralRuleTests.h; sourceTree = "<group>"; };
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralRuleTests.m; sourceTree = "<group>"; };
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLookaheadRuleTests.h; sourceTree = "<group>"; };
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerNamedRuleTests.h; sourceTree = "<group>"; };
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerNamedRuleTests.m; sourceTree = "<group>"; };
D4551ED7113F88700086F21C /* HammerParserTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerParserTests.m; sourceTree = "<group>"; };
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerReferenceRuleTests.h; sourceTree = "<group>"; };
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerReferenceRuleTests.m; sourceTree = "<group>"; };
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRepetitionRuleTests.h; sourceTree = "<group>"; };
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRulePrinterTests.m; sourceTree = "<group>"; };
D4551EDD113F88700086F21C /* HammerRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleTests.h; sourceTree = "<group>"; };
D4551EDE113F88700086F21C /* HammerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleTests.m; sourceTree = "<group>"; };
D4551EDF113F88700086F21C /* HammerTestParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestParser.h; sourceTree = "<group>"; };
D4551EE0113F88700086F21C /* HammerTestParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestParser.m; sourceTree = "<group>"; };
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestRuleVisitor.h; sourceTree = "<group>"; };
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestRuleVisitor.m; sourceTree = "<group>"; };
D4551EF7113F88A00086F21C /* Hammer.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = Hammer.grammar; path = "../Other Sources/Hammer.grammar"; sourceTree = "<group>"; };
D48B23E711B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARXModule+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "ARXModule+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
D48B23E911B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARXType+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "ARXType+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
D48B247911B25720007CBBB4 /* RXAllocation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAllocation.h; sourceTree = "<group>"; };
D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXCoreFoundationIntegration.h; sourceTree = "<group>"; };
D48B247D11B25720007CBBB4 /* RXObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObject.h; sourceTree = "<group>"; };
D48B248011B25720007CBBB4 /* RXObjectType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObjectType.h; sourceTree = "<group>"; };
D48B248111B25720007CBBB4 /* RXShadowObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXShadowObject.h; sourceTree = "<group>"; };
D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Polymorph.xcodeproj; sourceTree = "<group>"; };
D48B24BB11B25720007CBBB4 /* RXAssertions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAssertions.h; sourceTree = "<group>"; };
D48B24BC11B25720007CBBB4 /* RXAssertions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RXAssertions.m; sourceTree = "<group>"; };
D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = RXAssertions.xcodeproj; sourceTree = "<group>"; };
D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Auspicion.xcodeproj; sourceTree = "<group>"; };
D4D74F2211C3817B002FF2F1 /* NSObject+UniqueFactory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSObject+UniqueFactory.h"; path = "Classes/NSObject+UniqueFactory.h"; sourceTree = "<group>"; };
D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSObject+UniqueFactory.m"; path = "Classes/NSObject+UniqueFactory.m"; sourceTree = "<group>"; };
D4D750E011C3BE90002FF2F1 /* HammerRuleCompilerVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleCompilerVisitor.h; sourceTree = "<group>"; };
D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompilerVisitor.m; sourceTree = "<group>"; };
+ D4D753B011C670DC002FF2F1 /* HammerBlockRuleVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerBlockRuleVisitor.h; sourceTree = "<group>"; };
+ D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerBlockRuleVisitor.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
8DD76F9B0486AA7600D96B5E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1611C38031002FF2F1 /* libAuspicion.a in Frameworks */,
D4551E82113F85830086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF8113E48A90086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1711C38034002FF2F1 /* libAuspicion.a in Frameworks */,
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E25113F5F6D0086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1511C38023002FF2F1 /* libAuspicion.a in Frameworks */,
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
08FB7794FE84155DC02AAC07 /* hammerc */ = {
isa = PBXGroup;
children = (
D48B23E611B24D5E007CBBB4 /* Categories */,
08FB7795FE84155DC02AAC07 /* Classes */,
D4551E50113F5FEF0086F21C /* Other Sources */,
D4551E30113F5FB10086F21C /* Tests */,
C6859EA2029092E104C91782 /* Documentation */,
D4551E6B113F85410086F21C /* External */,
D4551E2F113F5F7D0086F21C /* Resources */,
1AB674ADFE9D54B511CA2CBB /* Products */,
);
name = hammerc;
sourceTree = "<group>";
};
08FB7795FE84155DC02AAC07 /* Classes */ = {
isa = PBXGroup;
children = (
+ D4D753B011C670DC002FF2F1 /* HammerBlockRuleVisitor.h */,
+ D4D753B111C670DC002FF2F1 /* HammerBlockRuleVisitor.m */,
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */,
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */,
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */,
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */,
D4D750E011C3BE90002FF2F1 /* HammerRuleCompilerVisitor.h */,
D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */,
);
path = Classes;
sourceTree = "<group>";
};
1AB674ADFE9D54B511CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
8DD76FA10486AA7600D96B5E /* hammerc */,
D4551DFA113E48A90086F21C /* bootstrap-hammerc */,
D4551E28113F5F6D0086F21C /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
C6859EA2029092E104C91782 /* Documentation */ = {
isa = PBXGroup;
children = (
C6859EA3029092ED04C91782 /* hammerc.1 */,
);
path = Documentation;
sourceTree = "<group>";
};
D4551E2F113F5F7D0086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551E29113F5F6D0086F21C /* Tests-Info.plist */,
);
path = Resources;
sourceTree = "<group>";
};
D4551E30113F5FB10086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */,
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */,
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */,
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */,
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */,
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */,
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */,
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */,
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */,
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */,
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551E50113F5FEF0086F21C /* Other Sources */ = {
isa = PBXGroup;
children = (
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */,
D4551E51113F5FEF0086F21C /* hammerc.m */,
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */,
);
path = "Other Sources";
sourceTree = "<group>";
};
D4551E6B113F85410086F21C /* External */ = {
isa = PBXGroup;
children = (
D4551E6D113F855E0086F21C /* Auspicion */,
D4551E6C113F85530086F21C /* Hammer */,
);
path = External;
sourceTree = "<group>";
};
D4551E6C113F85530086F21C /* Hammer */ = {
isa = PBXGroup;
children = (
D4551E6E113F85780086F21C /* Hammer.xcodeproj */,
D48B244C11B25720007CBBB4 /* External */,
D4551EF6113F88930086F21C /* Resources */,
D4551EC1113F88700086F21C /* Tests */,
);
path = Hammer;
sourceTree = "<group>";
};
D4551E6D113F855E0086F21C /* Auspicion */ = {
isa = PBXGroup;
children = (
D4D74F2211C3817B002FF2F1 /* NSObject+UniqueFactory.h */,
D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */,
D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */,
);
path = Auspicion;
sourceTree = "<group>";
};
D4551E6F113F85780086F21C /* Products */ = {
isa = PBXGroup;
children = (
D4551E7B113F85780086F21C /* libHammer.a */,
D4551E7F113F85780086F21C /* Tests.octest */,
D4551E81113F85780086F21C /* Measure Performance */,
);
name = Products;
sourceTree = "<group>";
};
D4551EC1113F88700086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551EC2113F88700086F21C /* Fixtures */,
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */,
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */,
D4551EC7113F88700086F21C /* HammerBuilderTests.m */,
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */,
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */,
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */,
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */,
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */,
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */,
D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */,
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */,
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */,
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */,
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */,
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */,
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */,
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */,
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */,
D4551ED7113F88700086F21C /* HammerParserTests.m */,
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */,
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */,
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */,
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */,
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */,
D4551EDD113F88700086F21C /* HammerRuleTests.h */,
D4551EDE113F88700086F21C /* HammerRuleTests.m */,
D4551EDF113F88700086F21C /* HammerTestParser.h */,
D4551EE0113F88700086F21C /* HammerTestParser.m */,
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */,
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551EC2113F88700086F21C /* Fixtures */ = {
isa = PBXGroup;
children = (
D4551EC3113F88700086F21C /* digit.grammar */,
D4551EC4113F88700086F21C /* letter.grammar */,
);
path = Fixtures;
sourceTree = "<group>";
};
D4551EF6113F88930086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551EF7113F88A00086F21C /* Hammer.grammar */,
);
path = Resources;
sourceTree = "<group>";
};
D48B23E611B24D5E007CBBB4 /* Categories */ = {
isa = PBXGroup;
children = (
D48B23E711B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.h */,
D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */,
D48B23E911B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.h */,
D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */,
);
path = Categories;
sourceTree = "<group>";
};
D48B244C11B25720007CBBB4 /* External */ = {
isa = PBXGroup;
children = (
D48B244D11B25720007CBBB4 /* Polymorph */,
D48B249111B25720007CBBB4 /* RXAssertions */,
);
path = External;
sourceTree = "<group>";
};
D48B244D11B25720007CBBB4 /* Polymorph */ = {
isa = PBXGroup;
children = (
D48B247811B25720007CBBB4 /* Classes */,
D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */,
);
path = Polymorph;
sourceTree = "<group>";
};
D48B247811B25720007CBBB4 /* Classes */ = {
isa = PBXGroup;
children = (
D48B247911B25720007CBBB4 /* RXAllocation.h */,
D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */,
D48B247D11B25720007CBBB4 /* RXObject.h */,
D48B248011B25720007CBBB4 /* RXObjectType.h */,
D48B248111B25720007CBBB4 /* RXShadowObject.h */,
);
path = Classes;
sourceTree = "<group>";
};
D48B248B11B25720007CBBB4 /* Products */ = {
isa = PBXGroup;
children = (
D48B24E211B25721007CBBB4 /* libPolymorph.a */,
D48B24E411B25721007CBBB4 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
D48B249111B25720007CBBB4 /* RXAssertions */ = {
isa = PBXGroup;
children = (
D48B24BB11B25720007CBBB4 /* RXAssertions.h */,
D48B24BC11B25720007CBBB4 /* RXAssertions.m */,
D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */,
);
path = RXAssertions;
sourceTree = "<group>";
};
D48B24BF11B25720007CBBB4 /* Products */ = {
isa = PBXGroup;
children = (
D48B24EB11B25721007CBBB4 /* libRXAssertions.a */,
D48B24ED11B25721007CBBB4 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
D4D74F0611C37FFC002FF2F1 /* Products */ = {
isa = PBXGroup;
children = (
D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */,
D4D74F0E11C37FFC002FF2F1 /* libAuspicionLLVM.a */,
D4D74F1011C37FFC002FF2F1 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
8DD76F960486AA7600D96B5E /* hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */;
buildPhases = (
8DD76F990486AA7600D96B5E /* Sources */,
8DD76F9B0486AA7600D96B5E /* Frameworks */,
8DD76F9E0486AA7600D96B5E /* CopyFiles */,
);
buildRules = (
);
dependencies = (
D4551DFF113E48B20086F21C /* PBXTargetDependency */,
);
name = hammerc;
productInstallPath = "$(HOME)/bin";
productName = hammerc;
productReference = 8DD76FA10486AA7600D96B5E /* hammerc */;
productType = "com.apple.product-type.tool";
};
D4551DF9113E48A90086F21C /* bootstrap-hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */;
buildPhases = (
D4551DF7113E48A90086F21C /* Sources */,
D4551DF8113E48A90086F21C /* Frameworks */,
);
buildRules = (
);
dependencies = (
D4551E9D113F85D70086F21C /* PBXTargetDependency */,
D4D74F1211C38010002FF2F1 /* PBXTargetDependency */,
);
name = "bootstrap-hammerc";
productName = "bootstrap-hammerc";
productReference = D4551DFA113E48A90086F21C /* bootstrap-hammerc */;
productType = "com.apple.product-type.tool";
};
D4551E27113F5F6D0086F21C /* Tests */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */;
buildPhases = (
D4551E24113F5F6D0086F21C /* Sources */,
D4551E23113F5F6D0086F21C /* Resources */,
D4551E25113F5F6D0086F21C /* Frameworks */,
D4551E26113F5F6D0086F21C /* ShellScript */,
);
buildRules = (
);
dependencies = (
D4551F00113F88CA0086F21C /* PBXTargetDependency */,
D4D74F1411C3801B002FF2F1 /* PBXTargetDependency */,
);
name = Tests;
productName = Tests;
productReference = D4551E28113F5F6D0086F21C /* Tests.octest */;
productType = "com.apple.product-type.bundle";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
08FB7793FE84155DC02AAC07 /* Project object */ = {
isa = PBXProject;
buildConfigurationList = 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */;
compatibilityVersion = "Xcode 3.1";
hasScannedForEncodings = 1;
mainGroup = 08FB7794FE84155DC02AAC07 /* hammerc */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = D4D74F0611C37FFC002FF2F1 /* Products */;
ProjectRef = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
},
{
ProductGroup = D4551E6F113F85780086F21C /* Products */;
ProjectRef = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
},
{
ProductGroup = D48B248B11B25720007CBBB4 /* Products */;
ProjectRef = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
},
{
ProductGroup = D48B24BF11B25720007CBBB4 /* Products */;
ProjectRef = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
},
);
projectRoot = "";
targets = (
8DD76F960486AA7600D96B5E /* hammerc */,
D4551DF9113E48A90086F21C /* bootstrap-hammerc */,
D4551E27113F5F6D0086F21C /* Tests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
D4551E7B113F85780086F21C /* libHammer.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libHammer.a;
remoteRef = D4551E7A113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E7F113F85780086F21C /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D4551E7E113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E81113F85780086F21C /* Measure Performance */ = {
isa = PBXReferenceProxy;
fileType = "compiled.mach-o.executable";
path = "Measure Performance";
remoteRef = D4551E80113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24E211B25721007CBBB4 /* libPolymorph.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libPolymorph.a;
remoteRef = D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24E411B25721007CBBB4 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24EB11B25721007CBBB4 /* libRXAssertions.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRXAssertions.a;
remoteRef = D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24ED11B25721007CBBB4 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libAuspicion.a;
remoteRef = D4D74F0B11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F0E11C37FFC002FF2F1 /* libAuspicionLLVM.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libAuspicionLLVM.a;
remoteRef = D4D74F0D11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F1011C37FFC002FF2F1 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D4D74F0F11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
D4551E23113F5F6D0086F21C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551EE3113F88700086F21C /* digit.grammar in Resources */,
D4551EE4113F88700086F21C /* letter.grammar in Resources */,
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
D4551E26113F5F6D0086F21C /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
8DD76F990486AA7600D96B5E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */,
D48B23ED11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
D48B23EE11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */,
D4D74F2611C38196002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
D4D750E311C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
+ D4D753B311C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF7113E48A90086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */,
D48B23EB11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
D48B23EC11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */,
D4D74F2511C38195002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
D4D750E211C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
+ D4D753B211C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E24113F5F6D0086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */,
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */,
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */,
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */,
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */,
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */,
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */,
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */,
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */,
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */,
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */,
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */,
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */,
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */,
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */,
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */,
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */,
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */,
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */,
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */,
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */,
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */,
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */,
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */,
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */,
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */,
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */,
D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */,
D4D74F2411C3817B002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
D4D74F3011C38209002FF2F1 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
D4D74F3111C3820E002FF2F1 /* ARXType+RuntimeTypeEncodings.m in Sources */,
D4D750FF11C3D8E8002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
+ D4D753B411C670DC002FF2F1 /* HammerBlockRuleVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D4551DFF113E48B20086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D4551DF9113E48A90086F21C /* bootstrap-hammerc */;
targetProxy = D4551DFE113E48B20086F21C /* PBXContainerItemProxy */;
};
D4551E9D113F85D70086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551E9C113F85D70086F21C /* PBXContainerItemProxy */;
};
D4551F00113F88CA0086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */;
};
D4D74F1211C38010002FF2F1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
targetProxy = D4D74F1111C38010002FF2F1 /* PBXContainerItemProxy */;
};
D4D74F1411C3801B002FF2F1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
targetProxy = D4D74F1311C3801B002FF2F1 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
1DEB927508733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_FIX_AND_CONTINUE = YES;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Debug;
};
1DEB927608733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_MODEL_TUNING = G5;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Release;
};
1DEB927908733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_GC = required;
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "External/Include/**";
ONLY_ACTIVE_ARCH = YES;
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = macosx10.6;
};
name = Debug;
};
1DEB927A08733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_GC = required;
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "External/Include/**";
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = macosx10.5;
};
name = Release;
};
D4551DFC113E48A90086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
};
name = Debug;
};
D4551DFD113E48A90086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_MODEL_TUNING = G5;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
};
name = Release;
};
D4551E2A113F5F6D0086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
FRAMEWORK_SEARCH_PATHS = "$(DEVELOPER_LIBRARY_DIR)/Frameworks";
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_MODEL_TUNING = G5;
GCC_OPTIMIZATION_LEVEL = 0;
INFOPLIST_FILE = "Resources/Tests-Info.plist";
INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles";
OTHER_CFLAGS = "-DHAMMERC_UNIT_TESTS";
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-framework",
SenTestingKit,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = Tests;
WRAPPER_EXTENSION = octest;
};
name = Debug;
};
D4551E2B113F5F6D0086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = "$(DEVELOPER_LIBRARY_DIR)/Frameworks";
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_MODEL_TUNING = G5;
INFOPLIST_FILE = "Resources/Tests-Info.plist";
INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles";
OTHER_CFLAGS = "-DHAMMERC_UNIT_TESTS";
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-framework",
SenTestingKit,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = Tests;
WRAPPER_EXTENSION = octest;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB927508733DD40010E9CD /* Debug */,
1DEB927608733DD40010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB927908733DD40010E9CD /* Debug */,
1DEB927A08733DD40010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D4551DFC113E48A90086F21C /* Debug */,
D4551DFD113E48A90086F21C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D4551E2A113F5F6D0086F21C /* Debug */,
D4551E2B113F5F6D0086F21C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
}
|
robrix/hammerc
|
47521f6d0d6ca7723d592c45737c7778e591c061
|
Compilation for HammerCompiledAlternationRuleTests now works up until it attempts to load the literal ruleâs sequence.
|
diff --git a/Categories/ARXModule+RuntimeTypeEncodings.h b/Categories/ARXModule+RuntimeTypeEncodings.h
new file mode 100644
index 0000000..df2f2f2
--- /dev/null
+++ b/Categories/ARXModule+RuntimeTypeEncodings.h
@@ -0,0 +1,13 @@
+// ARXModule+RuntimeTypeEncodings.h
+// Created by Rob Rix on 2010-05-30
+// Copyright 2010 Monochrome Industries
+
+#import <Auspicion/Auspicion.h>
+
+#define ARXModuleImportType(module, type) [module setObjCType: @encode(type) forName: @#type]
+
+@interface ARXModule (ARXModuleRuntimeTypeEncodings)
+
+-(ARXType *)setObjCType:(const char *)type forName:(NSString *)name;
+
+@end
diff --git a/Categories/ARXModule+RuntimeTypeEncodings.m b/Categories/ARXModule+RuntimeTypeEncodings.m
new file mode 100644
index 0000000..375cda2
--- /dev/null
+++ b/Categories/ARXModule+RuntimeTypeEncodings.m
@@ -0,0 +1,16 @@
+// ARXModule+RuntimeTypeEncodings.m
+// Created by Rob Rix on 2010-05-30
+// Copyright 2010 Monochrome Industries
+
+#import "ARXModule+RuntimeTypeEncodings.h"
+#import "ARXType+RuntimeTypeEncodings.h"
+
+@implementation ARXModule (ARXModuleRuntimeTypeEncodings)
+
+-(ARXType *)setObjCType:(const char *)type forName:(NSString *)name {
+ ARXType *result = [ARXType typeForObjCType: type inModule: self];
+ [self setType: result forName: name];
+ return result;
+}
+
+@end
diff --git a/Categories/ARXType+RuntimeTypeEncodings.h b/Categories/ARXType+RuntimeTypeEncodings.h
new file mode 100644
index 0000000..d0394aa
--- /dev/null
+++ b/Categories/ARXType+RuntimeTypeEncodings.h
@@ -0,0 +1,11 @@
+// ARXType+RuntimeTypeEncodings.h
+// Created by Rob Rix on 2010-05-30
+// Copyright 2010 Monochrome Industries
+
+#import <Auspicion/Auspicion.h>
+
+@interface ARXType (ARXTypeRuntimeTypeEncodings)
+
++(ARXType *)typeForObjCType:(const char *)type inModule:(ARXModule *)module;
+
+@end
diff --git a/Categories/ARXType+RuntimeTypeEncodings.m b/Categories/ARXType+RuntimeTypeEncodings.m
new file mode 100644
index 0000000..2d5df15
--- /dev/null
+++ b/Categories/ARXType+RuntimeTypeEncodings.m
@@ -0,0 +1,158 @@
+// ARXType+RuntimeTypeEncodings.m
+// Created by Rob Rix on 2010-05-30
+// Copyright 2010 Monochrome Industries
+
+#import "ARXType+RuntimeTypeEncodings.h"
+
+static NSString * const HammerCObjCTypeEncodingGrammar =
+ @"char = [cC];\n"
+ @"short = [sS];\n"
+ @"int = [iI];\n"
+ @"long = [lL];\n"
+ @"longLong = [qQ];\n"
+ @"float = 'f';\n"
+ @"double = 'd';\n"
+ @"bool = 'B';\n"
+ @"void = 'v';\n"
+ @"string = '*';\n"
+ @"object = '@';\n"
+ @"class = '#';\n"
+ @"selector = ':';\n"
+ @"array = '[' (count = [\\d]+) type ']';\n"
+ @"struct = '{' (name = [\\w]+) ('=' type*)? '}';\n"
+ @"union = '(' (name = [\\w]+) ('=' type*)? ')';\n"
+ @"bitfield = 'b' (width = [\\d]+);\n"
+ @"pointer = '^' type;\n"
+ @"unknown = '?';\n"
+ @"typeQualifier = 'r';\n"
+ @"type = typeQualifier? (char | short | int | long | longLong | float | double | bool | void | string | object | class | selector | array | struct | union | bitfield | pointer | unknown);\n"
+ @"main = type+;\n"
+;
+
+@interface HammerCTypeBuilder : NSObject <HammerBuilder> {
+ ARXType *resultType;
+ ARXModule *module;
+ ARXContext *context;
+}
+
+-(ARXType *)typeForObjCType:(const char *)type inModule:(ARXModule *)module;
+
+@end
+
+@implementation ARXType (ARXTypeRuntimeTypeEncodings)
+
++(ARXType *)typeForObjCType:(const char *)type inModule:(ARXModule *)module {
+ return [[[HammerCTypeBuilder alloc] init] typeForObjCType: type inModule: module];
+}
+
+@end
+
+
+@implementation HammerCTypeBuilder
+
+-(ARXType *)typeForObjCType:(const char *)type inModule:(ARXModule *)_module {
+ module = _module;
+ context = module.context;
+ HammerRuleGraphRef ruleGraph = HammerRuleGraphCreateWithGrammar(HammerCObjCTypeEncodingGrammar, nil, NULL);
+ NSError *error = nil;
+ if(!HammerRuleGraphParseString(ruleGraph, [NSString stringWithUTF8String: type], self, &error)) {
+ NSLog(@"Error parsing ObjC type '%s': %@ %@", type, error.localizedDescription, error.userInfo);
+ }
+ return resultType;
+}
+
+
+-(ARXType *)charRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType int8TypeInContext: context];
+}
+
+-(ARXType *)shortRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType int16TypeInContext: context];
+}
+
+-(ARXType *)intRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType int32TypeInContext: context];
+}
+
+-(ARXType *)longRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType int32TypeInContext: context];
+}
+
+-(ARXType *)longLongRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType int64TypeInContext: context];
+}
+
+-(ARXType *)floatRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType floatTypeInContext: context];
+}
+
+-(ARXType *)doubleRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType doubleTypeInContext: context];
+}
+
+-(ARXType *)boolRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType int1TypeInContext: context];
+}
+
+-(ARXType *)voidRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType voidTypeInContext: context];
+}
+
+-(ARXType *)stringRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType pointerTypeToType: [ARXType int8TypeInContext: context]];
+}
+
+-(ARXType *)objectRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType pointerTypeToType: [ARXType int8TypeInContext: context]];
+}
+
+-(ARXType *)classRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType pointerTypeToType: [ARXType int8TypeInContext: context]];
+}
+
+-(ARXType *)selectorRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType pointerTypeToType: [ARXType int8TypeInContext: context]];
+}
+
+-(ARXType *)arrayRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [ARXType arrayTypeWithCount: [[[submatches objectForKey: @"count"] lastObject] integerValue] type: [[submatches objectForKey: @"type"] lastObject]];
+}
+
+-(ARXType *)structRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return ([[submatches objectForKey: @"type"] count] > 0)
+ ? [ARXType structureTypeWithTypes: [submatches objectForKey: @"type"] inContext: context]
+ : [module typeNamed: [[submatches objectForKey: @"name"] lastObject]] ?: [ARXType int8TypeInContext: context];
+}
+
+-(ARXType *)unionRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return ([[submatches objectForKey: @"type"] count] > 0)
+ ? [ARXType unionTypeWithTypes: [submatches objectForKey: @"type"]]
+ : [module typeNamed: [[submatches objectForKey: @"name"] lastObject]] ?: [ARXType int8TypeInContext: context];
+}
+
+-(ARXType *)bitfieldRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return NULL;
+}
+
+-(ARXType *)pointerRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ ARXType *referencedType = [[submatches objectForKey: @"type"] lastObject];
+ if([referencedType isEqual: context.voidType]) {
+ referencedType = [ARXType int8TypeInContext: context];
+ }
+ return [ARXType pointerTypeToType: referencedType];
+}
+
+-(ARXType *)unknownRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return NULL;
+}
+
+-(ARXType *)typeRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [[submatches objectForKey: [submatches allKeys].lastObject] lastObject];
+}
+
+-(ARXType *)mainRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ resultType = [[submatches objectForKey: @"type"] lastObject];
+ return resultType;
+}
+
+@end
\ No newline at end of file
diff --git a/Categories/LLVMModule+RuntimeTypeEncodings.h b/Categories/LLVMModule+RuntimeTypeEncodings.h
deleted file mode 100644
index 24aecc7..0000000
--- a/Categories/LLVMModule+RuntimeTypeEncodings.h
+++ /dev/null
@@ -1,13 +0,0 @@
-// LLVMModule+RuntimeTypeEncodings.h
-// Created by Rob Rix on 2010-05-30
-// Copyright 2010 Monochrome Industries
-
-#import <Auspicion/Auspicion.h>
-
-#define LLVMModuleImportType(module, type) [module setObjCType: @encode(type) forName: @#type]
-
-@interface LLVMModule (LLVMModuleRuntimeTypeEncodings)
-
--(LLVMType *)setObjCType:(const char *)type forName:(NSString *)name;
-
-@end
diff --git a/Categories/LLVMModule+RuntimeTypeEncodings.m b/Categories/LLVMModule+RuntimeTypeEncodings.m
deleted file mode 100644
index d1fc598..0000000
--- a/Categories/LLVMModule+RuntimeTypeEncodings.m
+++ /dev/null
@@ -1,16 +0,0 @@
-// LLVMModule+RuntimeTypeEncodings.m
-// Created by Rob Rix on 2010-05-30
-// Copyright 2010 Monochrome Industries
-
-#import "LLVMModule+RuntimeTypeEncodings.h"
-#import "LLVMType+RuntimeTypeEncodings.h"
-
-@implementation LLVMModule (LLVMModuleRuntimeTypeEncodings)
-
--(LLVMType *)setObjCType:(const char *)type forName:(NSString *)name {
- LLVMType *result = [LLVMType typeForObjCType: type inModule: self];
- [self setType: result forName: name];
- return result;
-}
-
-@end
diff --git a/Categories/LLVMType+RuntimeTypeEncodings.h b/Categories/LLVMType+RuntimeTypeEncodings.h
deleted file mode 100644
index b310f61..0000000
--- a/Categories/LLVMType+RuntimeTypeEncodings.h
+++ /dev/null
@@ -1,11 +0,0 @@
-// LLVMType+RuntimeTypeEncodings.h
-// Created by Rob Rix on 2010-05-30
-// Copyright 2010 Monochrome Industries
-
-#import <Auspicion/Auspicion.h>
-
-@interface LLVMType (LLVMTypeRuntimeTypeEncodings)
-
-+(LLVMType *)typeForObjCType:(const char *)type inModule:(LLVMModule *)module;
-
-@end
diff --git a/Categories/LLVMType+RuntimeTypeEncodings.m b/Categories/LLVMType+RuntimeTypeEncodings.m
deleted file mode 100644
index ecd3b07..0000000
--- a/Categories/LLVMType+RuntimeTypeEncodings.m
+++ /dev/null
@@ -1,158 +0,0 @@
-// LLVMType+RuntimeTypeEncodings.m
-// Created by Rob Rix on 2010-05-30
-// Copyright 2010 Monochrome Industries
-
-#import "LLVMType+RuntimeTypeEncodings.h"
-
-static NSString * const HammerCObjCTypeEncodingGrammar =
- @"char = [cC];\n"
- @"short = [sS];\n"
- @"int = [iI];\n"
- @"long = [lL];\n"
- @"longLong = [qQ];\n"
- @"float = 'f';\n"
- @"double = 'd';\n"
- @"bool = 'B';\n"
- @"void = 'v';\n"
- @"string = '*';\n"
- @"object = '@';\n"
- @"class = '#';\n"
- @"selector = ':';\n"
- @"array = '[' (count = [\\d]+) type ']';\n"
- @"struct = '{' (name = [\\w]+) ('=' type*)? '}';\n"
- @"union = '(' (name = [\\w]+) ('=' type*)? ')';\n"
- @"bitfield = 'b' (width = [\\d]+);\n"
- @"pointer = '^' type;\n"
- @"unknown = '?';\n"
- @"type = char | short | int | long | longLong | float | double | bool | void | string | object | class | selector | array | struct | union | bitfield | pointer | unknown;\n"
- @"main = type+;\n"
-;
-
-@interface HammerCTypeBuilder : NSObject <HammerBuilder> {
- LLVMType *resultType;
- LLVMModule *module;
- LLVMContext *context;
-}
-
--(LLVMType *)typeForObjCType:(const char *)type inModule:(LLVMModule *)module;
-
-@end
-
-@implementation LLVMType (LLVMTypeRuntimeTypeEncodings)
-
-+(LLVMType *)typeForObjCType:(const char *)type inModule:(LLVMModule *)module {
- return [[[[HammerCTypeBuilder alloc] init] autorelease] typeForObjCType: type inModule: module];
-}
-
-@end
-
-
-@implementation HammerCTypeBuilder
-
--(LLVMType *)typeForObjCType:(const char *)type inModule:(LLVMModule *)_module {
- module = [_module retain];
- context = module.context;
- HammerRuleGraphRef ruleGraph = HammerRuleGraphCreateWithGrammar(HammerCObjCTypeEncodingGrammar, nil, NULL);
- NSError *error = nil;
- if(!HammerRuleGraphParseString(ruleGraph, [NSString stringWithUTF8String: type], self, &error)) {
- NSLog(@"Error parsing ObjC type '%s': %@ %@", type, error.localizedDescription, error.userInfo);
- }
- [module release];
- return resultType;
-}
-
-
--(LLVMType *)charRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType int8TypeInContext: context];
-}
-
--(LLVMType *)shortRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType int16TypeInContext: context];
-}
-
--(LLVMType *)intRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType int32TypeInContext: context];
-}
-
--(LLVMType *)longRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType int32TypeInContext: context];
-}
-
--(LLVMType *)longLongRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType int64TypeInContext: context];
-}
-
--(LLVMType *)floatRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType floatTypeInContext: context];
-}
-
--(LLVMType *)doubleRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType doubleTypeInContext: context];
-}
-
--(LLVMType *)boolRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType int1TypeInContext: context];
-}
-
--(LLVMType *)voidRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType voidTypeInContext: context];
-}
-
--(LLVMType *)stringRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType pointerTypeToType: [LLVMType int8TypeInContext: context]];
-}
-
--(LLVMType *)objectRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType pointerTypeToType: [LLVMType int8TypeInContext: context]];
-}
-
--(LLVMType *)classRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType pointerTypeToType: [LLVMType int8TypeInContext: context]];
-}
-
--(LLVMType *)selectorRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType pointerTypeToType: [LLVMType int8TypeInContext: context]];
-}
-
--(LLVMType *)arrayRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [LLVMType arrayTypeWithCount: [[[submatches objectForKey: @"count"] lastObject] integerValue] type: [[submatches objectForKey: @"type"] lastObject]];
-}
-
--(LLVMType *)structRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return ([[submatches objectForKey: @"type"] count] > 0)
- ? [LLVMType structureTypeWithTypes: [submatches objectForKey: @"type"]]
- : [module typeNamed: [[submatches objectForKey: @"name"] lastObject]] ?: [LLVMType int8TypeInContext: context];
-}
-
--(LLVMType *)unionRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return ([[submatches objectForKey: @"type"] count] > 0)
- ? [LLVMType unionTypeWithTypes: [submatches objectForKey: @"type"]]
- : [module typeNamed: [[submatches objectForKey: @"name"] lastObject]] ?: [LLVMType int8TypeInContext: context];
-}
-
--(LLVMType *)bitfieldRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return NULL;
-}
-
--(LLVMType *)pointerRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- LLVMType *referencedType = [[submatches objectForKey: @"type"] lastObject];
- if([referencedType isEqual: context.voidType]) {
- referencedType = [LLVMType int8TypeInContext: context];
- }
- return [LLVMType pointerTypeToType: referencedType];
-}
-
--(LLVMType *)unknownRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return NULL;
-}
-
--(LLVMType *)typeRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- return [[submatches objectForKey: [submatches allKeys].lastObject] lastObject];
-}
-
--(LLVMType *)mainRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
- resultType = [[submatches objectForKey: @"type"] lastObject];
- return resultType;
-}
-
-@end
\ No newline at end of file
diff --git a/Classes/HammerCompiledRule.h b/Classes/HammerCompiledRule.h
index 9e303a0..b5b6a4d 100644
--- a/Classes/HammerCompiledRule.h
+++ b/Classes/HammerCompiledRule.h
@@ -1,29 +1,29 @@
// HammerCompiledRule.h
// Created by Rob Rix on 2009-12-23
// Copyright 2009 Monochrome Industries
#import <Hammer/Hammer.h>
-@class LLVMCompiler, LLVMFunction;
+@class ARXCompiler, ARXFunction;
@interface HammerBuiltRuleFunctions : NSObject {
- LLVMFunction *lengthOfMatch;
- LLVMFunction *rangeOfMatch;
+ ARXFunction *lengthOfMatch;
+ ARXFunction *rangeOfMatch;
}
-@property (nonatomic, retain) LLVMFunction *lengthOfMatch;
-@property (nonatomic, retain) LLVMFunction *rangeOfMatch;
+@property (nonatomic, retain) ARXFunction *lengthOfMatch;
+@property (nonatomic, retain) ARXFunction *rangeOfMatch;
@end
typedef HammerIndex(*HammerCompiledRuleLengthOfMatchFunction)(HammerIndex, HammerParserState *);
typedef BOOL(*HammerCompiledRuleRangeOfMatchFunction)(NSRange *, HammerIndex, HammerParserState *);
typedef struct HammerCompiledRule * HammerCompiledRuleRef;
HammerCompiledRuleRef HammerCompiledRuleCreate(HammerRuleRef source, HammerCompiledRuleLengthOfMatchFunction lengthOfMatch, HammerCompiledRuleRangeOfMatchFunction rangeOfMatch);
HammerRuleRef HammerCompiledRuleGetSourceRule(HammerCompiledRuleRef self);
HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleGetLengthOfMatchFunction(HammerCompiledRuleRef self);
HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleGetRangeOfMatchFunction(HammerCompiledRuleRef self);
diff --git a/Classes/HammerRuleCompiler.h b/Classes/HammerRuleCompiler.h
index 8eb6141..25a7c95 100644
--- a/Classes/HammerRuleCompiler.h
+++ b/Classes/HammerRuleCompiler.h
@@ -1,25 +1,32 @@
// HammerRuleCompiler.h
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import <Foundation/Foundation.h>
-#import <Hammer/Hammer.h>
+#import "Hammer.h"
-@class LLVMBuilder, LLVMContext, LLVMModule, LLVMType;
+#import "ARXModule.h"
+
+@class ARXContext, ARXFunction;
@interface HammerRuleCompiler : HammerRuleVisitor {
- LLVMBuilder *builder;
- LLVMContext *context;
-
- LLVMModule *module;
-
+ ARXContext *context;
+ ARXModule *module;
HammerRulePrinter *printer;
-
- NSMutableArray *builtFunctionsStack;
}
+(id)compiler;
+@property (nonatomic, readonly) ARXModule *module;
+
+-(NSString *)nameForRule:(HammerRuleRef)rule;
+
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule;
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrule:(ARXFunction *)subrule;
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules;
+
+-(ARXModuleFunctionDefinitionBlock)rangeOfMatchSkippingIgnorableCharactersDefinitionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(ARXFunction *)lengthOfMatch;
+
-(HammerRuleRef)compileRule:(HammerRuleRef)rule;
@end
diff --git a/Classes/HammerRuleCompiler.m b/Classes/HammerRuleCompiler.m
index e73ac12..46e1b59 100644
--- a/Classes/HammerRuleCompiler.m
+++ b/Classes/HammerRuleCompiler.m
@@ -1,657 +1,260 @@
// HammerRuleCompiler.m
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
+#import "HammerRuleCompilerVisitor.h"
#import "Auspicion.h"
#import "Hammer.h"
-#import "LLVMModule+RuntimeTypeEncodings.h"
-
-@interface HammerRuleCompiler () <HammerRuleVisitor>
-
--(void)pushRule;
--(NSArray *)popRule;
-
--(NSString *)nameForFunction:(NSString *)function forRule:(HammerRuleRef)rule;
--(NSString *)nameForRule:(HammerRuleRef)rule;
-
-@end
+#import "ARXModule+RuntimeTypeEncodings.h"
@implementation HammerRuleCompiler
+@synthesize module;
+
+(id)compiler {
- return [[[self alloc] init] autorelease];
+ return [[self alloc] init];
}
-(id)init {
if(self = [super init]) {
- context = [[LLVMContext context] retain];
- builder = [[LLVMBuilder builderWithContext: context] retain];
+ context = [[ARXContext context] retain];
+ module = [[ARXModule moduleWithName: @"HammerRuleCompilerModule" inContext: context] retain];
+ printer = [[HammerRulePrinter alloc] init];
- module = [[LLVMModule moduleWithName: @"HammerRuleCompilerModule" inContext: context] retain];
+ ARXModuleImportType(module, HammerIndex);
+ ARXModuleImportType(module, CFIndex);
+ [module setType: context.int1Type forName: @"Boolean"];
+ ARXModuleImportType(module, UniChar);
+ CFCharacterSetRef characterSet = NULL;
+ CFStringRef string = NULL;
+ [module setObjCType: @encode(__typeof__(characterSet)) forName: @"CFCharacterSetRef"];
+ [module setObjCType: @encode(__typeof__(string)) forName: @"CFStringRef"];
- LLVMModuleImportType(module, HammerIndex);
- LLVMStructureType *rangeType = (LLVMStructureType *)LLVMModuleImportType(module, NSRange);
+ ARXStructureType *rangeType = (ARXStructureType *)ARXModuleImportType(module, NSRange);
[rangeType declareElementNames: [NSArray arrayWithObjects:
@"location",
@"length",
nil]];
- LLVMModuleImportType(module, HammerRuleRef);
- LLVMModuleImportType(module, HammerSequenceRef);
- LLVMModuleImportType(module, HammerMatchRef);
- LLVMModuleImportType(module, NSString *);
- LLVMStructureType *parserStateType = (LLVMStructureType *)LLVMModuleImportType(module, HammerParserState);
+ ARXModuleImportType(module, HammerRuleRef);
+ ARXModuleImportType(module, HammerSequenceRef);
+ ARXModuleImportType(module, HammerMatchRef);
+ ARXModuleImportType(module, NSString *);
+ ARXStructureType *parserStateType = (ARXStructureType *)ARXModuleImportType(module, HammerParserState);
[parserStateType declareElementNames: [NSArray arrayWithObjects:
@"sequence",
@"errorContext",
@"matchContext",
@"ruleGraph",
@"isIgnoringMatches",
nil]];
- [module setType: [LLVMType pointerTypeToType: parserStateType] forName: @"HammerParserState *"];
+ [module setType: [ARXType pointerTypeToType: parserStateType] forName: @"HammerParserState *"];
- [module setType: [LLVMType functionType: context.integerType,
+ ARXFunctionType *lengthOfMatch = [ARXType functionType: context.integerType,
[module typeNamed: @"HammerIndex"],
[module typeNamed: @"HammerParserState *"],
- nil] forName: @"HammerRuleLengthOfMatchFunction"];
+ nil];
+ [lengthOfMatch declareArgumentNames: [NSArray arrayWithObjects: @"initial", @"state", nil]];
+ [module setType: lengthOfMatch forName: @"lengthOfMatch"];
- [module setType: [LLVMType functionType: context.int1Type,
- [LLVMType pointerTypeToType: [module typeNamed: @"NSRange"]],
+ ARXFunctionType *rangeOfMatch = [ARXType functionType: context.int1Type,
+ [ARXType pointerTypeToType: [module typeNamed: @"NSRange"]],
[module typeNamed: @"HammerIndex"],
[module typeNamed: @"HammerParserState *"],
- nil] forName: @"HammerRuleRangeOfMatchFunction"];
-
- printer = [[HammerRulePrinter alloc] init];
+ nil];
+ [rangeOfMatch declareArgumentNames: [NSArray arrayWithObjects: @"outrange", @"initial", @"state", nil]];
+ [module setType: rangeOfMatch forName: @"rangeOfMatch"];
}
return self;
}
--(void)dealloc {
- [context release];
- [builder release];
- [module release];
- [printer release];
- [super dealloc];
-}
-
-(HammerRuleRef)compileRule:(HammerRuleRef)rule {
- NSArray *builtFunctionsArray = nil;
- builtFunctionsStack = [[NSMutableArray alloc] init];
- [self pushRule];
-
+ HammerBuiltRuleFunctions *builtFunctions = nil;
@try {
- HammerRuleAcceptVisitor(rule, self);
+ HammerRuleCompilerVisitor *visitor = [[HammerRuleCompilerVisitor alloc] initWithCompiler: self];
+ builtFunctions = HammerRuleAcceptVisitor(rule, visitor);
}
@catch(NSException *exception) {
NSLog(@"%@", [[exception callStackSymbols] componentsJoinedByString: @"\n"]);
@throw exception;
}
- builtFunctionsArray = [self popRule];
-
NSError *error = nil;
if(![module verifyWithError: &error]) {
// LLVMDumpModule([module moduleRef]);
NSLog(@"Error in module: %@", error.localizedDescription);
return nil;
}
- LLVMCompiler *compiler = [LLVMCompiler compilerWithContext: context];
+ ARXCompiler *compiler = [ARXCompiler compilerWithContext: context];
[compiler addModule: module];
- LLVMOptimizer *optimizer = [LLVMOptimizer optimizerWithCompiler: compiler];
+ ARXOptimizer *optimizer = [ARXOptimizer optimizerWithCompiler: compiler];
[optimizer addConstantPropagationPass];
[optimizer addInstructionCombiningPass];
[optimizer addPromoteMemoryToRegisterPass];
// [optimizer addGVNPass];
// [optimizer addCFGSimplificationPass];
[optimizer optimizeModule: module];
- NSAssert(builtFunctionsArray.count >= 1, @"No functions were built.");
- HammerBuiltRuleFunctions *builtFunctions = builtFunctionsArray.lastObject;
-
HammerCompiledRuleRef compiledRule = HammerCompiledRuleCreate(rule, [compiler compiledFunction: builtFunctions.lengthOfMatch], [compiler compiledFunction: builtFunctions.rangeOfMatch]);
- [builtFunctionsStack release];
-
return compiledRule;
}
--(LLVMFunction *)lengthOfIgnorableCharactersFunction {
- return [module externalFunctionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [LLVMType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"]]];
+-(NSString *)nameForRule:(HammerRuleRef)rule {
+ return [NSString stringWithFormat: @"%s(%@)", RXObjectTypeGetName(RXGetType(rule)), [printer printRule: rule]];
+}
+
+
+-(ARXFunction *)lengthOfIgnorableCharactersFunction {
+ return [module externalFunctionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"], nil]];
/*
- return [module functionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [LLVMType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"]] definition: ^(LLVMFunctionBuilder *function) {
- LLVMPointerValue
+ return [module functionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"], nil] definition: ^(ARXFunctionBuilder *function) {
+ ARXPointerValue
*length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]],
- *ignorableRule = [function allocateVariableOfType: [module typeNamed: @"HammerRuleRef"] value: [[self ruleGraphGetRuleForNameFunction] call: ((LLVMPointerValue *)[function argumentNamed: @"state"]).value elementNamed: @"ruleGraph"]];
+ *ignorableRule = [function allocateVariableOfType: [module typeNamed: @"HammerRuleRef"] value: [[self ruleGraphGetRuleForNameFunction] call: ((ARXPointerValue *)[function argumentNamed: @"state"]).value elementNamed: @"ruleGraph"]];
}];
*/
}
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule {
+ return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:", (NSString *)HammerRuleGetShortTypeName(rule)]) withObject: rule];
+}
--(LLVMFunction *)rangeOfMatchSkippingIgnorableCharactersFunctionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
- return [module functionWithName: [self nameForFunction: @"rangeOfMatchSkppingIgnorableCharacters" forRule: rule] type: [module typeNamed: @"HammerRuleRangeOfMatchFunction"] definition: ^(LLVMFunctionBuilder *function) {
- [function declareArgumentNames: [NSArray arrayWithObjects: @"outrange", @"initial", @"state", nil]];
-
- LLVMPointerValue
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrule:(ARXFunction *)subrule {
+ return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrule:", (NSString *)HammerRuleGetShortTypeName(rule), subrule]) withObject: rule withObject: subrule];
+}
+
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
+ return [self performSelector: NSSelectorFromString([NSString stringWithFormat: @"lengthOfMatchDefinitionFor%@:withVisitedSubrules:", (NSString *)HammerRuleGetShortTypeName(rule), subrules]) withObject: rule withObject: subrules];
+}
+
+-(ARXModuleFunctionDefinitionBlock)rangeOfMatchSkippingIgnorableCharactersDefinitionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(ARXFunction *)lengthOfMatch {
+ return [^(ARXFunctionBuilder *function) {
+ ARXPointerValue
*length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]],
*ignorable = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]];
[[length.value equals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
ignorable.value = [[self lengthOfIgnorableCharactersFunction] call: [function argumentNamed: @"state"], [function argumentNamed: @"initial"]];
[[ignorable.value notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
length.value = [lengthOfMatch call: [[function argumentNamed: @"initial"] plus: ignorable.value], [function argumentNamed: @"state"]];
}];
}];
- ((LLVMStructureValue *)((LLVMPointerValue *)[function argumentNamed: @"outrange"]).value).elements = [NSArray arrayWithObjects:
+ [function structureArgumentNamed: @"outrange"].elements = [NSArray arrayWithObjects:
[[function argumentNamed: @"initial"] plus: [[ignorable.value equals: [context constantUnsignedInteger: NSNotFound]] select: [context constantUnsignedInteger: 0] or: ignorable.value]],
length.value,
nil];
- [function return: [length notEquals: [context constantUnsignedInteger: NSNotFound]]];
- }];
+ [function return: [length.value notEquals: [context constantUnsignedInteger: NSNotFound]]];
+ } copy];
}
--(LLVMFunction *)defaultRangeOfMatchFunctionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
- NSString *name = [self nameForFunction: @"rangeOfMatchFromCursor:withParser:" forRule: rule];
-
- LLVMFunction *ignorableCharactersFromCursor = [module externalFunctionWithName: @"HammerParserIgnorableCharactersFromCursor" type: [LLVMType functionType: context.integerType, context.untypedPointerType, context.integerType, nil]];
-
- LLVMFunction *rangeOfMatch = [module functionNamed: name];
- if(!rangeOfMatch) {
- rangeOfMatch = [module functionWithName: name typeName: @"HammerRuleRangeOfMatchFunction"];
- [builder positionAtEndOfFunction: rangeOfMatch];
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForAlternationRule:(HammerAlternationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
+ return [^(ARXFunctionBuilder *function) {
+ ARXPointerValue *length = [function allocateVariableOfType: context.integerType value: [context constantUnsignedInteger: NSNotFound]];
+ ARXBlock *returnBlock = [function addBlockWithName: @"return"];
- LLVMBlock
- *tryIgnorableBlock = [rangeOfMatch appendBlockWithName: @"tryIgnorable"],
- *retryAfterIgnorableBlock = [rangeOfMatch appendBlockWithName: @"retryAfterIgnorable"],
- *returnBlock = [rangeOfMatch appendBlockWithName: @"return"];
-
- LLVMValue
- *notFound = [context constantUnsignedInteger: NSNotFound],
- *zero = [context constantUnsignedInteger: 0],
- *length = [builder allocateLocal: @"length" type: context.integerType],
- *ignorable = [builder allocateLocal: @"ignorable" type: context.integerType];
-
- // NSUInteger length = [self lengthOfMatchFromCursor: initial withParser: parser];
- [builder set: length, [builder call: lengthOfMatch, [rangeOfMatch argumentAtIndex: 1], [rangeOfMatch argumentAtIndex: 2], nil]];
-
- // NSUInteger ignorable = NSNotFound;
- [builder set: ignorable, notFound];
-
- // if(length == NSNotFound)
- [builder if: [builder equal: [builder get: length], notFound] then: tryIgnorableBlock else: returnBlock];
- [builder positionAtEndOfBlock: tryIgnorableBlock]; {
- // ignorable = HammerParserIgnorableCharactersFromCursor(parser, initial);
- [builder set: ignorable, [builder call: ignorableCharactersFromCursor, [rangeOfMatch argumentAtIndex: 2], [rangeOfMatch argumentAtIndex: 1], nil]];
-
- // if(ignorable != NSNotFound)
- [builder if: [builder notEqual: [builder get: ignorable], notFound] then: retryAfterIgnorableBlock else: returnBlock];
- [builder positionAtEndOfBlock: retryAfterIgnorableBlock]; {
- // length = [self lengthOfMatchFromCursor: initial + ignorable withParser: parser];
- [builder set: length, [builder call: lengthOfMatch, [builder add: [rangeOfMatch argumentAtIndex: 1], [builder get: ignorable]], [rangeOfMatch argumentAtIndex: 2], nil]];
-
- [builder jumpToBlock: returnBlock];
- }
+ for(HammerBuiltRuleFunctions *subrule in subrules) {
+ [[(length.value = [subrule.lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]) notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
+ [function goto: returnBlock];
+ }];
}
- [builder positionAtEndOfBlock: returnBlock]; {
- [builder setElements: [rangeOfMatch argumentAtIndex: 0],
- [builder add:
- [rangeOfMatch argumentAtIndex: 1],
- [builder condition: [builder equal: [builder get: ignorable], notFound]
- then: zero
- else: [builder get: ignorable]
- ]
- ],
- [builder get: length],
- nil];
-
- [builder return: [builder notEqual: [builder get: length], notFound]];
- }
- }
- return rangeOfMatch;
-}
-
-
--(HammerBuiltRuleFunctions *)defaultFunctionsForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
- HammerBuiltRuleFunctions *functions = [[[HammerBuiltRuleFunctions alloc] init] autorelease];
- functions.lengthOfMatch = lengthOfMatch;
- functions.rangeOfMatch = [self defaultRangeOfMatchFunctionForRule: rule withLengthOfMatchFunction: lengthOfMatch];
- return functions;
-}
-
-
--(void)addBuiltFunctions:(HammerBuiltRuleFunctions *)functions {
- [builtFunctionsStack.lastObject addObject: functions];
-}
-
-
--(void)pushRule {
- [builtFunctionsStack addObject: [NSMutableArray array]];
+ [function goto: returnBlock];
+
+ [returnBlock define: ^{
+ [function return: length.value];
+ }];
+ } copy];
}
--(NSArray *)popRule {
- NSArray *lastFunctions = [[builtFunctionsStack.lastObject retain] autorelease];
- [builtFunctionsStack removeLastObject];
- return lastFunctions;
+-(ARXModuleFunctionDefinitionBlock)rangeOfMatchFunctionForAlternationRule:(HammerAlternationRuleRef)rule {
+ NSLog(@"type of a function: %s", @encode(HammerRuleLengthOfMatchMethod));
+ return nil;
}
--(LLVMFunction *)parserIsAtEndFunction {
- return [module externalFunctionWithName: @"HammerParserCursorIsAtEnd" type: [LLVMType functionType: context.int1Type,
- context.untypedPointerType,
- context.integerType,
- nil]];
+-(ARXFunction *)sequenceGetLengthFunction {
+ return [module externalFunctionWithName: @"HammerSequenceGetLength" type: [ARXType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerSequenceRef"], nil]];
}
--(LLVMFunction *)parserGetInputStringFunction {
- return [module externalFunctionWithName: @"HammerParserGetInputString" type: [LLVMType functionType: context.untypedPointerType, context.untypedPointerType, nil]];
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchFunctionForCharacterRule:(HammerCharacterRuleRef)rule {
+ return [^(ARXFunctionBuilder *function) {
+ [[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction
+ call: [[function pointerArgumentNamed: @"state"].structureValue elementNamed: @"sequence"]]]
+ select: [context constantUnsignedInteger: 1]
+ or: [context constantUnsignedInteger: NSNotFound]];
+ } copy];
}
--(NSString *)nameForFunction:(NSString *)function forRule:(HammerRuleRef)rule {
- return [NSString stringWithFormat: @"%s(%@) %@", RXObjectTypeGetName(RXGetType(rule)), [printer printRule: rule], function];
+-(ARXFunction *)characterIsMemberFunction {
+ return [module externalFunctionWithName: @"CFCharacterSetIsCharacterMember" type: [ARXType functionType: [module typeNamed: @"Boolean"], [module typeNamed: @"CFCharacterSetRef"], [module typeNamed: @"UniChar"], nil]];
}
--(NSString *)nameForRule:(HammerRuleRef)rule {
- return [self nameForFunction: @"lengthOfMatchFromCursor:withParser:" forRule: rule];
+-(ARXFunction *)getCharacterAtIndexFunction {
+ return [module externalFunctionWithName: @"CFStringGetCharacterAtIndex" type: [ARXType functionType: [module typeNamed: @"UniChar"], [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"CFIndex"], nil]];
}
-
--(void)leaveAlternationRule:(HammerAlternationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
-
- LLVMValue *length = [builder allocateLocal: @"length" type: context.integerType];
-
- LLVMBlock *returnBlock = [lengthOfMatch appendBlockWithName: @"return"];
-
- NSUInteger i = 0;
- for(HammerBuiltRuleFunctions *subrule in subrules) {
- LLVMBlock *subruleBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d", i]];
- [builder jumpToBlock: subruleBlock];
- [builder positionAtEndOfBlock: subruleBlock];
-
- [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil]];
-
- LLVMBlock *subruleNotMatchedBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d not matched", i]];
- [builder if: [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]] then: returnBlock else: subruleNotMatchedBlock];
-
- [builder positionAtEndOfBlock: subruleNotMatchedBlock];
- i++;
- }
-
- [builder jumpToBlock: returnBlock];
-
- [builder positionAtEndOfBlock: returnBlock];
- [builder return: [builder get: length]];
- }
-
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
-}
-
-
--(void)leaveCharacterRule:(HammerCharacterRuleRef)rule {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfFunction: lengthOfMatch];
-
- [builder return: [builder condition:
- [builder not: [builder call: [self parserIsAtEndFunction], [lengthOfMatch argumentAtIndex: 1], [lengthOfMatch argumentAtIndex: 0], nil]]
- then: [context constantUnsignedInteger: 1]
- else: [context constantUnsignedInteger: NSNotFound]
- ]];
- }
-
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
-}
-
-
--(void)leaveCharacterSetRule:(HammerCharacterSetRuleRef)rule {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction *isCharacterMemberFunction = [module externalFunctionWithName: @"CFCharacterSetIsCharacterMember" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, context.int16Type, nil]];
- LLVMFunction *characterAtIndexFunction = [module externalFunctionWithName: @"CFStringGetCharacterAtIndex" type: [LLVMType functionType: context.int16Type, context.untypedPointerType, context.integerType, nil]];
-
- LLVMValue *notFound = [context constantUnsignedInteger: NSNotFound];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfFunction: lengthOfMatch];
-
- [builder return: [builder condition: [builder and:
- [builder not: [builder call: [self parserIsAtEndFunction], [lengthOfMatch argumentAtIndex: 1], [lengthOfMatch argumentAtIndex: 0], nil]],
- [builder call: isCharacterMemberFunction,
- [context constantUntypedPointer: HammerCharacterSetRuleGetCharacterSet(rule)],
- [builder call: characterAtIndexFunction,
- [builder call: [self parserGetInputStringFunction], [lengthOfMatch argumentAtIndex: 1], nil],
- [lengthOfMatch argumentAtIndex: 0],
- nil],
- nil]
- ]
- then: [context constantUnsignedInteger: 1]
- else: notFound
- ]];
- }
-
- name = [self nameForFunction: @"range:ofMatchFromCursor:withParser:" forRule: rule];
- LLVMFunction *rangeOfMatch = [module functionNamed: name];
- if(!rangeOfMatch) {
- rangeOfMatch = [module functionWithName: name typeName: @"HammerRuleRangeOfMatchFunction"];
- [builder positionAtEndOfFunction: rangeOfMatch];
-
- [builder setElements: [rangeOfMatch argumentAtIndex: 0],
- [rangeOfMatch argumentAtIndex: 1],
- [context constantUnsignedInteger: 1],
- nil];
-
- [builder return: [builder notEqual: [builder call: lengthOfMatch, [rangeOfMatch argumentAtIndex: 1], [rangeOfMatch argumentAtIndex: 2], nil], notFound]];
- }
-
- HammerBuiltRuleFunctions *functions = [[[HammerBuiltRuleFunctions alloc] init] autorelease];
- functions.lengthOfMatch = lengthOfMatch;
- functions.rangeOfMatch = rangeOfMatch;
-
- [self addBuiltFunctions: functions];
+-(ARXFunction *)sequenceGetStringFunction {
+ return [module externalFunctionWithName: @"HammerSequenceGetString" type: [ARXType functionType: [module typeNamed: @"CFStringRef"], [module typeNamed: @"HammerSequenceRef"], nil]];
}
--(void)leaveConcatenationRule:(HammerConcatenationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction
- *pushMatchContext = [module externalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
- *popMatchContext = [module externalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, nil]];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
-
- [builder call: pushMatchContext, [lengthOfMatch argumentAtIndex: 1], nil];
-
- LLVMValue
- *length = [builder allocateLocal: @"length" type: context.integerType],
- *subrange = [builder allocateLocal: @"subrange" type: [module typeNamed: @"NSRange"]];
-
- [builder set: length, [context constantUnsignedInteger: 0]];
-
- LLVMBlock
- *notFoundBlock = [lengthOfMatch appendBlockWithName: @"notFound"],
- *returnLengthBlock = [lengthOfMatch appendBlockWithName: @"returnLength"];
-
- NSUInteger i = 0;
- for(HammerBuiltRuleFunctions *subruleFunctions in subrules) {
- LLVMBlock *subruleBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d", i]];
- LLVMBlock *subruleFoundBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d found", i]];
- [builder jumpToBlock: subruleBlock];
- [builder positionAtEndOfBlock: subruleBlock]; {
- [builder if: [builder call: subruleFunctions.rangeOfMatch,
- subrange,
- [builder add: [lengthOfMatch argumentAtIndex: 0], [builder get: length]],
- [lengthOfMatch argumentAtIndex: 1],
- nil] then: subruleFoundBlock else: notFoundBlock];
- }
-
- [builder positionAtEndOfBlock: subruleFoundBlock]; {
- // length = NSMaxRange(subrange) - initial;
- [builder set: length, [builder subtract: [builder add: [builder getElement: subrange atIndex: 0], [builder getElement: subrange atIndex: 1]], [lengthOfMatch argumentAtIndex: 0]]];
- }
-
- i++;
- }
-
- [builder jumpToBlock: returnLengthBlock];
-
- [builder positionAtEndOfBlock: notFoundBlock]; {
- [builder set: length, [context constantUnsignedInteger: NSNotFound]];
- [builder jumpToBlock: returnLengthBlock];
- }
-
- [builder positionAtEndOfBlock: returnLengthBlock]; {
- [builder call: popMatchContext, [lengthOfMatch argumentAtIndex: 1], [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]], nil];
- [builder return: [builder get: length]];
- }
- }
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
+-(void)initializeDataForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
+ // fixme: constant pointers are only viable for JIT
+ // fixme: actually call the initializers from a function
+ [module initializeGlobal: [context constantPointer: (void *)HammerCharacterSetRuleGetCharacterSet(rule) ofType: [module typeNamed: @"CFCharacterSetRef"]] forName: [self nameForRule: rule]];
}
-
--(void)leaveLiteralConcatenationRule:(HammerLiteralConcatenationRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction
- *getAttemptsIgnorableRule = [module externalFunctionWithName: @"HammerParserGetAttemptsIgnorableRule" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, nil]],
- *setAttemptsIgnorableRule = [module externalFunctionWithName: @"HammerParserSetAttemptsIgnorableRule" type: [LLVMType functionType: context.voidType, context.untypedPointerType, context.int1Type, nil]];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
-
- LLVMValue
- *attemptsIgnorableRule = [builder allocateLocal: @"attemptsIgnorableRule" type: context.int1Type],
- *length = [builder allocateLocal: @"length" type: context.integerType];
-
- [builder set: attemptsIgnorableRule, [builder call: getAttemptsIgnorableRule, [lengthOfMatch argumentAtIndex: 1], nil]];
-
- [builder call: setAttemptsIgnorableRule, [lengthOfMatch argumentAtIndex: 1], [context constantNullOfType: context.int1Type], nil];
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
+ return [^(ARXFunctionBuilder *function) {
+ [self initializeDataForCharacterSetRule: rule];
- [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil]];
-
- [builder call: setAttemptsIgnorableRule, [lengthOfMatch argumentAtIndex: 1], [builder get: attemptsIgnorableRule], nil];
-
- [builder return: [builder get: length]];
- }
-
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
+ ARXValue *sequence = [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"];
+ [function return: [[[[function argumentNamed: @"initial"] isUnsignedLessThan: [self.sequenceGetLengthFunction call: sequence]]
+ and: [self.characterIsMemberFunction call: [module globalNamed: [self nameForRule: rule]], [self.getCharacterAtIndexFunction call: [self.sequenceGetStringFunction call: sequence], [function argumentNamed: @"initial"], nil], nil]
+ ] select: [context constantUnsignedInteger: 1]
+ or: [context constantUnsignedInteger: NSNotFound]]];
+ } copy];
}
+// -(ARXModuleFunctionDefinitionBlock)rangeOfMatchDefinitionForCharacterSetRule:(HammerCharacterSetRuleRef)rule {
+//
+// }
--(void)leaveLiteralRule:(HammerLiteralRuleRef)rule {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction *stringContainsStringAtIndexFunction = [module externalFunctionWithName: @"HammerLiteralRuleStringContainsStringAtIndex" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, context.untypedPointerType, context.integerType, nil]];
- LLVMFunction *parserGetInputLengthFunction = [module externalFunctionWithName: @"HammerParserGetInputLength" type: [LLVMType functionType: context.integerType, context.untypedPointerType, nil]];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfFunction: lengthOfMatch];
-
- [builder return: [builder condition: [builder and:
- [builder unsignedLessOrEqual: [builder add: [lengthOfMatch argumentAtIndex: 0], [context constantUnsignedInteger: HammerLiteralRuleGetLiteral(rule).length]], [builder call: parserGetInputLengthFunction, [lengthOfMatch argumentAtIndex: 1], nil]],
- [builder call: stringContainsStringAtIndexFunction,
- [builder call: [self parserGetInputStringFunction], [lengthOfMatch argumentAtIndex: 1], nil],
- [context constantUntypedPointer: HammerLiteralRuleGetLiteral(rule)],
- [lengthOfMatch argumentAtIndex: 0],
- nil]
- ]
- then: [context constantUnsignedInteger: HammerLiteralRuleGetLiteral(rule).length]
- else: [context constantUnsignedInteger: NSNotFound]
- ]];
- }
-
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
-}
-
--(void)leaveLookaheadRule:(HammerLookaheadRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfFunction: lengthOfMatch];
-
- [builder return: [builder condition: [builder notEqual: [builder call: subrule.lengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil], [context constantUnsignedInteger: NSNotFound]]
- then: [context constantUnsignedInteger: HammerLookaheadRuleGetNegative(rule)? NSNotFound : 0]
- else: [context constantUnsignedInteger: HammerLookaheadRuleGetNegative(rule)? 0 : NSNotFound]
- ]];
- }
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
+-(ARXFunction *)sequenceContainsSequenceAtIndexFunction {
+ return [module externalFunctionWithName: @"HammerSequenceContainsSequenceAtIndex" type: [ARXType functionType: context.int1Type, [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"HammerSequenceRef"], [module typeNamed: @"HammerIndex"], nil]];
}
-
--(void)leaveNamedRule:(HammerNamedRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction
- *pushMatchContext = [module externalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
- *popMatchContext = [module externalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, [module typeNamed: @"HammerRule"], [module typeNamed: @"NSString"], [module typeNamed: @"NSRange"], nil]];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfFunction: lengthOfMatch];
-
- [builder call: pushMatchContext, [lengthOfMatch argumentAtIndex: 1], nil];
-
- LLVMValue
- *length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
- *range = [builder allocateLocal: @"range" type: [module typeNamed: @"NSRange"]];
-
- [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil]];
- [builder setElements: range, [lengthOfMatch argumentAtIndex: 0], [builder get: length], nil];
-
- [builder call: popMatchContext,
- [lengthOfMatch argumentAtIndex: 1],
- [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]],
- [context constantUntypedPointer: rule],
- [context constantUntypedPointer: HammerNamedRuleGetName(rule)],
- [builder get: range],
- nil];
-
- [builder return: [builder get: length]];
- }
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
+-(void)initializeDataForLiteralRule:(HammerLiteralRuleRef)rule {
+ // fixme: constant pointers are only viable for JIT
+ // fixme: actually call the initializers from a function
+ [module initializeGlobal: [context constantPointer: (void *)HammerLiteralRuleGetSequence(rule) ofType: [module typeNamed: @"HammerSequenceRef"]] forName: [self nameForRule: rule]];
}
-
--(void)leaveReferenceRule:(HammerReferenceRuleRef)rule {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction
- *lengthOfMatchFunctionForReference = [module externalFunctionWithName: @"HammerCompiledRuleLengthOfMatchFunctionForReference" type: [LLVMType functionType: [LLVMType pointerTypeToType: [module typeNamed: @"HammerRuleLengthOfMatchFunction"]], [module typeNamed: @"HammerParser"], [module typeNamed: @"NSString"], nil]],
- *pushMatchContext = [module externalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
- *popMatchContext = [module externalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, [module typeNamed: @"HammerRule"], [module typeNamed: @"NSString"], [module typeNamed: @"NSRange"], nil]];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfFunction: lengthOfMatch];
-
- [builder call: pushMatchContext, [lengthOfMatch argumentAtIndex: 1], nil];
-
- LLVMFunction *subruleLengthOfMatch = (LLVMFunction *)[builder call: lengthOfMatchFunctionForReference, [lengthOfMatch argumentAtIndex: 1], [context constantUntypedPointer: HammerReferenceRuleGetReference(rule)], nil];
+-(ARXModuleFunctionDefinitionBlock)lengthOfMatchDefinitionForLiteralRule:(HammerLiteralRuleRef)rule {
+ return [^(ARXFunctionBuilder *function) {
+ [self initializeDataForLiteralRule: rule];
- LLVMValue
- *length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
- *range = [builder allocateLocal: @"range" type: [module typeNamed: @"NSRange"]];
-
- [builder set: length, [builder call: subruleLengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil]];
- [builder setElements: range, [lengthOfMatch argumentAtIndex: 0], [builder get: length], nil];
-
- [builder call: popMatchContext,
- [lengthOfMatch argumentAtIndex: 1],
- [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]],
- [context constantUntypedPointer: rule],
- [context constantUntypedPointer: HammerReferenceRuleGetReference(rule)],
- [builder get: range],
- nil];
-
- [builder return: [builder get: length]];
- }
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
+ ARXValue *sequence = [[function structureArgumentNamed: @"state"] elementNamed: @"sequence"];
+ [function return: [[[self.sequenceContainsSequenceAtIndexFunction call: sequence, [module globalNamed: [self nameForRule: rule]], [function argumentNamed: @"initial"]] toBoolean]
+ select: [context constantUnsignedInteger: HammerSequenceGetLength(HammerLiteralRuleGetSequence(rule))]
+ or: [context constantUnsignedInteger: NSNotFound]]];
+ } copy];
}
--(void)leaveRepetitionRule:(HammerRepetitionRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
- NSString *name = [self nameForRule: rule];
-
- LLVMFunction
- *pushMatchContext = [module externalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
- *popMatchContext = [module externalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, nil]];
-
- LLVMFunction *lengthOfMatch = [module functionNamed: name];
- if(!lengthOfMatch) {
- lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
- [builder positionAtEndOfFunction: lengthOfMatch];
-
- [builder call: pushMatchContext, [lengthOfMatch argumentAtIndex: 1], nil];
-
- LLVMValue
- *length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
- *count = [builder allocateLocal: @"count" type: context.int64Type],
- *subrange = [builder allocateLocal: @"subrange" type: [module typeNamed: @"NSRange"]];
-
- [builder set: length, [context constantUnsignedInteger: 0]];
- [builder set: count, [context constantUnsignedInt64: 0]];
-
- LLVMBlock
- *loopBlock = [lengthOfMatch appendBlockWithName: @"loop"],
- *subruleTestBlock = [lengthOfMatch appendBlockWithName: @"subrule test"],
- *subruleMatchedBlock = [lengthOfMatch appendBlockWithName: @"subrule matched"],
- *returnBlock = [lengthOfMatch appendBlockWithName: @"return"];
-
- LLVMValue
- *unbounded = [context constantUnsignedInt64: HammerRepetitionRuleUnboundedMaximum],
- *maximum = [context constantUnsignedInt64: HammerRepetitionRuleGetMaximum(rule)],
- *minimum = [context constantUnsignedInt64: HammerRepetitionRuleGetMinimum(rule)];
-
- [builder jumpToBlock: loopBlock];
-
- [builder positionAtEndOfBlock: loopBlock]; {
- [builder if: [builder or: [builder equal: maximum, unbounded], [builder unsignedLessThan: [builder get: count], maximum]] then: subruleTestBlock else: returnBlock];
- }
-
- [builder positionAtEndOfBlock: subruleTestBlock]; {
- [builder set: count, [builder add: [builder get: count], [context constantUnsignedInt64: 1]]];
-
- [builder if: [builder call: subrule.rangeOfMatch, subrange, [builder add: [lengthOfMatch argumentAtIndex: 0], [builder get: length]], [lengthOfMatch argumentAtIndex: 1], nil] then: subruleMatchedBlock else: returnBlock];
- }
-
- [builder positionAtEndOfBlock: subruleMatchedBlock]; {
- [builder set: length, [builder subtract: [builder add: [builder getElement: subrange atIndex: 0], [builder getElement: subrange atIndex: 1]], [lengthOfMatch argumentAtIndex: 0]]];
-
- [builder jumpToBlock: loopBlock];
- }
-
- [builder positionAtEndOfBlock: returnBlock]; {
- [builder set: length, [builder condition: (
- (HammerRepetitionRuleGetMaximum(rule) == HammerRepetitionRuleUnboundedMaximum)
- ? [builder unsignedLessThan: minimum, [builder get: count]]
- : [builder and: [builder unsignedLessThan: minimum, [builder get: count]], [builder unsignedLessOrEqual: [builder get: count], maximum]]
- )
- then: [builder get: length]
- else: [context constantUnsignedInteger: NSNotFound]
- ]];
-
- [builder call: popMatchContext, [lengthOfMatch argumentAtIndex: 1], [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]], nil];
-
- [builder return: [builder get: length]];
- }
- }
-
- [self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
-}
-
@end
diff --git a/Classes/HammerRuleCompilerVisitor.h b/Classes/HammerRuleCompilerVisitor.h
new file mode 100644
index 0000000..5fc1e50
--- /dev/null
+++ b/Classes/HammerRuleCompilerVisitor.h
@@ -0,0 +1,15 @@
+// HammerRuleCompilerVisitor.h
+// Created by Rob Rix on 2010-06-12
+// Copyright 2010 Monochrome Industries
+
+#import <Foundation/Foundation.h>
+
+@class HammerRuleCompiler, HammerRulePrinter;
+
+@interface HammerRuleCompilerVisitor : NSObject <HammerRuleVisitor> {
+ HammerRuleCompiler *compiler;
+}
+
+-(id)initWithCompiler:(HammerRuleCompiler *)_compiler;
+
+@end
diff --git a/Classes/HammerRuleCompilerVisitor.m b/Classes/HammerRuleCompilerVisitor.m
new file mode 100644
index 0000000..54f4dc0
--- /dev/null
+++ b/Classes/HammerRuleCompilerVisitor.m
@@ -0,0 +1,66 @@
+// HammerRuleCompilerVisitor.m
+// Created by Rob Rix on 2010-06-12
+// Copyright 2010 Monochrome Industries
+
+#import "HammerCompiledRule.h"
+#import "HammerRuleCompiler.h"
+#import "HammerRuleCompilerVisitor.h"
+
+@implementation HammerRuleCompilerVisitor
+
+-(id)initWithCompiler:(HammerRuleCompiler *)_compiler {
+ if(self = [super init]) {
+ compiler = _compiler;
+ }
+ return self;
+}
+
+
+-(void)visitRule:(HammerRuleRef)rule {}
+
+
+-(NSString *)nameForFunction:(NSString *)function forRule:(HammerRuleRef)rule {
+ return [NSString stringWithFormat: @"%@ %@", [compiler nameForRule: rule], function];
+}
+
+
+-(id)lengthOfMatchFunctionForRule:(HammerRuleRef)rule withDefinition:(ARXModuleFunctionDefinitionBlock)definition {
+ return [compiler.module functionWithName: [self nameForFunction: @"lengthOfMatch" forRule: rule] type: [compiler.module typeNamed: @"lengthOfMatch"] definition: definition];
+}
+
+-(id)rangeOfMatchFunctionForRule:(HammerRuleRef)rule withDefinition:(ARXModuleFunctionDefinitionBlock)definition {
+ return [compiler.module functionWithName: [self nameForFunction: @"rangeOfMatch" forRule: rule] type: [compiler.module typeNamed: @"rangeOfMatch"] definition: definition];
+}
+
+
+-(id)leaveRule:(HammerRuleRef)rule {
+ SEL selector = NSSelectorFromString([NSString stringWithFormat: @"rangeOfMatchDefinitionFor%@:", (NSString *)HammerRuleGetShortTypeName(rule)]);
+ HammerBuiltRuleFunctions *functions = [[HammerBuiltRuleFunctions alloc] init];
+ functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [compiler lengthOfMatchDefinitionForRule: rule]];
+ functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [compiler respondsToSelector: selector]
+ ? [compiler performSelector: selector withObject: rule]
+ : [compiler rangeOfMatchSkippingIgnorableCharactersDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
+ return functions;
+}
+
+-(id)leaveRule:(HammerRuleRef)rule withVisitedSubrule:(id)subrule {
+ SEL selector = NSSelectorFromString([NSString stringWithFormat: @"rangeOfMatchDefinitionFor%@:withVisitedSubrule:", (NSString *)HammerRuleGetShortTypeName(rule)]);
+ HammerBuiltRuleFunctions *functions = [[HammerBuiltRuleFunctions alloc] init];
+ functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [compiler lengthOfMatchDefinitionForRule: rule withVisitedSubrule: subrule]];
+ functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [compiler respondsToSelector: selector]
+ ? [compiler performSelector: selector withObject: rule withObject: subrule]
+ : [compiler rangeOfMatchSkippingIgnorableCharactersDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
+ return functions;
+}
+
+-(id)leaveRule:(HammerRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
+ SEL selector = NSSelectorFromString([NSString stringWithFormat: @"rangeOfMatchDefinitionFor%@:withVisitedSubrules:", (NSString *)HammerRuleGetShortTypeName(rule)]);
+ HammerBuiltRuleFunctions *functions = [[HammerBuiltRuleFunctions alloc] init];
+ functions.lengthOfMatch = [self lengthOfMatchFunctionForRule: rule withDefinition: [compiler lengthOfMatchDefinitionForRule: rule withVisitedSubrules: subrules]];
+ functions.rangeOfMatch = [self rangeOfMatchFunctionForRule: rule withDefinition: [compiler respondsToSelector: selector]
+ ? [compiler performSelector: selector withObject: rule withObject: subrules]
+ : [compiler rangeOfMatchSkippingIgnorableCharactersDefinitionForRule: rule withLengthOfMatchFunction: functions.lengthOfMatch]];
+ return functions;
+}
+
+@end
diff --git a/External/Auspicion b/External/Auspicion
index cc27173..d18afcd 160000
--- a/External/Auspicion
+++ b/External/Auspicion
@@ -1 +1 @@
-Subproject commit cc271739a58adc5a6e0c24f33ea874f1a7608d81
+Subproject commit d18afcd7f058886d5a94a0a70eed51295cb906e9
diff --git a/External/Hammer b/External/Hammer
index f5681c7..82f8413 160000
--- a/External/Hammer
+++ b/External/Hammer
@@ -1 +1 @@
-Subproject commit f5681c796c0d2da6a7c94d511d5c61a9fddf5985
+Subproject commit 82f8413dbb051876c44e28bbd66f6673d5addd2e
diff --git a/External/Include/Auspicion/ARXBlock+Protected.h b/External/Include/Auspicion/ARXBlock+Protected.h
new file mode 120000
index 0000000..c2fc7a2
--- /dev/null
+++ b/External/Include/Auspicion/ARXBlock+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXBlock+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXBlock.h b/External/Include/Auspicion/ARXBlock.h
new file mode 120000
index 0000000..7bb804c
--- /dev/null
+++ b/External/Include/Auspicion/ARXBlock.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXBlock.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXBooleanValue.h b/External/Include/Auspicion/ARXBooleanValue.h
new file mode 120000
index 0000000..b529d28
--- /dev/null
+++ b/External/Include/Auspicion/ARXBooleanValue.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/ARXBooleanValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXBuilder+Protected.h b/External/Include/Auspicion/ARXBuilder+Protected.h
new file mode 120000
index 0000000..286ea4b
--- /dev/null
+++ b/External/Include/Auspicion/ARXBuilder+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXBuilder+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXBuilder.h b/External/Include/Auspicion/ARXBuilder.h
new file mode 120000
index 0000000..0e8dd0d
--- /dev/null
+++ b/External/Include/Auspicion/ARXBuilder.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXBuilder.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXCompiler+Protected.h b/External/Include/Auspicion/ARXCompiler+Protected.h
new file mode 120000
index 0000000..5f85a09
--- /dev/null
+++ b/External/Include/Auspicion/ARXCompiler+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXCompiler+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXCompiler.h b/External/Include/Auspicion/ARXCompiler.h
new file mode 120000
index 0000000..5d6332d
--- /dev/null
+++ b/External/Include/Auspicion/ARXCompiler.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXCompiler.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXContext+Protected.h b/External/Include/Auspicion/ARXContext+Protected.h
new file mode 120000
index 0000000..2c50439
--- /dev/null
+++ b/External/Include/Auspicion/ARXContext+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXContext+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXContext.h b/External/Include/Auspicion/ARXContext.h
new file mode 120000
index 0000000..90874ac
--- /dev/null
+++ b/External/Include/Auspicion/ARXContext.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXContext.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXFunction+Protected.h b/External/Include/Auspicion/ARXFunction+Protected.h
new file mode 120000
index 0000000..100cd1f
--- /dev/null
+++ b/External/Include/Auspicion/ARXFunction+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/ARXFunction+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXFunction.h b/External/Include/Auspicion/ARXFunction.h
new file mode 120000
index 0000000..8748664
--- /dev/null
+++ b/External/Include/Auspicion/ARXFunction.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/ARXFunction.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXFunctionBuilder.h b/External/Include/Auspicion/ARXFunctionBuilder.h
new file mode 120000
index 0000000..e2d3f1f
--- /dev/null
+++ b/External/Include/Auspicion/ARXFunctionBuilder.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXFunctionBuilder.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXFunctionType.h b/External/Include/Auspicion/ARXFunctionType.h
new file mode 120000
index 0000000..faf4b71
--- /dev/null
+++ b/External/Include/Auspicion/ARXFunctionType.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Type/ARXFunctionType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXModule+Protected.h b/External/Include/Auspicion/ARXModule+Protected.h
new file mode 120000
index 0000000..7410d23
--- /dev/null
+++ b/External/Include/Auspicion/ARXModule+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXModule+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXModule.h b/External/Include/Auspicion/ARXModule.h
new file mode 120000
index 0000000..1f88f5e
--- /dev/null
+++ b/External/Include/Auspicion/ARXModule.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXModule.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXOptimizer+Protected.h b/External/Include/Auspicion/ARXOptimizer+Protected.h
new file mode 120000
index 0000000..99a8d54
--- /dev/null
+++ b/External/Include/Auspicion/ARXOptimizer+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXOptimizer+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXOptimizer.h b/External/Include/Auspicion/ARXOptimizer.h
new file mode 120000
index 0000000..33800ba
--- /dev/null
+++ b/External/Include/Auspicion/ARXOptimizer.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/ARXOptimizer.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXPointerType.h b/External/Include/Auspicion/ARXPointerType.h
new file mode 120000
index 0000000..7a49088
--- /dev/null
+++ b/External/Include/Auspicion/ARXPointerType.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Type/ARXPointerType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXPointerValue.h b/External/Include/Auspicion/ARXPointerValue.h
new file mode 120000
index 0000000..a488a8a
--- /dev/null
+++ b/External/Include/Auspicion/ARXPointerValue.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/ARXPointerValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXStructureType.h b/External/Include/Auspicion/ARXStructureType.h
new file mode 120000
index 0000000..cfc64ce
--- /dev/null
+++ b/External/Include/Auspicion/ARXStructureType.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Type/ARXStructureType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXStructureValue.h b/External/Include/Auspicion/ARXStructureValue.h
new file mode 120000
index 0000000..77c47bf
--- /dev/null
+++ b/External/Include/Auspicion/ARXStructureValue.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/ARXStructureValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXType+Protected.h b/External/Include/Auspicion/ARXType+Protected.h
new file mode 120000
index 0000000..b99113c
--- /dev/null
+++ b/External/Include/Auspicion/ARXType+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Type/ARXType+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXType.h b/External/Include/Auspicion/ARXType.h
new file mode 120000
index 0000000..b9908fc
--- /dev/null
+++ b/External/Include/Auspicion/ARXType.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Type/ARXType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXValue+Protected.h b/External/Include/Auspicion/ARXValue+Protected.h
new file mode 120000
index 0000000..68c7ce7
--- /dev/null
+++ b/External/Include/Auspicion/ARXValue+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/ARXValue+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/ARXValue.h b/External/Include/Auspicion/ARXValue.h
new file mode 120000
index 0000000..d88ca8d
--- /dev/null
+++ b/External/Include/Auspicion/ARXValue.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/ARXValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMBlock.h b/External/Include/Auspicion/LLVMBlock.h
deleted file mode 120000
index 7501027..0000000
--- a/External/Include/Auspicion/LLVMBlock.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMBlock.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMBooleanValue.h b/External/Include/Auspicion/LLVMBooleanValue.h
deleted file mode 120000
index 7f98253..0000000
--- a/External/Include/Auspicion/LLVMBooleanValue.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Values/LLVMBooleanValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMBuilder.h b/External/Include/Auspicion/LLVMBuilder.h
deleted file mode 120000
index 3d8df8d..0000000
--- a/External/Include/Auspicion/LLVMBuilder.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMBuilder.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMCompiler.h b/External/Include/Auspicion/LLVMCompiler.h
deleted file mode 120000
index 62d0f5f..0000000
--- a/External/Include/Auspicion/LLVMCompiler.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMCompiler.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteBlock.h b/External/Include/Auspicion/LLVMConcreteBlock.h
deleted file mode 120000
index 58a6cbc..0000000
--- a/External/Include/Auspicion/LLVMConcreteBlock.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteBlock.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteBuilder.h b/External/Include/Auspicion/LLVMConcreteBuilder.h
deleted file mode 120000
index c5c7532..0000000
--- a/External/Include/Auspicion/LLVMConcreteBuilder.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteBuilder.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteCompiler.h b/External/Include/Auspicion/LLVMConcreteCompiler.h
deleted file mode 120000
index 31f755b..0000000
--- a/External/Include/Auspicion/LLVMConcreteCompiler.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteCompiler.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteContext.h b/External/Include/Auspicion/LLVMConcreteContext.h
deleted file mode 120000
index e9ea6aa..0000000
--- a/External/Include/Auspicion/LLVMConcreteContext.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteContext.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteFunction.h b/External/Include/Auspicion/LLVMConcreteFunction.h
deleted file mode 120000
index cf17259..0000000
--- a/External/Include/Auspicion/LLVMConcreteFunction.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteFunction.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteModule.h b/External/Include/Auspicion/LLVMConcreteModule.h
deleted file mode 120000
index d5636d7..0000000
--- a/External/Include/Auspicion/LLVMConcreteModule.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteModule.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteOptimizer.h b/External/Include/Auspicion/LLVMConcreteOptimizer.h
deleted file mode 120000
index ad2bb26..0000000
--- a/External/Include/Auspicion/LLVMConcreteOptimizer.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteOptimizer.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMContext.h b/External/Include/Auspicion/LLVMContext.h
deleted file mode 120000
index a27d35d..0000000
--- a/External/Include/Auspicion/LLVMContext.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMContext.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMFunction+Protected.h b/External/Include/Auspicion/LLVMFunction+Protected.h
deleted file mode 120000
index 0c28d12..0000000
--- a/External/Include/Auspicion/LLVMFunction+Protected.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Values/LLVMFunction+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMFunction.h b/External/Include/Auspicion/LLVMFunction.h
deleted file mode 120000
index c705cc2..0000000
--- a/External/Include/Auspicion/LLVMFunction.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Values/LLVMFunction.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMFunctionBuilder.h b/External/Include/Auspicion/LLVMFunctionBuilder.h
deleted file mode 120000
index c829e4f..0000000
--- a/External/Include/Auspicion/LLVMFunctionBuilder.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMFunctionBuilder.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMFunctionType.h b/External/Include/Auspicion/LLVMFunctionType.h
deleted file mode 120000
index 5c7ce4d..0000000
--- a/External/Include/Auspicion/LLVMFunctionType.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Type/LLVMFunctionType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMModule+Protected.h b/External/Include/Auspicion/LLVMModule+Protected.h
deleted file mode 120000
index 317d008..0000000
--- a/External/Include/Auspicion/LLVMModule+Protected.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMModule+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMModule.h b/External/Include/Auspicion/LLVMModule.h
deleted file mode 120000
index 6de00ae..0000000
--- a/External/Include/Auspicion/LLVMModule.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMModule.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMOptimizer.h b/External/Include/Auspicion/LLVMOptimizer.h
deleted file mode 120000
index d432ac0..0000000
--- a/External/Include/Auspicion/LLVMOptimizer.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMOptimizer.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMPointerValue.h b/External/Include/Auspicion/LLVMPointerValue.h
deleted file mode 120000
index da0df8b..0000000
--- a/External/Include/Auspicion/LLVMPointerValue.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Values/LLVMPointerValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMStructureType.h b/External/Include/Auspicion/LLVMStructureType.h
deleted file mode 120000
index 18f50a9..0000000
--- a/External/Include/Auspicion/LLVMStructureType.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Type/LLVMStructureType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMStructureValue.h b/External/Include/Auspicion/LLVMStructureValue.h
deleted file mode 120000
index 5e46274..0000000
--- a/External/Include/Auspicion/LLVMStructureValue.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Values/LLVMStructureValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMType+Protected.h b/External/Include/Auspicion/LLVMType+Protected.h
deleted file mode 120000
index ee2e1f5..0000000
--- a/External/Include/Auspicion/LLVMType+Protected.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Type/LLVMType+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMType.h b/External/Include/Auspicion/LLVMType.h
deleted file mode 120000
index 6b7b6b6..0000000
--- a/External/Include/Auspicion/LLVMType.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Type/LLVMType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMValue+Protected.h b/External/Include/Auspicion/LLVMValue+Protected.h
deleted file mode 120000
index 9d00fa4..0000000
--- a/External/Include/Auspicion/LLVMValue+Protected.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Values/LLVMValue+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMValue.h b/External/Include/Auspicion/LLVMValue.h
deleted file mode 120000
index d9dc89e..0000000
--- a/External/Include/Auspicion/LLVMValue.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/Values/LLVMValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/NSObject+UniqueFactory.h b/External/Include/Auspicion/NSObject+UniqueFactory.h
new file mode 120000
index 0000000..007ee23
--- /dev/null
+++ b/External/Include/Auspicion/NSObject+UniqueFactory.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/NSObject+UniqueFactory.h
\ No newline at end of file
diff --git a/Other Sources/bootstrap-hammerc.m b/Other Sources/bootstrap-hammerc.m
index 1b37f9b..5b351ac 100644
--- a/Other Sources/bootstrap-hammerc.m
+++ b/Other Sources/bootstrap-hammerc.m
@@ -1,27 +1,27 @@
// bootstrap-hammerc.m
// Created by Rob Rix on 2010-03-03
// Copyright 2010 Monochrome Industries
#import <Foundation/Foundation.h>
#import <Hammer/Hammer.h>
#import "HammerRuleCompiler.h"
int main(int argc, const char *argv[]) {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
HammerRuleGraphRef grammar = [HammerBuilder grammarRuleGraph];
HammerRuleCompiler *compiler = [[HammerRuleCompiler alloc] init];
for(NSString *ruleName in grammar) {
HammerRuleRef rule = HammerRuleGraphGetRuleForName(grammar, ruleName);
HammerRuleRef compiledRule = [compiler compileRule: rule];
}
// the rules shouldnât be JITed, they should just be outputâhow?
// then they should actually be assembled via llc?
// where does optimization come in?
- [pool drain];
+ // [pool drain];
return 0;
}
diff --git a/Other Sources/hammerc.m b/Other Sources/hammerc.m
index e9ce70d..d7ef36c 100644
--- a/Other Sources/hammerc.m
+++ b/Other Sources/hammerc.m
@@ -1,14 +1,14 @@
// hammerc.m
// Created by Rob Rix on 2010-03-03
// Copyright 2010 Monochrome Industries
#import <Foundation/Foundation.h>
int main(int argc, const char *argv[]) {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- [pool drain];
+ // [pool drain];
return 0;
}
diff --git a/README.mdown b/README.mdown
index 8b5979f..1b3c220 100644
--- a/README.mdown
+++ b/README.mdown
@@ -1,5 +1,5 @@
#hammerc
A compiler for [Hammer](http://github.com/robrix/Hammer) using [Auspicion](http://github.com/robrix/Auspicion) for most of the heavy lifting.
-Not yet working as such, but [not without its perks](http://github.com/robrix/hammerc/blob/master/Categories/LLVMType%2BRuntimeTypeEncodings.m).
\ No newline at end of file
+Not yet working as such, but [not without its perks](http://github.com/robrix/hammerc/blob/master/Categories/ARXType%2BRuntimeTypeEncodings.m).
\ No newline at end of file
diff --git a/Resources/Tests-Info.plist b/Resources/Tests-Info.plist
index c285a47..4e37ebe 100644
--- a/Resources/Tests-Info.plist
+++ b/Resources/Tests-Info.plist
@@ -1,22 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
- <string>com.yourcompany.${PRODUCT_NAME:rfc1034identifier}</string>
+ <string>com.monochromeindustries.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
diff --git a/Tasks.taskpaper b/Tasks.taskpaper
index 4b035a2..7d855fc 100644
--- a/Tasks.taskpaper
+++ b/Tasks.taskpaper
@@ -1,9 +1,18 @@
-- write a parser for `@encode()` directive strings.
-- provide JIT-compiled implementations of the match methods for rules, written in Auspicion. Use those in Hammer, and use them in hammerc as the components of the static compilation.
- Is that even possible, i.e. resolving function calls and replacing them with static ones?
-- inline everything.
+Compiler:
+ - write a parser for `@encode()` directive strings. @done(2010-06-14)
+ - provide JIT-compiled implementations of the match methods for rules, written in Auspicion. Use those in Hammer, and use them in hammerc as the components of the static compilation.
+ Is that even possible, i.e. resolving function calls and replacing them with static ones?
+ - inline everything.
+ - compile the rule graph rather than just individual rules.
+ - replace reference rules with the (compiled) rules they reference.
+ - build functions for the clients to call:
+ - rule graph (parser) initialization
+ - calls -initializeDataFor<rule>: on each rule
+ - parse
+ - free
+ - frees the globals created in -initializeDataFor<rule>:.
Tools:
- Xcode plugin with a build rule for .grammar files.
- header generator.
- Generation Gap builder scaffold tool (like mogenerator but based on a grammar).
diff --git a/Tests/HammerCompiledReferenceRuleTests.m b/Tests/HammerCompiledReferenceRuleTests.m
index b1c27bf..439908e 100644
--- a/Tests/HammerCompiledReferenceRuleTests.m
+++ b/Tests/HammerCompiledReferenceRuleTests.m
@@ -1,30 +1,29 @@
// HammerCompiledReferenceRuleTests.m
// Created by Rob Rix on 2010-01-30
// Copyright 2010 Monochrome Industries
#import "HammerCharacterRule.h"
#import "HammerConcatenationRule.h"
#import "HammerReferenceRule.h"
#import "HammerReferenceRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledReferenceRuleTests : HammerReferenceRuleTests
@end
@implementation HammerCompiledReferenceRuleTests
-(HammerRuleRef)rule {
return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
-(void)setUp {
[super setUp];
HammerRuleCompiler *compiler = [[HammerRuleCompiler alloc] init];
state.ruleGraph = (HammerRuleGraphRef)RXDictionary(
[compiler compileRule: HammerCharacterRuleCreate()], @"any",
[compiler compileRule: HammerConcatenationRuleCreate(RXArray(HammerReferenceRuleCreate(@"any"), HammerReferenceRuleCreate(@"any"), NULL))], @"anyTwo",
NULL);
- [compiler release];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerRuleCompilerTests.m b/Tests/HammerRuleCompilerTests.m
index 6d77227..7102b12 100644
--- a/Tests/HammerRuleCompilerTests.m
+++ b/Tests/HammerRuleCompilerTests.m
@@ -1,36 +1,32 @@
// HammerRuleCompilerTests.m
// Created by Rob Rix on 2009-12-11
// Copyright 2009 Monochrome Industries
#import "Hammer.h"
#import "HammerRuleCompiler.h"
#import "RXAssertions.h"
@interface HammerRuleCompilerTests : SenTestCase {
HammerRuleCompiler *compiler;
}
@end
@implementation HammerRuleCompilerTests
-(void)setUp {
compiler = [[HammerRuleCompiler alloc] init];
}
--(void)tearDown {
- [compiler release];
-}
-
// rule functionality is tested in HammerCompiled*RuleTests suites
-(void)testCompilesCharacterRules {
HammerRuleRef compiledRule = [compiler compileRule: HammerCharacterRuleCreate()];
RXAssertNotNil(compiledRule);
}
-(void)testCompilesLiteralRules {
HammerRuleRef compiledRule = [compiler compileRule: HammerLiteralRuleCreate(@"literal")];
RXAssertNotNil(compiledRule);
}
@end
\ No newline at end of file
diff --git a/hammerc.xcodeproj/project.pbxproj b/hammerc.xcodeproj/project.pbxproj
index 8e5fe2b..a51d771 100644
--- a/hammerc.xcodeproj/project.pbxproj
+++ b/hammerc.xcodeproj/project.pbxproj
@@ -1,1063 +1,1073 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 45;
objects = {
/* Begin PBXBuildFile section */
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859EA3029092ED04C91782 /* hammerc.1 */; };
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */; };
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */; };
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */; };
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */; };
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */; };
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */; };
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */; };
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */; };
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */; };
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */; };
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */; };
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E51113F5FEF0086F21C /* hammerc.m */; };
D4551E82113F85830086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EBA113F88300086F21C /* bootstrap-hammerc.m */; };
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551EE3113F88700086F21C /* digit.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC3113F88700086F21C /* digit.grammar */; };
D4551EE4113F88700086F21C /* letter.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC4113F88700086F21C /* letter.grammar */; };
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */; };
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC7113F88700086F21C /* HammerBuilderTests.m */; };
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */; };
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */; };
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */; };
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */; };
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */; };
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */; };
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */; };
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */; };
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */; };
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */; };
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDE113F88700086F21C /* HammerRuleTests.m */; };
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */; };
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EF7113F88A00086F21C /* Hammer.grammar */; };
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
- D48B23EB11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */; };
- D48B23EC11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */; };
- D48B23ED11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */; };
- D48B23EE11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */; };
+ D48B23EB11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
+ D48B23EC11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
+ D48B23ED11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
+ D48B23EE11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B24BC11B25720007CBBB4 /* RXAssertions.m */; };
D4D74F1511C38023002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F1611C38031002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F1711C38034002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
D4D74F2411C3817B002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
D4D74F2511C38195002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
D4D74F2611C38196002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
- D4D74F3011C38209002FF2F1 /* LLVMModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */; };
- D4D74F3111C3820E002FF2F1 /* LLVMType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */; };
+ D4D74F3011C38209002FF2F1 /* ARXModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */; };
+ D4D74F3111C3820E002FF2F1 /* ARXType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */; };
+ D4D750E211C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
+ D4D750E311C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
+ D4D750FF11C3D8E8002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D4551DFE113E48B20086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
proxyType = 1;
remoteGlobalIDString = D4551DF9113E48A90086F21C;
remoteInfo = "bootstrap-hammerc";
};
D4551E7A113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4041AB1113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D4551E7E113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4DB11D60D138C7400C730A3;
remoteInfo = Tests;
};
D4551E80113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D404EB4610F5791C007612E9;
remoteInfo = "Measure Performance";
};
D4551E9C113F85D70086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D2AAC046055464E500DB518D;
remoteInfo = Polymorph;
};
D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4AB04351180335A0048BBA1;
remoteInfo = Tests;
};
D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D2AAC07E0554694100DB518D;
remoteInfo = RXAssertions;
};
D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D442A488106FD94900944F07;
remoteInfo = Tests;
};
D4D74F0B11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D2AAC07E0554694100DB518D /* libAuspicion.a */;
+ remoteGlobalIDString = D2AAC07E0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4D74F0D11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D4D9DE5510EB5F4F003EEE90 /* libAuspicionLLVM.a */;
+ remoteGlobalIDString = D4D9DE5510EB5F4F003EEE90;
remoteInfo = AuspicionLLVM;
};
D4D74F0F11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D4CF603311C32F8000C9DD15 /* Tests.octest */;
+ remoteGlobalIDString = D4CF603311C32F8000C9DD15;
remoteInfo = Tests;
};
D4D74F1111C38010002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 1;
- remoteGlobalIDString = D2AAC07D0554694100DB518D /* Auspicion (Static Library) */;
+ remoteGlobalIDString = D2AAC07D0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4D74F1311C3801B002FF2F1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
proxyType = 1;
- remoteGlobalIDString = D2AAC07D0554694100DB518D /* Auspicion (Static Library) */;
+ remoteGlobalIDString = D2AAC07D0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
8DD76F9E0486AA7600D96B5E /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 8;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
8DD76FA10486AA7600D96B5E /* hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = hammerc; sourceTree = BUILT_PRODUCTS_DIR; };
C6859EA3029092ED04C91782 /* hammerc.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = hammerc.1; sourceTree = "<group>"; };
D4551DFA113E48A90086F21C /* bootstrap-hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "bootstrap-hammerc"; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E28113F5F6D0086F21C /* Tests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Tests.octest; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E29113F5F6D0086F21C /* Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Tests-Info.plist"; sourceTree = "<group>"; };
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledAlternationRuleTests.m; sourceTree = "<group>"; };
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterRuleTests.m; sourceTree = "<group>"; };
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralRuleTests.m; sourceTree = "<group>"; };
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledNamedRuleTests.m; sourceTree = "<group>"; };
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledReferenceRuleTests.m; sourceTree = "<group>"; };
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompilerTests.m; sourceTree = "<group>"; };
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCompiledRule.h; sourceTree = "<group>"; };
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRule.m; sourceTree = "<group>"; };
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleCompiler.h; sourceTree = "<group>"; };
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompiler.m; sourceTree = "<group>"; };
D4551E51113F5FEF0086F21C /* hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = hammerc.m; sourceTree = "<group>"; };
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hammerc_Prefix.pch; sourceTree = "<group>"; };
D4551E6E113F85780086F21C /* Hammer.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Hammer.xcodeproj; sourceTree = "<group>"; };
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "bootstrap-hammerc.m"; sourceTree = "<group>"; };
D4551EC3113F88700086F21C /* digit.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = digit.grammar; sourceTree = "<group>"; };
D4551EC4113F88700086F21C /* letter.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = letter.grammar; sourceTree = "<group>"; };
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerAlternationRuleTests.h; sourceTree = "<group>"; };
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerAlternationRuleTests.m; sourceTree = "<group>"; };
D4551EC7113F88700086F21C /* HammerBuilderTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerBuilderTests.m; sourceTree = "<group>"; };
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterRuleTests.h; sourceTree = "<group>"; };
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterRuleTests.m; sourceTree = "<group>"; };
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterSetRuleTests.h; sourceTree = "<group>"; };
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerContainerRuleTests.m; sourceTree = "<group>"; };
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralRuleTests.h; sourceTree = "<group>"; };
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralRuleTests.m; sourceTree = "<group>"; };
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLookaheadRuleTests.h; sourceTree = "<group>"; };
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerNamedRuleTests.h; sourceTree = "<group>"; };
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerNamedRuleTests.m; sourceTree = "<group>"; };
D4551ED7113F88700086F21C /* HammerParserTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerParserTests.m; sourceTree = "<group>"; };
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerReferenceRuleTests.h; sourceTree = "<group>"; };
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerReferenceRuleTests.m; sourceTree = "<group>"; };
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRepetitionRuleTests.h; sourceTree = "<group>"; };
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRulePrinterTests.m; sourceTree = "<group>"; };
D4551EDD113F88700086F21C /* HammerRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleTests.h; sourceTree = "<group>"; };
D4551EDE113F88700086F21C /* HammerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleTests.m; sourceTree = "<group>"; };
D4551EDF113F88700086F21C /* HammerTestParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestParser.h; sourceTree = "<group>"; };
D4551EE0113F88700086F21C /* HammerTestParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestParser.m; sourceTree = "<group>"; };
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestRuleVisitor.h; sourceTree = "<group>"; };
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestRuleVisitor.m; sourceTree = "<group>"; };
D4551EF7113F88A00086F21C /* Hammer.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = Hammer.grammar; path = "../Other Sources/Hammer.grammar"; sourceTree = "<group>"; };
- D48B23E711B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "LLVMModule+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
- D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "LLVMModule+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
- D48B23E911B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "LLVMType+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
- D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "LLVMType+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
+ D48B23E711B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARXModule+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
+ D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "ARXModule+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
+ D48B23E911B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARXType+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
+ D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "ARXType+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
D48B247911B25720007CBBB4 /* RXAllocation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAllocation.h; sourceTree = "<group>"; };
D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXCoreFoundationIntegration.h; sourceTree = "<group>"; };
D48B247D11B25720007CBBB4 /* RXObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObject.h; sourceTree = "<group>"; };
D48B248011B25720007CBBB4 /* RXObjectType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObjectType.h; sourceTree = "<group>"; };
D48B248111B25720007CBBB4 /* RXShadowObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXShadowObject.h; sourceTree = "<group>"; };
D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Polymorph.xcodeproj; sourceTree = "<group>"; };
D48B24BB11B25720007CBBB4 /* RXAssertions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAssertions.h; sourceTree = "<group>"; };
D48B24BC11B25720007CBBB4 /* RXAssertions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RXAssertions.m; sourceTree = "<group>"; };
D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = RXAssertions.xcodeproj; sourceTree = "<group>"; };
D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Auspicion.xcodeproj; sourceTree = "<group>"; };
D4D74F2211C3817B002FF2F1 /* NSObject+UniqueFactory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSObject+UniqueFactory.h"; path = "Classes/NSObject+UniqueFactory.h"; sourceTree = "<group>"; };
D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSObject+UniqueFactory.m"; path = "Classes/NSObject+UniqueFactory.m"; sourceTree = "<group>"; };
+ D4D750E011C3BE90002FF2F1 /* HammerRuleCompilerVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleCompilerVisitor.h; sourceTree = "<group>"; };
+ D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompilerVisitor.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
8DD76F9B0486AA7600D96B5E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1611C38031002FF2F1 /* libAuspicion.a in Frameworks */,
D4551E82113F85830086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF8113E48A90086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1711C38034002FF2F1 /* libAuspicion.a in Frameworks */,
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E25113F5F6D0086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4D74F1511C38023002FF2F1 /* libAuspicion.a in Frameworks */,
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
08FB7794FE84155DC02AAC07 /* hammerc */ = {
isa = PBXGroup;
children = (
D48B23E611B24D5E007CBBB4 /* Categories */,
08FB7795FE84155DC02AAC07 /* Classes */,
D4551E50113F5FEF0086F21C /* Other Sources */,
D4551E30113F5FB10086F21C /* Tests */,
C6859EA2029092E104C91782 /* Documentation */,
D4551E6B113F85410086F21C /* External */,
D4551E2F113F5F7D0086F21C /* Resources */,
1AB674ADFE9D54B511CA2CBB /* Products */,
);
name = hammerc;
sourceTree = "<group>";
};
08FB7795FE84155DC02AAC07 /* Classes */ = {
isa = PBXGroup;
children = (
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */,
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */,
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */,
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */,
+ D4D750E011C3BE90002FF2F1 /* HammerRuleCompilerVisitor.h */,
+ D4D750E111C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m */,
);
path = Classes;
sourceTree = "<group>";
};
1AB674ADFE9D54B511CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
8DD76FA10486AA7600D96B5E /* hammerc */,
D4551DFA113E48A90086F21C /* bootstrap-hammerc */,
D4551E28113F5F6D0086F21C /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
C6859EA2029092E104C91782 /* Documentation */ = {
isa = PBXGroup;
children = (
C6859EA3029092ED04C91782 /* hammerc.1 */,
);
path = Documentation;
sourceTree = "<group>";
};
D4551E2F113F5F7D0086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551E29113F5F6D0086F21C /* Tests-Info.plist */,
);
path = Resources;
sourceTree = "<group>";
};
D4551E30113F5FB10086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */,
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */,
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */,
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */,
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */,
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */,
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */,
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */,
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */,
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */,
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551E50113F5FEF0086F21C /* Other Sources */ = {
isa = PBXGroup;
children = (
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */,
D4551E51113F5FEF0086F21C /* hammerc.m */,
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */,
);
path = "Other Sources";
sourceTree = "<group>";
};
D4551E6B113F85410086F21C /* External */ = {
isa = PBXGroup;
children = (
D4551E6D113F855E0086F21C /* Auspicion */,
D4551E6C113F85530086F21C /* Hammer */,
);
path = External;
sourceTree = "<group>";
};
D4551E6C113F85530086F21C /* Hammer */ = {
isa = PBXGroup;
children = (
D4551E6E113F85780086F21C /* Hammer.xcodeproj */,
D48B244C11B25720007CBBB4 /* External */,
D4551EF6113F88930086F21C /* Resources */,
D4551EC1113F88700086F21C /* Tests */,
);
path = Hammer;
sourceTree = "<group>";
};
D4551E6D113F855E0086F21C /* Auspicion */ = {
isa = PBXGroup;
children = (
D4D74F2211C3817B002FF2F1 /* NSObject+UniqueFactory.h */,
D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */,
D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */,
);
path = Auspicion;
sourceTree = "<group>";
};
D4551E6F113F85780086F21C /* Products */ = {
isa = PBXGroup;
children = (
D4551E7B113F85780086F21C /* libHammer.a */,
D4551E7F113F85780086F21C /* Tests.octest */,
D4551E81113F85780086F21C /* Measure Performance */,
);
name = Products;
sourceTree = "<group>";
};
D4551EC1113F88700086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551EC2113F88700086F21C /* Fixtures */,
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */,
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */,
D4551EC7113F88700086F21C /* HammerBuilderTests.m */,
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */,
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */,
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */,
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */,
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */,
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */,
D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */,
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */,
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */,
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */,
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */,
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */,
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */,
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */,
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */,
D4551ED7113F88700086F21C /* HammerParserTests.m */,
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */,
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */,
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */,
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */,
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */,
D4551EDD113F88700086F21C /* HammerRuleTests.h */,
D4551EDE113F88700086F21C /* HammerRuleTests.m */,
D4551EDF113F88700086F21C /* HammerTestParser.h */,
D4551EE0113F88700086F21C /* HammerTestParser.m */,
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */,
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551EC2113F88700086F21C /* Fixtures */ = {
isa = PBXGroup;
children = (
D4551EC3113F88700086F21C /* digit.grammar */,
D4551EC4113F88700086F21C /* letter.grammar */,
);
path = Fixtures;
sourceTree = "<group>";
};
D4551EF6113F88930086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551EF7113F88A00086F21C /* Hammer.grammar */,
);
path = Resources;
sourceTree = "<group>";
};
D48B23E611B24D5E007CBBB4 /* Categories */ = {
isa = PBXGroup;
children = (
- D48B23E711B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.h */,
- D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */,
- D48B23E911B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.h */,
- D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */,
+ D48B23E711B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.h */,
+ D48B23E811B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m */,
+ D48B23E911B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.h */,
+ D48B23EA11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m */,
);
path = Categories;
sourceTree = "<group>";
};
D48B244C11B25720007CBBB4 /* External */ = {
isa = PBXGroup;
children = (
D48B244D11B25720007CBBB4 /* Polymorph */,
D48B249111B25720007CBBB4 /* RXAssertions */,
);
path = External;
sourceTree = "<group>";
};
D48B244D11B25720007CBBB4 /* Polymorph */ = {
isa = PBXGroup;
children = (
D48B247811B25720007CBBB4 /* Classes */,
D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */,
);
path = Polymorph;
sourceTree = "<group>";
};
D48B247811B25720007CBBB4 /* Classes */ = {
isa = PBXGroup;
children = (
D48B247911B25720007CBBB4 /* RXAllocation.h */,
D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */,
D48B247D11B25720007CBBB4 /* RXObject.h */,
D48B248011B25720007CBBB4 /* RXObjectType.h */,
D48B248111B25720007CBBB4 /* RXShadowObject.h */,
);
path = Classes;
sourceTree = "<group>";
};
D48B248B11B25720007CBBB4 /* Products */ = {
isa = PBXGroup;
children = (
D48B24E211B25721007CBBB4 /* libPolymorph.a */,
D48B24E411B25721007CBBB4 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
D48B249111B25720007CBBB4 /* RXAssertions */ = {
isa = PBXGroup;
children = (
D48B24BB11B25720007CBBB4 /* RXAssertions.h */,
D48B24BC11B25720007CBBB4 /* RXAssertions.m */,
D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */,
);
path = RXAssertions;
sourceTree = "<group>";
};
D48B24BF11B25720007CBBB4 /* Products */ = {
isa = PBXGroup;
children = (
D48B24EB11B25721007CBBB4 /* libRXAssertions.a */,
D48B24ED11B25721007CBBB4 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
D4D74F0611C37FFC002FF2F1 /* Products */ = {
isa = PBXGroup;
children = (
D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */,
D4D74F0E11C37FFC002FF2F1 /* libAuspicionLLVM.a */,
D4D74F1011C37FFC002FF2F1 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
8DD76F960486AA7600D96B5E /* hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */;
buildPhases = (
8DD76F990486AA7600D96B5E /* Sources */,
8DD76F9B0486AA7600D96B5E /* Frameworks */,
8DD76F9E0486AA7600D96B5E /* CopyFiles */,
);
buildRules = (
);
dependencies = (
D4551DFF113E48B20086F21C /* PBXTargetDependency */,
);
name = hammerc;
productInstallPath = "$(HOME)/bin";
productName = hammerc;
productReference = 8DD76FA10486AA7600D96B5E /* hammerc */;
productType = "com.apple.product-type.tool";
};
D4551DF9113E48A90086F21C /* bootstrap-hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */;
buildPhases = (
D4551DF7113E48A90086F21C /* Sources */,
D4551DF8113E48A90086F21C /* Frameworks */,
);
buildRules = (
);
dependencies = (
D4551E9D113F85D70086F21C /* PBXTargetDependency */,
D4D74F1211C38010002FF2F1 /* PBXTargetDependency */,
);
name = "bootstrap-hammerc";
productName = "bootstrap-hammerc";
productReference = D4551DFA113E48A90086F21C /* bootstrap-hammerc */;
productType = "com.apple.product-type.tool";
};
D4551E27113F5F6D0086F21C /* Tests */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */;
buildPhases = (
D4551E24113F5F6D0086F21C /* Sources */,
D4551E23113F5F6D0086F21C /* Resources */,
D4551E25113F5F6D0086F21C /* Frameworks */,
D4551E26113F5F6D0086F21C /* ShellScript */,
);
buildRules = (
);
dependencies = (
D4551F00113F88CA0086F21C /* PBXTargetDependency */,
D4D74F1411C3801B002FF2F1 /* PBXTargetDependency */,
);
name = Tests;
productName = Tests;
productReference = D4551E28113F5F6D0086F21C /* Tests.octest */;
productType = "com.apple.product-type.bundle";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
08FB7793FE84155DC02AAC07 /* Project object */ = {
isa = PBXProject;
buildConfigurationList = 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */;
compatibilityVersion = "Xcode 3.1";
hasScannedForEncodings = 1;
mainGroup = 08FB7794FE84155DC02AAC07 /* hammerc */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = D4D74F0611C37FFC002FF2F1 /* Products */;
ProjectRef = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
},
{
ProductGroup = D4551E6F113F85780086F21C /* Products */;
ProjectRef = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
},
{
ProductGroup = D48B248B11B25720007CBBB4 /* Products */;
ProjectRef = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
},
{
ProductGroup = D48B24BF11B25720007CBBB4 /* Products */;
ProjectRef = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
},
);
projectRoot = "";
targets = (
8DD76F960486AA7600D96B5E /* hammerc */,
D4551DF9113E48A90086F21C /* bootstrap-hammerc */,
D4551E27113F5F6D0086F21C /* Tests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
D4551E7B113F85780086F21C /* libHammer.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libHammer.a;
remoteRef = D4551E7A113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E7F113F85780086F21C /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D4551E7E113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E81113F85780086F21C /* Measure Performance */ = {
isa = PBXReferenceProxy;
fileType = "compiled.mach-o.executable";
path = "Measure Performance";
remoteRef = D4551E80113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24E211B25721007CBBB4 /* libPolymorph.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libPolymorph.a;
remoteRef = D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24E411B25721007CBBB4 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24EB11B25721007CBBB4 /* libRXAssertions.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRXAssertions.a;
remoteRef = D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24ED11B25721007CBBB4 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libAuspicion.a;
remoteRef = D4D74F0B11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F0E11C37FFC002FF2F1 /* libAuspicionLLVM.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libAuspicionLLVM.a;
remoteRef = D4D74F0D11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4D74F1011C37FFC002FF2F1 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D4D74F0F11C37FFC002FF2F1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
D4551E23113F5F6D0086F21C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551EE3113F88700086F21C /* digit.grammar in Resources */,
D4551EE4113F88700086F21C /* letter.grammar in Resources */,
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
D4551E26113F5F6D0086F21C /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
8DD76F990486AA7600D96B5E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */,
- D48B23ED11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */,
- D48B23EE11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */,
+ D48B23ED11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
+ D48B23EE11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */,
D4D74F2611C38196002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
+ D4D750E311C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF7113E48A90086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */,
- D48B23EB11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */,
- D48B23EC11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */,
+ D48B23EB11B24D5E007CBBB4 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
+ D48B23EC11B24D5E007CBBB4 /* ARXType+RuntimeTypeEncodings.m in Sources */,
D4D74F2511C38195002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
+ D4D750E211C3BE90002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E24113F5F6D0086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */,
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */,
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */,
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */,
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */,
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */,
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */,
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */,
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */,
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */,
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */,
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */,
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */,
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */,
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */,
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */,
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */,
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */,
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */,
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */,
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */,
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */,
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */,
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */,
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */,
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */,
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */,
D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */,
D4D74F2411C3817B002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
- D4D74F3011C38209002FF2F1 /* LLVMModule+RuntimeTypeEncodings.m in Sources */,
- D4D74F3111C3820E002FF2F1 /* LLVMType+RuntimeTypeEncodings.m in Sources */,
+ D4D74F3011C38209002FF2F1 /* ARXModule+RuntimeTypeEncodings.m in Sources */,
+ D4D74F3111C3820E002FF2F1 /* ARXType+RuntimeTypeEncodings.m in Sources */,
+ D4D750FF11C3D8E8002FF2F1 /* HammerRuleCompilerVisitor.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D4551DFF113E48B20086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D4551DF9113E48A90086F21C /* bootstrap-hammerc */;
targetProxy = D4551DFE113E48B20086F21C /* PBXContainerItemProxy */;
};
D4551E9D113F85D70086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551E9C113F85D70086F21C /* PBXContainerItemProxy */;
};
D4551F00113F88CA0086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */;
};
D4D74F1211C38010002FF2F1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
targetProxy = D4D74F1111C38010002FF2F1 /* PBXContainerItemProxy */;
};
D4D74F1411C3801B002FF2F1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
targetProxy = D4D74F1311C3801B002FF2F1 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
1DEB927508733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_FIX_AND_CONTINUE = YES;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Debug;
};
1DEB927608733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_MODEL_TUNING = G5;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Release;
};
1DEB927908733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_GC = required;
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "External/Include/**";
ONLY_ACTIVE_ARCH = YES;
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = macosx10.6;
};
name = Debug;
};
1DEB927A08733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_GC = required;
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "External/Include/**";
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = macosx10.5;
};
name = Release;
};
D4551DFC113E48A90086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
};
name = Debug;
};
D4551DFD113E48A90086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_MODEL_TUNING = G5;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
};
name = Release;
};
D4551E2A113F5F6D0086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
FRAMEWORK_SEARCH_PATHS = "$(DEVELOPER_LIBRARY_DIR)/Frameworks";
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_MODEL_TUNING = G5;
GCC_OPTIMIZATION_LEVEL = 0;
INFOPLIST_FILE = "Resources/Tests-Info.plist";
INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles";
OTHER_CFLAGS = "-DHAMMERC_UNIT_TESTS";
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-framework",
SenTestingKit,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = Tests;
WRAPPER_EXTENSION = octest;
};
name = Debug;
};
D4551E2B113F5F6D0086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = "$(DEVELOPER_LIBRARY_DIR)/Frameworks";
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_MODEL_TUNING = G5;
INFOPLIST_FILE = "Resources/Tests-Info.plist";
INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles";
OTHER_CFLAGS = "-DHAMMERC_UNIT_TESTS";
OTHER_LDFLAGS = (
"$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-framework",
SenTestingKit,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = Tests;
WRAPPER_EXTENSION = octest;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB927508733DD40010E9CD /* Debug */,
1DEB927608733DD40010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB927908733DD40010E9CD /* Debug */,
1DEB927A08733DD40010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D4551DFC113E48A90086F21C /* Debug */,
D4551DFD113E48A90086F21C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D4551E2A113F5F6D0086F21C /* Debug */,
D4551E2B113F5F6D0086F21C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
}
|
robrix/hammerc
|
627520da3a3d158a862dfa9482c6bd2d0c946323
|
Added a README since github was kind enough to remind me.
|
diff --git a/README.mdown b/README.mdown
new file mode 100644
index 0000000..8b5979f
--- /dev/null
+++ b/README.mdown
@@ -0,0 +1,5 @@
+#hammerc
+
+A compiler for [Hammer](http://github.com/robrix/Hammer) using [Auspicion](http://github.com/robrix/Auspicion) for most of the heavy lifting.
+
+Not yet working as such, but [not without its perks](http://github.com/robrix/hammerc/blob/master/Categories/LLVMType%2BRuntimeTypeEncodings.m).
\ No newline at end of file
|
robrix/hammerc
|
f725bbcb139e341c01ab48f336fec3606a07a94c
|
Implemented parsing of ObjC types into LLVM types.
|
diff --git a/Categories/LLVMModule+RuntimeTypeEncodings.h b/Categories/LLVMModule+RuntimeTypeEncodings.h
index c6d289e..24aecc7 100644
--- a/Categories/LLVMModule+RuntimeTypeEncodings.h
+++ b/Categories/LLVMModule+RuntimeTypeEncodings.h
@@ -1,13 +1,13 @@
// LLVMModule+RuntimeTypeEncodings.h
// Created by Rob Rix on 2010-05-30
// Copyright 2010 Monochrome Industries
#import <Auspicion/Auspicion.h>
#define LLVMModuleImportType(module, type) [module setObjCType: @encode(type) forName: @#type]
@interface LLVMModule (LLVMModuleRuntimeTypeEncodings)
--(void)setObjCType:(const char *)type forName:(NSString *)name;
+-(LLVMType *)setObjCType:(const char *)type forName:(NSString *)name;
-@end
\ No newline at end of file
+@end
diff --git a/Categories/LLVMModule+RuntimeTypeEncodings.m b/Categories/LLVMModule+RuntimeTypeEncodings.m
index 64a81be..d1fc598 100644
--- a/Categories/LLVMModule+RuntimeTypeEncodings.m
+++ b/Categories/LLVMModule+RuntimeTypeEncodings.m
@@ -1,14 +1,16 @@
// LLVMModule+RuntimeTypeEncodings.m
// Created by Rob Rix on 2010-05-30
// Copyright 2010 Monochrome Industries
#import "LLVMModule+RuntimeTypeEncodings.h"
#import "LLVMType+RuntimeTypeEncodings.h"
@implementation LLVMModule (LLVMModuleRuntimeTypeEncodings)
--(void)setObjCType:(const char *)type forName:(NSString *)name {
- [self setType: [LLVMType typeForObjCType: type] forName: name];
+-(LLVMType *)setObjCType:(const char *)type forName:(NSString *)name {
+ LLVMType *result = [LLVMType typeForObjCType: type inModule: self];
+ [self setType: result forName: name];
+ return result;
}
-@end
\ No newline at end of file
+@end
diff --git a/Categories/LLVMType+RuntimeTypeEncodings.h b/Categories/LLVMType+RuntimeTypeEncodings.h
index 4aa49a1..b310f61 100644
--- a/Categories/LLVMType+RuntimeTypeEncodings.h
+++ b/Categories/LLVMType+RuntimeTypeEncodings.h
@@ -1,11 +1,11 @@
// LLVMType+RuntimeTypeEncodings.h
// Created by Rob Rix on 2010-05-30
// Copyright 2010 Monochrome Industries
#import <Auspicion/Auspicion.h>
@interface LLVMType (LLVMTypeRuntimeTypeEncodings)
-+(LLVMType *)typeForObjCType:(const char *)type;
++(LLVMType *)typeForObjCType:(const char *)type inModule:(LLVMModule *)module;
-@end
\ No newline at end of file
+@end
diff --git a/Categories/LLVMType+RuntimeTypeEncodings.m b/Categories/LLVMType+RuntimeTypeEncodings.m
index 4b3eb25..ecd3b07 100644
--- a/Categories/LLVMType+RuntimeTypeEncodings.m
+++ b/Categories/LLVMType+RuntimeTypeEncodings.m
@@ -1,13 +1,158 @@
// LLVMType+RuntimeTypeEncodings.m
// Created by Rob Rix on 2010-05-30
// Copyright 2010 Monochrome Industries
#import "LLVMType+RuntimeTypeEncodings.h"
+static NSString * const HammerCObjCTypeEncodingGrammar =
+ @"char = [cC];\n"
+ @"short = [sS];\n"
+ @"int = [iI];\n"
+ @"long = [lL];\n"
+ @"longLong = [qQ];\n"
+ @"float = 'f';\n"
+ @"double = 'd';\n"
+ @"bool = 'B';\n"
+ @"void = 'v';\n"
+ @"string = '*';\n"
+ @"object = '@';\n"
+ @"class = '#';\n"
+ @"selector = ':';\n"
+ @"array = '[' (count = [\\d]+) type ']';\n"
+ @"struct = '{' (name = [\\w]+) ('=' type*)? '}';\n"
+ @"union = '(' (name = [\\w]+) ('=' type*)? ')';\n"
+ @"bitfield = 'b' (width = [\\d]+);\n"
+ @"pointer = '^' type;\n"
+ @"unknown = '?';\n"
+ @"type = char | short | int | long | longLong | float | double | bool | void | string | object | class | selector | array | struct | union | bitfield | pointer | unknown;\n"
+ @"main = type+;\n"
+;
+
+@interface HammerCTypeBuilder : NSObject <HammerBuilder> {
+ LLVMType *resultType;
+ LLVMModule *module;
+ LLVMContext *context;
+}
+
+-(LLVMType *)typeForObjCType:(const char *)type inModule:(LLVMModule *)module;
+
+@end
+
@implementation LLVMType (LLVMTypeRuntimeTypeEncodings)
-+(LLVMType *)typeForObjCType:(const char *)type {
- // HammerRuleGraphRef ruleGraph = HammerRuleGraph
++(LLVMType *)typeForObjCType:(const char *)type inModule:(LLVMModule *)module {
+ return [[[[HammerCTypeBuilder alloc] init] autorelease] typeForObjCType: type inModule: module];
+}
+
+@end
+
+
+@implementation HammerCTypeBuilder
+
+-(LLVMType *)typeForObjCType:(const char *)type inModule:(LLVMModule *)_module {
+ module = [_module retain];
+ context = module.context;
+ HammerRuleGraphRef ruleGraph = HammerRuleGraphCreateWithGrammar(HammerCObjCTypeEncodingGrammar, nil, NULL);
+ NSError *error = nil;
+ if(!HammerRuleGraphParseString(ruleGraph, [NSString stringWithUTF8String: type], self, &error)) {
+ NSLog(@"Error parsing ObjC type '%s': %@ %@", type, error.localizedDescription, error.userInfo);
+ }
+ [module release];
+ return resultType;
+}
+
+
+-(LLVMType *)charRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType int8TypeInContext: context];
+}
+
+-(LLVMType *)shortRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType int16TypeInContext: context];
+}
+
+-(LLVMType *)intRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType int32TypeInContext: context];
+}
+
+-(LLVMType *)longRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType int32TypeInContext: context];
+}
+
+-(LLVMType *)longLongRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType int64TypeInContext: context];
+}
+
+-(LLVMType *)floatRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType floatTypeInContext: context];
+}
+
+-(LLVMType *)doubleRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType doubleTypeInContext: context];
+}
+
+-(LLVMType *)boolRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType int1TypeInContext: context];
+}
+
+-(LLVMType *)voidRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType voidTypeInContext: context];
+}
+
+-(LLVMType *)stringRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType pointerTypeToType: [LLVMType int8TypeInContext: context]];
+}
+
+-(LLVMType *)objectRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType pointerTypeToType: [LLVMType int8TypeInContext: context]];
+}
+
+-(LLVMType *)classRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType pointerTypeToType: [LLVMType int8TypeInContext: context]];
+}
+
+-(LLVMType *)selectorRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType pointerTypeToType: [LLVMType int8TypeInContext: context]];
+}
+
+-(LLVMType *)arrayRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [LLVMType arrayTypeWithCount: [[[submatches objectForKey: @"count"] lastObject] integerValue] type: [[submatches objectForKey: @"type"] lastObject]];
+}
+
+-(LLVMType *)structRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return ([[submatches objectForKey: @"type"] count] > 0)
+ ? [LLVMType structureTypeWithTypes: [submatches objectForKey: @"type"]]
+ : [module typeNamed: [[submatches objectForKey: @"name"] lastObject]] ?: [LLVMType int8TypeInContext: context];
+}
+
+-(LLVMType *)unionRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return ([[submatches objectForKey: @"type"] count] > 0)
+ ? [LLVMType unionTypeWithTypes: [submatches objectForKey: @"type"]]
+ : [module typeNamed: [[submatches objectForKey: @"name"] lastObject]] ?: [LLVMType int8TypeInContext: context];
+}
+
+-(LLVMType *)bitfieldRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return NULL;
+}
+
+-(LLVMType *)pointerRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ LLVMType *referencedType = [[submatches objectForKey: @"type"] lastObject];
+ if([referencedType isEqual: context.voidType]) {
+ referencedType = [LLVMType int8TypeInContext: context];
+ }
+ return [LLVMType pointerTypeToType: referencedType];
+}
+
+-(LLVMType *)unknownRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return NULL;
+}
+
+-(LLVMType *)typeRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ return [[submatches objectForKey: [submatches allKeys].lastObject] lastObject];
+}
+
+-(LLVMType *)mainRuleDidMatchInRange:(NSRange)range withSubmatches:(NSDictionary *)submatches {
+ resultType = [[submatches objectForKey: @"type"] lastObject];
+ return resultType;
}
@end
\ No newline at end of file
diff --git a/Classes/HammerCompiledRule.h b/Classes/HammerCompiledRule.h
index 92640f4..9e303a0 100644
--- a/Classes/HammerCompiledRule.h
+++ b/Classes/HammerCompiledRule.h
@@ -1,49 +1,29 @@
// HammerCompiledRule.h
// Created by Rob Rix on 2009-12-23
// Copyright 2009 Monochrome Industries
#import <Hammer/Hammer.h>
@class LLVMCompiler, LLVMFunction;
@interface HammerBuiltRuleFunctions : NSObject {
LLVMFunction *lengthOfMatch;
LLVMFunction *rangeOfMatch;
}
@property (nonatomic, retain) LLVMFunction *lengthOfMatch;
@property (nonatomic, retain) LLVMFunction *rangeOfMatch;
@end
typedef HammerIndex(*HammerCompiledRuleLengthOfMatchFunction)(HammerIndex, HammerParserState *);
typedef BOOL(*HammerCompiledRuleRangeOfMatchFunction)(NSRange *, HammerIndex, HammerParserState *);
typedef struct HammerCompiledRule * HammerCompiledRuleRef;
HammerCompiledRuleRef HammerCompiledRuleCreate(HammerRuleRef source, HammerCompiledRuleLengthOfMatchFunction lengthOfMatch, HammerCompiledRuleRangeOfMatchFunction rangeOfMatch);
HammerRuleRef HammerCompiledRuleGetSourceRule(HammerCompiledRuleRef self);
HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleGetLengthOfMatchFunction(HammerCompiledRuleRef self);
HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleGetRangeOfMatchFunction(HammerCompiledRuleRef self);
-
-// @interface HammerCompiledRule : HammerRule {
-// HammerRuleRef original;
-// HammerCompiledRuleLengthOfMatchFunction lengthOfMatchFunction;
-// HammerCompiledRuleRangeOfMatchFunction rangeOfMatchFunction;
-// }
-//
-// +(id)ruleWithOriginalRule:(HammerRuleRef)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions;
-// -(id)initWithOriginalRule:(HammerRuleRef)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions;
-//
-// @property (nonatomic, readonly) HammerRuleRef original;
-//
-// @property (nonatomic, readonly) HammerCompiledRuleLengthOfMatchFunction lengthOfMatchFunction;
-// // @property (nonatomic, readonly) HammerCompiledRuleRangeOfMatchFunction rangeOfMatchFunction;
-//
-// @end
-//
-//
-// HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParserState *parser, NSString *reference);
-// // HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference);
diff --git a/Classes/HammerCompiledRule.m b/Classes/HammerCompiledRule.m
index eee3e81..263940f 100644
--- a/Classes/HammerCompiledRule.m
+++ b/Classes/HammerCompiledRule.m
@@ -1,158 +1,78 @@
// HammerCompiledRule.m
// Created by Rob Rix on 2009-12-23
// Copyright 2009 Monochrome Industries
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
#import <Auspicion/Auspicion.h>
@implementation HammerBuiltRuleFunctions
@synthesize lengthOfMatch, rangeOfMatch;
@end
static struct HammerRuleType HammerCompiledRuleType;
typedef struct HammerCompiledRule {
HammerRuleRef sourceRule;
HammerCompiledRuleLengthOfMatchFunction lengthOfMatch;
HammerCompiledRuleRangeOfMatchFunction rangeOfMatch;
} HammerCompiledRule;
HammerCompiledRuleRef HammerCompiledRuleCreate(HammerRuleRef sourceRule, HammerCompiledRuleLengthOfMatchFunction lengthOfMatch, HammerCompiledRuleRangeOfMatchFunction rangeOfMatch) {
HammerCompiledRuleRef self = RXCreate(sizeof(HammerCompiledRule), &HammerCompiledRuleType);
self->sourceRule = HammerRuleRetain(sourceRule);
self->lengthOfMatch = lengthOfMatch;
self->rangeOfMatch = rangeOfMatch;
return self;
}
void HammerCompiledRuleDeallocate(HammerCompiledRuleRef self) {
HammerRuleRelease(self->sourceRule);
}
bool HammerCompiledRuleIsEqual(HammerCompiledRuleRef self, HammerCompiledRuleRef other) {
return
(RXGetType(self) == RXGetType(other))
&& RXEquals(self->sourceRule, other->sourceRule);
}
HammerRuleRef HammerCompiledRuleGetSourceRule(HammerCompiledRuleRef self) {
return self->sourceRule;
}
HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleGetLengthOfMatchFunction(HammerCompiledRuleRef self) {
return self->lengthOfMatch;
}
HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleGetRangeOfMatchFunction(HammerCompiledRuleRef self) {
return self->rangeOfMatch;
}
HammerIndex HammerCompiledRuleLengthOfMatch(HammerCompiledRuleRef self, HammerIndex initial, HammerParserState *state) {
return self->lengthOfMatch(initial, state);
}
HammerIndex HammerCompiledRuleRangeOfMatch(HammerCompiledRuleRef self, NSRange *outrange, HammerIndex initial, HammerParserState *state) {
return self->rangeOfMatch(outrange, initial, state);
}
id HammerCompiledRuleAcceptVisitor(HammerCompiledRuleRef self, id<HammerRuleVisitor> visitor) {
return HammerRuleAcceptVisitor(self->sourceRule, visitor);
}
static struct HammerRuleType HammerCompiledRuleType = {
.name = "HammerCompiledRule",
.deallocate = (RXDeallocateMethod)HammerCompiledRuleDeallocate,
.isEqual = (RXIsEqualMethod)HammerCompiledRuleIsEqual,
.lengthOfMatch = (HammerRuleLengthOfMatchMethod)HammerCompiledRuleLengthOfMatch,
.rangeOfMatch = (HammerRuleRangeOfMatchMethod)HammerCompiledRuleRangeOfMatch,
.acceptVisitor = (HammerRuleAcceptVisitorMethod)HammerCompiledRuleAcceptVisitor,
};
-
-// @implementation HammerCompiledRule
-//
-// +(id)ruleWithOriginalRule:(HammerRule *)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions {
-// return [[[self alloc] initWithOriginalRule: _original compiler: _compiler functions: _functions] autorelease];
-// }
-//
-// -(id)initWithOriginalRule:(HammerRule *)_original compiler:(LLVMCompiler *)compiler functions:(HammerBuiltRuleFunctions *)functions {
-// if(self = [super init]) {
-// original = [_original retain];
-// NSParameterAssert(original != nil);
-// NSParameterAssert(compiler != nil);
-// NSParameterAssert(functions != nil);
-// NSParameterAssert(functions.lengthOfMatch != nil);
-// lengthOfMatchFunction = [compiler compiledFunction: functions.lengthOfMatch];
-// NSParameterAssert(lengthOfMatchFunction != NULL);
-//
-// if(functions.rangeOfMatch) { // remove this if we compile HammerRuleâs version too
-// rangeOfMatchFunction = [compiler compiledFunction: functions.rangeOfMatch];
-// NSParameterAssert(rangeOfMatchFunction != NULL);
-// }
-// }
-// return self;
-// }
-//
-// -(void)dealloc {
-// [original release];
-// [super dealloc];
-// }
-//
-//
-// @synthesize original;
-//
-// @synthesize lengthOfMatchFunction;
-//
-//
-// -(NSUInteger)lengthOfMatchFromCursor:(NSUInteger)initial withParser:(HammerParser *)parser {
-// return lengthOfMatchFunction(initial, parser);
-// }
-//
-// -(BOOL)range:(NSRange *)outrange ofMatchFromCursor:(NSUInteger)initial withParser:(HammerParser *)parser {
-// return rangeOfMatchFunction(outrange, initial, parser);
-// }
-//
-//
-// -(void)acceptVisitor:(id<HammerRuleVisitor>)visitor {
-// [original acceptVisitor: visitor];
-// }
-//
-//
-// // 10.6-only
-// -(id)forwardingTargetForSelector:(SEL)selector {
-// return original;
-// }
-//
-//
-// // 10.5
-// -(void)forwardInvocation:(NSInvocation *)invocation {
-// if([original respondsToSelector: invocation.selector]) {
-// [invocation invokeWithTarget: original];
-// } else {
-// [original doesNotRecognizeSelector: invocation.selector];
-// }
-// }
-//
-// -(NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
-// return [original methodSignatureForSelector: selector];
-// }
-//
-// @end
-//
-//
-// HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference) {
-// HammerCompiledRule *compiledRule = (HammerCompiledRule *)[parser ruleForReference: reference];
-// return compiledRule.lengthOfMatchFunction;
-// }
-//
-// // HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference) {
-// //
-// // }
diff --git a/Classes/HammerRuleCompiler.h b/Classes/HammerRuleCompiler.h
index eadff5a..8eb6141 100644
--- a/Classes/HammerRuleCompiler.h
+++ b/Classes/HammerRuleCompiler.h
@@ -1,23 +1,25 @@
// HammerRuleCompiler.h
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import <Foundation/Foundation.h>
#import <Hammer/Hammer.h>
@class LLVMBuilder, LLVMContext, LLVMModule, LLVMType;
@interface HammerRuleCompiler : HammerRuleVisitor {
LLVMBuilder *builder;
LLVMContext *context;
LLVMModule *module;
HammerRulePrinter *printer;
NSMutableArray *builtFunctionsStack;
}
++(id)compiler;
+
-(HammerRuleRef)compileRule:(HammerRuleRef)rule;
@end
diff --git a/Classes/HammerRuleCompiler.m b/Classes/HammerRuleCompiler.m
index a6ef892..9110b9d 100644
--- a/Classes/HammerRuleCompiler.m
+++ b/Classes/HammerRuleCompiler.m
@@ -1,640 +1,658 @@
// HammerRuleCompiler.m
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
-#import <Auspicion/Auspicion.h>
-#import <Hammer/Hammer.h>
+#import "Auspicion.h"
+#import "Hammer.h"
#import "LLVMModule+RuntimeTypeEncodings.h"
@interface HammerRuleCompiler () <HammerRuleVisitor>
-(void)pushRule;
-(NSArray *)popRule;
-(NSString *)nameForFunction:(NSString *)function forRule:(HammerRuleRef)rule;
-(NSString *)nameForRule:(HammerRuleRef)rule;
@end
@implementation HammerRuleCompiler
++(id)compiler {
+ return [[[self alloc] init] autorelease];
+}
+
-(id)init {
if(self = [super init]) {
context = [[LLVMContext context] retain];
builder = [[LLVMBuilder builderWithContext: context] retain];
module = [[LLVMModule moduleWithName: @"HammerRuleCompilerModule" inContext: context] retain];
LLVMModuleImportType(module, HammerIndex);
- LLVMModuleImportType(module, NSRange);
+ LLVMStructureType *rangeType = (LLVMStructureType *)LLVMModuleImportType(module, NSRange);
+ [rangeType declareElementNames: [NSArray arrayWithObjects:
+ @"location",
+ @"length",
+ nil]];
LLVMModuleImportType(module, HammerRuleRef);
LLVMModuleImportType(module, HammerSequenceRef);
LLVMModuleImportType(module, HammerMatchRef);
LLVMModuleImportType(module, NSString *);
- LLVMModuleImportType(module, HammerParserState *);
+ LLVMStructureType *parserStateType = (LLVMStructureType *)LLVMModuleImportType(module, HammerParserState);
+ [parserStateType declareElementNames: [NSArray arrayWithObjects:
+ @"sequence",
+ @"errorContext",
+ @"matchContext",
+ @"ruleGraph",
+ @"isIgnoringMatches",
+ nil]];
+ [module setType: [LLVMType pointerTypeToType: parserStateType] forName: @"HammerParserState *"];
[module setType: [LLVMType functionType: context.integerType,
[module typeNamed: @"HammerIndex"],
[module typeNamed: @"HammerParserState *"],
nil] forName: @"HammerRuleLengthOfMatchFunction"];
+ NSLog(@"NSRange: %@", [module typeNamed: @"NSRange"]);
[module setType: [LLVMType functionType: context.int1Type,
[LLVMType pointerTypeToType: [module typeNamed: @"NSRange"]],
[module typeNamed: @"HammerIndex"],
[module typeNamed: @"HammerParserState *"],
nil] forName: @"HammerRuleRangeOfMatchFunction"];
printer = [[HammerRulePrinter alloc] init];
}
return self;
}
-(void)dealloc {
[context release];
[builder release];
[module release];
[printer release];
[super dealloc];
}
-(HammerRuleRef)compileRule:(HammerRuleRef)rule {
NSArray *builtFunctionsArray = nil;
builtFunctionsStack = [[NSMutableArray alloc] init];
[self pushRule];
@try {
HammerRuleAcceptVisitor(rule, self);
}
@catch(NSException *exception) {
NSLog(@"%@", [[exception callStackSymbols] componentsJoinedByString: @"\n"]);
@throw exception;
}
builtFunctionsArray = [self popRule];
NSError *error = nil;
if(![module verifyWithError: &error]) {
// LLVMDumpModule([module moduleRef]);
NSLog(@"Error in module: %@", error.localizedDescription);
return nil;
}
- LLVMCompiler *compiler = [LLVMCompiler sharedCompiler];
+ LLVMCompiler *compiler = [LLVMCompiler compilerWithContext: context];
[compiler addModule: module];
LLVMOptimizer *optimizer = [LLVMOptimizer optimizerWithCompiler: compiler];
[optimizer addConstantPropagationPass];
[optimizer addInstructionCombiningPass];
[optimizer addPromoteMemoryToRegisterPass];
// [optimizer addGVNPass];
// [optimizer addCFGSimplificationPass];
[optimizer optimizeModule: module];
NSAssert(builtFunctionsArray.count >= 1, @"No functions were built.");
HammerBuiltRuleFunctions *builtFunctions = builtFunctionsArray.lastObject;
HammerCompiledRuleRef compiledRule = HammerCompiledRuleCreate(rule, [compiler compiledFunction: builtFunctions.lengthOfMatch], [compiler compiledFunction: builtFunctions.rangeOfMatch]);
[builtFunctionsStack release];
return compiledRule;
}
-/*
-(LLVMFunction *)lengthOfIgnorableCharactersFunction {
- return [module functionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [LLVMType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"]] definition: ^(LLVMFunctionBuilder *) {
- LLVMValue
- *length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: LLVMConstant(NSNotFound)],
- *ignorableRule = [function allocateVariableOfType: [module typeNamed: @"HammerRuleRef"] value: [[self ruleGraphGetRuleForNameFunction] call: ]];
+ return [module externalFunctionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [LLVMType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"]]];
+/*
+ return [module functionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [LLVMType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"]] definition: ^(LLVMFunctionBuilder *function) {
+ LLVMPointerValue
+ *length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]],
+ *ignorableRule = [function allocateVariableOfType: [module typeNamed: @"HammerRuleRef"] value: [[self ruleGraphGetRuleForNameFunction] call: ((LLVMPointerValue *)[function argumentNamed: @"state"]).value elementNamed: @"ruleGraph"]];
}];
+*/
}
-(LLVMFunction *)rangeOfMatchSkippingIgnorableCharactersFunctionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
- return [module functionWithName: [self nameForFunction: @"rangeOfMatchSkppingIgnorableCharacters" forRule: rule] type: [module typeNamed: @"HammerRuleRangeOfMatchFunction"] definitionBlock: ^(LLVMFunctionBuilder *function) {
- [function declareArguments: [NSArray arrayWithObjects: @"outrange", @"initial", @"state", nil]];
+ return [module functionWithName: [self nameForFunction: @"rangeOfMatchSkppingIgnorableCharacters" forRule: rule] type: [module typeNamed: @"HammerRuleRangeOfMatchFunction"] definition: ^(LLVMFunctionBuilder *function) {
+ [function declareArgumentNames: [NSArray arrayWithObjects: @"outrange", @"initial", @"state", nil]];
- LLVMValue
+ LLVMPointerValue
*length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]],
- *ignorable = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: LLVMConstant(NSNotFound)];
+ *ignorable = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [context constantUnsignedInteger: NSNotFound]];
- [[length.value equals: LLVMConstant(NSNotFound)] ifTrue: ^{
+ [[length.value equals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
ignorable.value = [[self lengthOfIgnorableCharactersFunction] call: [function argumentNamed: @"state"], [function argumentNamed: @"initial"]];
- [[ignorable.value notEquals: LLVMConstant(NSNotFound)] ifTrue: ^{
+ [[ignorable.value notEquals: [context constantUnsignedInteger: NSNotFound]] ifTrue: ^{
length.value = [lengthOfMatch call: [[function argumentNamed: @"initial"] plus: ignorable.value], [function argumentNamed: @"state"]];
}];
}];
- [function argumentNamed: @"outrange"].value = [LLVMStruct structWithValues:
- [[function argumentNamed: @"initial"] plus: [[ignorable.value equals: LLVMConstant(NSNotFound)] select: LLVMConstant(0) or: ignorable.value]],
+ ((LLVMStructureValue *)((LLVMPointerValue *)[function argumentNamed: @"outrange"]).value).elements = [NSArray arrayWithObjects:
+ [[function argumentNamed: @"initial"] plus: [[ignorable.value equals: [context constantUnsignedInteger: NSNotFound]] select: [context constantUnsignedInteger: 0] or: ignorable.value]],
length.value,
nil];
- [function return: [length notEquals: LLVMConstant(NSNotFound)]];
+ [function return: [length notEquals: [context constantUnsignedInteger: NSNotFound]]];
}];
}
-*/
-(LLVMFunction *)defaultRangeOfMatchFunctionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
NSString *name = [self nameForFunction: @"rangeOfMatchFromCursor:withParser:" forRule: rule];
- LLVMFunction *ignorableCharactersFromCursor = [module declareExternalFunctionWithName: @"HammerParserIgnorableCharactersFromCursor" type: [LLVMType functionType: context.integerType, context.untypedPointerType, context.integerType, nil]];
+ LLVMFunction *ignorableCharactersFromCursor = [module externalFunctionWithName: @"HammerParserIgnorableCharactersFromCursor" type: [LLVMType functionType: context.integerType, context.untypedPointerType, context.integerType, nil]];
- LLVMFunction *rangeOfMatch = [module functionWithName: name];
+ LLVMFunction *rangeOfMatch = [module functionNamed: name];
if(!rangeOfMatch) {
rangeOfMatch = [module functionWithName: name typeName: @"HammerRuleRangeOfMatchFunction"];
[builder positionAtEndOfFunction: rangeOfMatch];
LLVMBlock
*tryIgnorableBlock = [rangeOfMatch appendBlockWithName: @"tryIgnorable"],
*retryAfterIgnorableBlock = [rangeOfMatch appendBlockWithName: @"retryAfterIgnorable"],
*returnBlock = [rangeOfMatch appendBlockWithName: @"return"];
LLVMValue
*notFound = [context constantUnsignedInteger: NSNotFound],
*zero = [context constantUnsignedInteger: 0],
*length = [builder allocateLocal: @"length" type: context.integerType],
*ignorable = [builder allocateLocal: @"ignorable" type: context.integerType];
// NSUInteger length = [self lengthOfMatchFromCursor: initial withParser: parser];
- [builder set: length, [builder call: lengthOfMatch, [rangeOfMatch parameterAtIndex: 1], [rangeOfMatch parameterAtIndex: 2], nil]];
+ [builder set: length, [builder call: lengthOfMatch, [rangeOfMatch argumentAtIndex: 1], [rangeOfMatch argumentAtIndex: 2], nil]];
// NSUInteger ignorable = NSNotFound;
[builder set: ignorable, notFound];
// if(length == NSNotFound)
[builder if: [builder equal: [builder get: length], notFound] then: tryIgnorableBlock else: returnBlock];
[builder positionAtEndOfBlock: tryIgnorableBlock]; {
// ignorable = HammerParserIgnorableCharactersFromCursor(parser, initial);
- [builder set: ignorable, [builder call: ignorableCharactersFromCursor, [rangeOfMatch parameterAtIndex: 2], [rangeOfMatch parameterAtIndex: 1], nil]];
+ [builder set: ignorable, [builder call: ignorableCharactersFromCursor, [rangeOfMatch argumentAtIndex: 2], [rangeOfMatch argumentAtIndex: 1], nil]];
// if(ignorable != NSNotFound)
[builder if: [builder notEqual: [builder get: ignorable], notFound] then: retryAfterIgnorableBlock else: returnBlock];
[builder positionAtEndOfBlock: retryAfterIgnorableBlock]; {
// length = [self lengthOfMatchFromCursor: initial + ignorable withParser: parser];
- [builder set: length, [builder call: lengthOfMatch, [builder add: [rangeOfMatch parameterAtIndex: 1], [builder get: ignorable]], [rangeOfMatch parameterAtIndex: 2], nil]];
+ [builder set: length, [builder call: lengthOfMatch, [builder add: [rangeOfMatch argumentAtIndex: 1], [builder get: ignorable]], [rangeOfMatch argumentAtIndex: 2], nil]];
[builder jumpToBlock: returnBlock];
}
}
[builder positionAtEndOfBlock: returnBlock]; {
- [builder setElements: [rangeOfMatch parameterAtIndex: 0],
+ [builder setElements: [rangeOfMatch argumentAtIndex: 0],
[builder add:
- [rangeOfMatch parameterAtIndex: 1],
+ [rangeOfMatch argumentAtIndex: 1],
[builder condition: [builder equal: [builder get: ignorable], notFound]
then: zero
else: [builder get: ignorable]
]
],
[builder get: length],
nil];
[builder return: [builder notEqual: [builder get: length], notFound]];
}
}
return rangeOfMatch;
}
-(HammerBuiltRuleFunctions *)defaultFunctionsForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
HammerBuiltRuleFunctions *functions = [[[HammerBuiltRuleFunctions alloc] init] autorelease];
functions.lengthOfMatch = lengthOfMatch;
functions.rangeOfMatch = [self defaultRangeOfMatchFunctionForRule: rule withLengthOfMatchFunction: lengthOfMatch];
return functions;
}
-(void)addBuiltFunctions:(HammerBuiltRuleFunctions *)functions {
[builtFunctionsStack.lastObject addObject: functions];
}
-(void)pushRule {
[builtFunctionsStack addObject: [NSMutableArray array]];
}
-(NSArray *)popRule {
NSArray *lastFunctions = [[builtFunctionsStack.lastObject retain] autorelease];
[builtFunctionsStack removeLastObject];
return lastFunctions;
}
-(LLVMFunction *)parserIsAtEndFunction {
- return [module declareExternalFunctionWithName: @"HammerParserCursorIsAtEnd" type: [LLVMType functionType: context.int1Type,
+ return [module externalFunctionWithName: @"HammerParserCursorIsAtEnd" type: [LLVMType functionType: context.int1Type,
context.untypedPointerType,
context.integerType,
nil]];
}
-(LLVMFunction *)parserGetInputStringFunction {
- return [module declareExternalFunctionWithName: @"HammerParserGetInputString" type: [LLVMType functionType: context.untypedPointerType, context.untypedPointerType, nil]];
+ return [module externalFunctionWithName: @"HammerParserGetInputString" type: [LLVMType functionType: context.untypedPointerType, context.untypedPointerType, nil]];
}
-(NSString *)nameForFunction:(NSString *)function forRule:(HammerRuleRef)rule {
return [NSString stringWithFormat: @"%s(%@) %@", RXObjectTypeGetName(RXGetType(rule)), [printer printRule: rule], function];
}
-(NSString *)nameForRule:(HammerRuleRef)rule {
return [self nameForFunction: @"lengthOfMatchFromCursor:withParser:" forRule: rule];
}
-(void)leaveAlternationRule:(HammerAlternationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
NSString *name = [self nameForRule: rule];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
LLVMValue *length = [builder allocateLocal: @"length" type: context.integerType];
LLVMBlock *returnBlock = [lengthOfMatch appendBlockWithName: @"return"];
NSUInteger i = 0;
for(HammerBuiltRuleFunctions *subrule in subrules) {
LLVMBlock *subruleBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d", i]];
[builder jumpToBlock: subruleBlock];
[builder positionAtEndOfBlock: subruleBlock];
- [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil]];
+ [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil]];
LLVMBlock *subruleNotMatchedBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d not matched", i]];
[builder if: [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]] then: returnBlock else: subruleNotMatchedBlock];
[builder positionAtEndOfBlock: subruleNotMatchedBlock];
i++;
}
[builder jumpToBlock: returnBlock];
[builder positionAtEndOfBlock: returnBlock];
[builder return: [builder get: length]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
-(void)leaveCharacterRule:(HammerCharacterRuleRef)rule {
NSString *name = [self nameForRule: rule];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder return: [builder condition:
- [builder not: [builder call: [self parserIsAtEndFunction], [lengthOfMatch parameterAtIndex: 1], [lengthOfMatch parameterAtIndex: 0], nil]]
+ [builder not: [builder call: [self parserIsAtEndFunction], [lengthOfMatch argumentAtIndex: 1], [lengthOfMatch argumentAtIndex: 0], nil]]
then: [context constantUnsignedInteger: 1]
else: [context constantUnsignedInteger: NSNotFound]
]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
-(void)leaveCharacterSetRule:(HammerCharacterSetRuleRef)rule {
NSString *name = [self nameForRule: rule];
- LLVMFunction *isCharacterMemberFunction = [module declareExternalFunctionWithName: @"CFCharacterSetIsCharacterMember" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, context.int16Type, nil]];
- LLVMFunction *characterAtIndexFunction = [module declareExternalFunctionWithName: @"CFStringGetCharacterAtIndex" type: [LLVMType functionType: context.int16Type, context.untypedPointerType, context.integerType, nil]];
+ LLVMFunction *isCharacterMemberFunction = [module externalFunctionWithName: @"CFCharacterSetIsCharacterMember" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, context.int16Type, nil]];
+ LLVMFunction *characterAtIndexFunction = [module externalFunctionWithName: @"CFStringGetCharacterAtIndex" type: [LLVMType functionType: context.int16Type, context.untypedPointerType, context.integerType, nil]];
LLVMValue *notFound = [context constantUnsignedInteger: NSNotFound];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder return: [builder condition: [builder and:
- [builder not: [builder call: [self parserIsAtEndFunction], [lengthOfMatch parameterAtIndex: 1], [lengthOfMatch parameterAtIndex: 0], nil]],
+ [builder not: [builder call: [self parserIsAtEndFunction], [lengthOfMatch argumentAtIndex: 1], [lengthOfMatch argumentAtIndex: 0], nil]],
[builder call: isCharacterMemberFunction,
[context constantUntypedPointer: HammerCharacterSetRuleGetCharacterSet(rule)],
[builder call: characterAtIndexFunction,
- [builder call: [self parserGetInputStringFunction], [lengthOfMatch parameterAtIndex: 1], nil],
- [lengthOfMatch parameterAtIndex: 0],
+ [builder call: [self parserGetInputStringFunction], [lengthOfMatch argumentAtIndex: 1], nil],
+ [lengthOfMatch argumentAtIndex: 0],
nil],
nil]
]
then: [context constantUnsignedInteger: 1]
else: notFound
]];
}
name = [self nameForFunction: @"range:ofMatchFromCursor:withParser:" forRule: rule];
- LLVMFunction *rangeOfMatch = [module functionWithName: name];
+ LLVMFunction *rangeOfMatch = [module functionNamed: name];
if(!rangeOfMatch) {
rangeOfMatch = [module functionWithName: name typeName: @"HammerRuleRangeOfMatchFunction"];
[builder positionAtEndOfFunction: rangeOfMatch];
- [builder setElements: [rangeOfMatch parameterAtIndex: 0],
- [rangeOfMatch parameterAtIndex: 1],
+ [builder setElements: [rangeOfMatch argumentAtIndex: 0],
+ [rangeOfMatch argumentAtIndex: 1],
[context constantUnsignedInteger: 1],
nil];
- [builder return: [builder notEqual: [builder call: lengthOfMatch, [rangeOfMatch parameterAtIndex: 1], [rangeOfMatch parameterAtIndex: 2], nil], notFound]];
+ [builder return: [builder notEqual: [builder call: lengthOfMatch, [rangeOfMatch argumentAtIndex: 1], [rangeOfMatch argumentAtIndex: 2], nil], notFound]];
}
HammerBuiltRuleFunctions *functions = [[[HammerBuiltRuleFunctions alloc] init] autorelease];
functions.lengthOfMatch = lengthOfMatch;
functions.rangeOfMatch = rangeOfMatch;
[self addBuiltFunctions: functions];
}
-(void)leaveConcatenationRule:(HammerConcatenationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
- *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, nil]];
+ *pushMatchContext = [module externalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
+ *popMatchContext = [module externalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, nil]];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
- [builder call: pushMatchContext, [lengthOfMatch parameterAtIndex: 1], nil];
+ [builder call: pushMatchContext, [lengthOfMatch argumentAtIndex: 1], nil];
LLVMValue
*length = [builder allocateLocal: @"length" type: context.integerType],
*subrange = [builder allocateLocal: @"subrange" type: [module typeNamed: @"NSRange"]];
[builder set: length, [context constantUnsignedInteger: 0]];
LLVMBlock
*notFoundBlock = [lengthOfMatch appendBlockWithName: @"notFound"],
*returnLengthBlock = [lengthOfMatch appendBlockWithName: @"returnLength"];
NSUInteger i = 0;
for(HammerBuiltRuleFunctions *subruleFunctions in subrules) {
LLVMBlock *subruleBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d", i]];
LLVMBlock *subruleFoundBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d found", i]];
[builder jumpToBlock: subruleBlock];
[builder positionAtEndOfBlock: subruleBlock]; {
[builder if: [builder call: subruleFunctions.rangeOfMatch,
subrange,
- [builder add: [lengthOfMatch parameterAtIndex: 0], [builder get: length]],
- [lengthOfMatch parameterAtIndex: 1],
+ [builder add: [lengthOfMatch argumentAtIndex: 0], [builder get: length]],
+ [lengthOfMatch argumentAtIndex: 1],
nil] then: subruleFoundBlock else: notFoundBlock];
}
[builder positionAtEndOfBlock: subruleFoundBlock]; {
// length = NSMaxRange(subrange) - initial;
- [builder set: length, [builder subtract: [builder add: [builder getElement: subrange atIndex: 0], [builder getElement: subrange atIndex: 1]], [lengthOfMatch parameterAtIndex: 0]]];
+ [builder set: length, [builder subtract: [builder add: [builder getElement: subrange atIndex: 0], [builder getElement: subrange atIndex: 1]], [lengthOfMatch argumentAtIndex: 0]]];
}
i++;
}
[builder jumpToBlock: returnLengthBlock];
[builder positionAtEndOfBlock: notFoundBlock]; {
[builder set: length, [context constantUnsignedInteger: NSNotFound]];
[builder jumpToBlock: returnLengthBlock];
}
[builder positionAtEndOfBlock: returnLengthBlock]; {
- [builder call: popMatchContext, [lengthOfMatch parameterAtIndex: 1], [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]], nil];
+ [builder call: popMatchContext, [lengthOfMatch argumentAtIndex: 1], [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]], nil];
[builder return: [builder get: length]];
}
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
-(void)leaveLiteralConcatenationRule:(HammerLiteralConcatenationRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *getAttemptsIgnorableRule = [module declareExternalFunctionWithName: @"HammerParserGetAttemptsIgnorableRule" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, nil]],
- *setAttemptsIgnorableRule = [module declareExternalFunctionWithName: @"HammerParserSetAttemptsIgnorableRule" type: [LLVMType functionType: context.voidType, context.untypedPointerType, context.int1Type, nil]];
+ *getAttemptsIgnorableRule = [module externalFunctionWithName: @"HammerParserGetAttemptsIgnorableRule" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, nil]],
+ *setAttemptsIgnorableRule = [module externalFunctionWithName: @"HammerParserSetAttemptsIgnorableRule" type: [LLVMType functionType: context.voidType, context.untypedPointerType, context.int1Type, nil]];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
LLVMValue
*attemptsIgnorableRule = [builder allocateLocal: @"attemptsIgnorableRule" type: context.int1Type],
*length = [builder allocateLocal: @"length" type: context.integerType];
- [builder set: attemptsIgnorableRule, [builder call: getAttemptsIgnorableRule, [lengthOfMatch parameterAtIndex: 1], nil]];
+ [builder set: attemptsIgnorableRule, [builder call: getAttemptsIgnorableRule, [lengthOfMatch argumentAtIndex: 1], nil]];
- [builder call: setAttemptsIgnorableRule, [lengthOfMatch parameterAtIndex: 1], [context constantNullOfType: context.int1Type], nil];
+ [builder call: setAttemptsIgnorableRule, [lengthOfMatch argumentAtIndex: 1], [context constantNullOfType: context.int1Type], nil];
- [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil]];
+ [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil]];
- [builder call: setAttemptsIgnorableRule, [lengthOfMatch parameterAtIndex: 1], [builder get: attemptsIgnorableRule], nil];
+ [builder call: setAttemptsIgnorableRule, [lengthOfMatch argumentAtIndex: 1], [builder get: attemptsIgnorableRule], nil];
[builder return: [builder get: length]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
-(void)leaveLiteralRule:(HammerLiteralRuleRef)rule {
NSString *name = [self nameForRule: rule];
- LLVMFunction *stringContainsStringAtIndexFunction = [module declareExternalFunctionWithName: @"HammerLiteralRuleStringContainsStringAtIndex" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, context.untypedPointerType, context.integerType, nil]];
- LLVMFunction *parserGetInputLengthFunction = [module declareExternalFunctionWithName: @"HammerParserGetInputLength" type: [LLVMType functionType: context.integerType, context.untypedPointerType, nil]];
+ LLVMFunction *stringContainsStringAtIndexFunction = [module externalFunctionWithName: @"HammerLiteralRuleStringContainsStringAtIndex" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, context.untypedPointerType, context.integerType, nil]];
+ LLVMFunction *parserGetInputLengthFunction = [module externalFunctionWithName: @"HammerParserGetInputLength" type: [LLVMType functionType: context.integerType, context.untypedPointerType, nil]];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder return: [builder condition: [builder and:
- [builder unsignedLessOrEqual: [builder add: [lengthOfMatch parameterAtIndex: 0], [context constantUnsignedInteger: HammerLiteralRuleGetLiteral(rule).length]], [builder call: parserGetInputLengthFunction, [lengthOfMatch parameterAtIndex: 1], nil]],
+ [builder unsignedLessOrEqual: [builder add: [lengthOfMatch argumentAtIndex: 0], [context constantUnsignedInteger: HammerLiteralRuleGetLiteral(rule).length]], [builder call: parserGetInputLengthFunction, [lengthOfMatch argumentAtIndex: 1], nil]],
[builder call: stringContainsStringAtIndexFunction,
- [builder call: [self parserGetInputStringFunction], [lengthOfMatch parameterAtIndex: 1], nil],
+ [builder call: [self parserGetInputStringFunction], [lengthOfMatch argumentAtIndex: 1], nil],
[context constantUntypedPointer: HammerLiteralRuleGetLiteral(rule)],
- [lengthOfMatch parameterAtIndex: 0],
+ [lengthOfMatch argumentAtIndex: 0],
nil]
]
then: [context constantUnsignedInteger: HammerLiteralRuleGetLiteral(rule).length]
else: [context constantUnsignedInteger: NSNotFound]
]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
-(void)leaveLookaheadRule:(HammerLookaheadRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
NSString *name = [self nameForRule: rule];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
- [builder return: [builder condition: [builder notEqual: [builder call: subrule.lengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil], [context constantUnsignedInteger: NSNotFound]]
+ [builder return: [builder condition: [builder notEqual: [builder call: subrule.lengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil], [context constantUnsignedInteger: NSNotFound]]
then: [context constantUnsignedInteger: HammerLookaheadRuleGetNegative(rule)? NSNotFound : 0]
else: [context constantUnsignedInteger: HammerLookaheadRuleGetNegative(rule)? 0 : NSNotFound]
]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
-(void)leaveNamedRule:(HammerNamedRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
- *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, [module typeNamed: @"HammerRule"], [module typeNamed: @"NSString"], [module typeNamed: @"NSRange"], nil]];
+ *pushMatchContext = [module externalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
+ *popMatchContext = [module externalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, [module typeNamed: @"HammerRule"], [module typeNamed: @"NSString"], [module typeNamed: @"NSRange"], nil]];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
- [builder call: pushMatchContext, [lengthOfMatch parameterAtIndex: 1], nil];
+ [builder call: pushMatchContext, [lengthOfMatch argumentAtIndex: 1], nil];
LLVMValue
*length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
*range = [builder allocateLocal: @"range" type: [module typeNamed: @"NSRange"]];
- [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil]];
- [builder setElements: range, [lengthOfMatch parameterAtIndex: 0], [builder get: length], nil];
+ [builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil]];
+ [builder setElements: range, [lengthOfMatch argumentAtIndex: 0], [builder get: length], nil];
[builder call: popMatchContext,
- [lengthOfMatch parameterAtIndex: 1],
+ [lengthOfMatch argumentAtIndex: 1],
[builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]],
[context constantUntypedPointer: rule],
[context constantUntypedPointer: HammerNamedRuleGetName(rule)],
[builder get: range],
nil];
[builder return: [builder get: length]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
-(void)leaveReferenceRule:(HammerReferenceRuleRef)rule {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *lengthOfMatchFunctionForReference = [module declareExternalFunctionWithName: @"HammerCompiledRuleLengthOfMatchFunctionForReference" type: [LLVMType functionType: [LLVMType pointerTypeToType: [module typeNamed: @"HammerRuleLengthOfMatchFunction"]], [module typeNamed: @"HammerParser"], [module typeNamed: @"NSString"], nil]],
- *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
- *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, [module typeNamed: @"HammerRule"], [module typeNamed: @"NSString"], [module typeNamed: @"NSRange"], nil]];
+ *lengthOfMatchFunctionForReference = [module externalFunctionWithName: @"HammerCompiledRuleLengthOfMatchFunctionForReference" type: [LLVMType functionType: [LLVMType pointerTypeToType: [module typeNamed: @"HammerRuleLengthOfMatchFunction"]], [module typeNamed: @"HammerParser"], [module typeNamed: @"NSString"], nil]],
+ *pushMatchContext = [module externalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
+ *popMatchContext = [module externalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, [module typeNamed: @"HammerRule"], [module typeNamed: @"NSString"], [module typeNamed: @"NSRange"], nil]];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
- [builder call: pushMatchContext, [lengthOfMatch parameterAtIndex: 1], nil];
+ [builder call: pushMatchContext, [lengthOfMatch argumentAtIndex: 1], nil];
- LLVMFunction *subruleLengthOfMatch = (LLVMFunction *)[builder call: lengthOfMatchFunctionForReference, [lengthOfMatch parameterAtIndex: 1], [context constantUntypedPointer: HammerReferenceRuleGetReference(rule)], nil];
+ LLVMFunction *subruleLengthOfMatch = (LLVMFunction *)[builder call: lengthOfMatchFunctionForReference, [lengthOfMatch argumentAtIndex: 1], [context constantUntypedPointer: HammerReferenceRuleGetReference(rule)], nil];
LLVMValue
*length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
*range = [builder allocateLocal: @"range" type: [module typeNamed: @"NSRange"]];
- [builder set: length, [builder call: subruleLengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil]];
- [builder setElements: range, [lengthOfMatch parameterAtIndex: 0], [builder get: length], nil];
+ [builder set: length, [builder call: subruleLengthOfMatch, [lengthOfMatch argumentAtIndex: 0], [lengthOfMatch argumentAtIndex: 1], nil]];
+ [builder setElements: range, [lengthOfMatch argumentAtIndex: 0], [builder get: length], nil];
[builder call: popMatchContext,
- [lengthOfMatch parameterAtIndex: 1],
+ [lengthOfMatch argumentAtIndex: 1],
[builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]],
[context constantUntypedPointer: rule],
[context constantUntypedPointer: HammerReferenceRuleGetReference(rule)],
[builder get: range],
nil];
[builder return: [builder get: length]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
-(void)leaveRepetitionRule:(HammerRepetitionRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
- *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, nil]];
+ *pushMatchContext = [module externalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
+ *popMatchContext = [module externalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, nil]];
- LLVMFunction *lengthOfMatch = [module functionWithName: name];
+ LLVMFunction *lengthOfMatch = [module functionNamed: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
- [builder call: pushMatchContext, [lengthOfMatch parameterAtIndex: 1], nil];
+ [builder call: pushMatchContext, [lengthOfMatch argumentAtIndex: 1], nil];
LLVMValue
*length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
*count = [builder allocateLocal: @"count" type: context.int64Type],
*subrange = [builder allocateLocal: @"subrange" type: [module typeNamed: @"NSRange"]];
[builder set: length, [context constantUnsignedInteger: 0]];
[builder set: count, [context constantUnsignedInt64: 0]];
LLVMBlock
*loopBlock = [lengthOfMatch appendBlockWithName: @"loop"],
*subruleTestBlock = [lengthOfMatch appendBlockWithName: @"subrule test"],
*subruleMatchedBlock = [lengthOfMatch appendBlockWithName: @"subrule matched"],
*returnBlock = [lengthOfMatch appendBlockWithName: @"return"];
LLVMValue
*unbounded = [context constantUnsignedInt64: HammerRepetitionRuleUnboundedMaximum],
*maximum = [context constantUnsignedInt64: HammerRepetitionRuleGetMaximum(rule)],
*minimum = [context constantUnsignedInt64: HammerRepetitionRuleGetMinimum(rule)];
[builder jumpToBlock: loopBlock];
[builder positionAtEndOfBlock: loopBlock]; {
[builder if: [builder or: [builder equal: maximum, unbounded], [builder unsignedLessThan: [builder get: count], maximum]] then: subruleTestBlock else: returnBlock];
}
[builder positionAtEndOfBlock: subruleTestBlock]; {
[builder set: count, [builder add: [builder get: count], [context constantUnsignedInt64: 1]]];
- [builder if: [builder call: subrule.rangeOfMatch, subrange, [builder add: [lengthOfMatch parameterAtIndex: 0], [builder get: length]], [lengthOfMatch parameterAtIndex: 1], nil] then: subruleMatchedBlock else: returnBlock];
+ [builder if: [builder call: subrule.rangeOfMatch, subrange, [builder add: [lengthOfMatch argumentAtIndex: 0], [builder get: length]], [lengthOfMatch argumentAtIndex: 1], nil] then: subruleMatchedBlock else: returnBlock];
}
[builder positionAtEndOfBlock: subruleMatchedBlock]; {
- [builder set: length, [builder subtract: [builder add: [builder getElement: subrange atIndex: 0], [builder getElement: subrange atIndex: 1]], [lengthOfMatch parameterAtIndex: 0]]];
+ [builder set: length, [builder subtract: [builder add: [builder getElement: subrange atIndex: 0], [builder getElement: subrange atIndex: 1]], [lengthOfMatch argumentAtIndex: 0]]];
[builder jumpToBlock: loopBlock];
}
[builder positionAtEndOfBlock: returnBlock]; {
[builder set: length, [builder condition: (
(HammerRepetitionRuleGetMaximum(rule) == HammerRepetitionRuleUnboundedMaximum)
? [builder unsignedLessThan: minimum, [builder get: count]]
: [builder and: [builder unsignedLessThan: minimum, [builder get: count]], [builder unsignedLessOrEqual: [builder get: count], maximum]]
)
then: [builder get: length]
else: [context constantUnsignedInteger: NSNotFound]
]];
- [builder call: popMatchContext, [lengthOfMatch parameterAtIndex: 1], [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]], nil];
+ [builder call: popMatchContext, [lengthOfMatch argumentAtIndex: 1], [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]], nil];
[builder return: [builder get: length]];
}
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
@end
diff --git a/External/Auspicion b/External/Auspicion
index 06810f3..629c747 160000
--- a/External/Auspicion
+++ b/External/Auspicion
@@ -1 +1 @@
-Subproject commit 06810f3339ba70e353acacc8f421156a1fdded20
+Subproject commit 629c747e1f2173ad3f74d823bb9306a7bff530d7
diff --git a/External/Include/Auspicion/LLVMBooleanValue.h b/External/Include/Auspicion/LLVMBooleanValue.h
new file mode 120000
index 0000000..7f98253
--- /dev/null
+++ b/External/Include/Auspicion/LLVMBooleanValue.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/LLVMBooleanValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteType.h b/External/Include/Auspicion/LLVMConcreteType.h
deleted file mode 120000
index 5efae51..0000000
--- a/External/Include/Auspicion/LLVMConcreteType.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMConcreteValue.h b/External/Include/Auspicion/LLVMConcreteValue.h
deleted file mode 120000
index 5df91ea..0000000
--- a/External/Include/Auspicion/LLVMConcreteValue.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../External/Auspicion/Classes/LLVMConcreteValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMFunction+Protected.h b/External/Include/Auspicion/LLVMFunction+Protected.h
new file mode 120000
index 0000000..0c28d12
--- /dev/null
+++ b/External/Include/Auspicion/LLVMFunction+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/LLVMFunction+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMFunction.h b/External/Include/Auspicion/LLVMFunction.h
index 9dd70c4..c705cc2 120000
--- a/External/Include/Auspicion/LLVMFunction.h
+++ b/External/Include/Auspicion/LLVMFunction.h
@@ -1 +1 @@
-../../../External/Auspicion/Classes/LLVMFunction.h
\ No newline at end of file
+../../../External/Auspicion/Classes/Values/LLVMFunction.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMFunctionBuilder.h b/External/Include/Auspicion/LLVMFunctionBuilder.h
new file mode 120000
index 0000000..c829e4f
--- /dev/null
+++ b/External/Include/Auspicion/LLVMFunctionBuilder.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/LLVMFunctionBuilder.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMFunctionType.h b/External/Include/Auspicion/LLVMFunctionType.h
new file mode 120000
index 0000000..5c7ce4d
--- /dev/null
+++ b/External/Include/Auspicion/LLVMFunctionType.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Type/LLVMFunctionType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMModule+Protected.h b/External/Include/Auspicion/LLVMModule+Protected.h
new file mode 120000
index 0000000..317d008
--- /dev/null
+++ b/External/Include/Auspicion/LLVMModule+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/LLVMModule+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMPointerValue.h b/External/Include/Auspicion/LLVMPointerValue.h
new file mode 120000
index 0000000..da0df8b
--- /dev/null
+++ b/External/Include/Auspicion/LLVMPointerValue.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/LLVMPointerValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMStructureType.h b/External/Include/Auspicion/LLVMStructureType.h
new file mode 120000
index 0000000..18f50a9
--- /dev/null
+++ b/External/Include/Auspicion/LLVMStructureType.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Type/LLVMStructureType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMStructureValue.h b/External/Include/Auspicion/LLVMStructureValue.h
new file mode 120000
index 0000000..5e46274
--- /dev/null
+++ b/External/Include/Auspicion/LLVMStructureValue.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/LLVMStructureValue.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMType+Protected.h b/External/Include/Auspicion/LLVMType+Protected.h
new file mode 120000
index 0000000..ee2e1f5
--- /dev/null
+++ b/External/Include/Auspicion/LLVMType+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Type/LLVMType+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMType.h b/External/Include/Auspicion/LLVMType.h
index 4358fe9..6b7b6b6 120000
--- a/External/Include/Auspicion/LLVMType.h
+++ b/External/Include/Auspicion/LLVMType.h
@@ -1 +1 @@
-../../../External/Auspicion/Classes/LLVMType.h
\ No newline at end of file
+../../../External/Auspicion/Classes/Type/LLVMType.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMValue+Protected.h b/External/Include/Auspicion/LLVMValue+Protected.h
new file mode 120000
index 0000000..9d00fa4
--- /dev/null
+++ b/External/Include/Auspicion/LLVMValue+Protected.h
@@ -0,0 +1 @@
+../../../External/Auspicion/Classes/Values/LLVMValue+Protected.h
\ No newline at end of file
diff --git a/External/Include/Auspicion/LLVMValue.h b/External/Include/Auspicion/LLVMValue.h
index a1525dc..d9dc89e 120000
--- a/External/Include/Auspicion/LLVMValue.h
+++ b/External/Include/Auspicion/LLVMValue.h
@@ -1 +1 @@
-../../../External/Auspicion/Classes/LLVMValue.h
\ No newline at end of file
+../../../External/Auspicion/Classes/Values/LLVMValue.h
\ No newline at end of file
diff --git a/Other Sources/hammerc_Prefix.pch b/Other Sources/hammerc_Prefix.pch
index d05cc05..c2881ea 100644
--- a/Other Sources/hammerc_Prefix.pch
+++ b/Other Sources/hammerc_Prefix.pch
@@ -1,7 +1,13 @@
// hammerc_Prefix.pch
// Created by Rob Rix on 2010-03-03
// Copyright 2010 Monochrome Industries
#ifdef __OBJC__
#import <Foundation/Foundation.h>
+ #import "RXObject.h"
+ #import "Hammer.h"
+ #ifdef HAMMERC_UNIT_TESTS
+ #import "RXAssertions.h"
+ #import "RXCoreFoundationIntegration.h"
+ #endif
#endif
diff --git a/Tasks.taskpaper b/Tasks.taskpaper
index d40feed..4b035a2 100644
--- a/Tasks.taskpaper
+++ b/Tasks.taskpaper
@@ -1,4 +1,9 @@
- write a parser for `@encode()` directive strings.
- provide JIT-compiled implementations of the match methods for rules, written in Auspicion. Use those in Hammer, and use them in hammerc as the components of the static compilation.
Is that even possible, i.e. resolving function calls and replacing them with static ones?
- inline everything.
+
+Tools:
+ - Xcode plugin with a build rule for .grammar files.
+ - header generator.
+ - Generation Gap builder scaffold tool (like mogenerator but based on a grammar).
diff --git a/Tests/HammerCompiledAlternationRuleTests.m b/Tests/HammerCompiledAlternationRuleTests.m
index cbd13cc..ec75679 100644
--- a/Tests/HammerCompiledAlternationRuleTests.m
+++ b/Tests/HammerCompiledAlternationRuleTests.m
@@ -1,17 +1,17 @@
// HammerCompiledAlternationRuleTests.m
// Created by Rob Rix on 2010-01-05
// Copyright 2010 Monochrome Industries
#import "HammerAlternationRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledAlternationRuleTests : HammerAlternationRuleTests
@end
@implementation HammerCompiledAlternationRuleTests
--(HammerRule *)rule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.rule];
+-(HammerRuleRef)rule {
+ return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledCharacterRuleTests.m b/Tests/HammerCompiledCharacterRuleTests.m
index bafdd6e..fcfb788 100644
--- a/Tests/HammerCompiledCharacterRuleTests.m
+++ b/Tests/HammerCompiledCharacterRuleTests.m
@@ -1,17 +1,17 @@
// HammerCompiledCharacterRuleTests.m
// Created by Rob Rix on 2009-12-28
// Copyright 2009 Monochrome Industries
#import "HammerCharacterRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledCharacterRuleTests : HammerCharacterRuleTests
@end
@implementation HammerCompiledCharacterRuleTests
--(HammerRule *)rule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.rule];
+-(HammerRuleRef)rule {
+ return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledCharacterSetRuleTests.m b/Tests/HammerCompiledCharacterSetRuleTests.m
index a1f1978..e139f37 100644
--- a/Tests/HammerCompiledCharacterSetRuleTests.m
+++ b/Tests/HammerCompiledCharacterSetRuleTests.m
@@ -1,17 +1,17 @@
// HammerCompiledCharacterSetRuleTests.m
// Created by Rob Rix on 2009-12-30
// Copyright 2009 Monochrome Industries
#import "HammerCharacterSetRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledCharacterSetRuleTests : HammerCharacterSetRuleTests
@end
@implementation HammerCompiledCharacterSetRuleTests
--(HammerRule *)rule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.rule];
+-(HammerRuleRef)rule {
+ return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledConcatenationRuleTests.m b/Tests/HammerCompiledConcatenationRuleTests.m
index f2186ff..9982361 100644
--- a/Tests/HammerCompiledConcatenationRuleTests.m
+++ b/Tests/HammerCompiledConcatenationRuleTests.m
@@ -1,17 +1,17 @@
// HammerCompiledConcatenationRuleTests.m
// Created by Rob Rix on 2010-01-04
// Copyright 2010 Monochrome Industries
#import "HammerConcatenationRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledConcatenationRuleTests : HammerConcatenationRuleTests
@end
@implementation HammerCompiledConcatenationRuleTests
--(HammerRule *)rule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.rule];
+-(HammerRuleRef)rule {
+ return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledLiteralConcatenationRuleTests.m b/Tests/HammerCompiledLiteralConcatenationRuleTests.m
index 4ffa888..5bf5dc0 100644
--- a/Tests/HammerCompiledLiteralConcatenationRuleTests.m
+++ b/Tests/HammerCompiledLiteralConcatenationRuleTests.m
@@ -1,17 +1,17 @@
// HammerCompiledLiteralConcatenationRuleTests.m
// Created by Rob Rix on 2010-01-01
// Copyright 2010 Monochrome Industries
#import "HammerLiteralConcatenationRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledLiteralConcatenationRuleTests : HammerLiteralConcatenationRuleTests
@end
@implementation HammerCompiledLiteralConcatenationRuleTests
--(HammerRule *)rule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.rule];
+-(HammerRuleRef)rule {
+ return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledLiteralRuleTests.m b/Tests/HammerCompiledLiteralRuleTests.m
index ebf7cfa..f4eeda6 100644
--- a/Tests/HammerCompiledLiteralRuleTests.m
+++ b/Tests/HammerCompiledLiteralRuleTests.m
@@ -1,17 +1,17 @@
// HammerCompiledLiteralRuleTests.m
// Created by Rob Rix on 2009-12-29
// Copyright 2009 Monochrome Industries
#import "HammerLiteralRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledLiteralRuleTests : HammerLiteralRuleTests
@end
@implementation HammerCompiledLiteralRuleTests
--(HammerRule *)rule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.rule];
+-(HammerRuleRef)rule {
+ return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledLookaheadRuleTests.m b/Tests/HammerCompiledLookaheadRuleTests.m
index bb5c070..9aa86ae 100644
--- a/Tests/HammerCompiledLookaheadRuleTests.m
+++ b/Tests/HammerCompiledLookaheadRuleTests.m
@@ -1,21 +1,21 @@
// HammerCompiledLookaheadRuleTests.m
// Created by Rob Rix on 2010-01-02
// Copyright 2010 Monochrome Industries
#import "HammerLookaheadRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledLookaheadRuleTests : HammerLookaheadRuleTests
@end
@implementation HammerCompiledLookaheadRuleTests
--(HammerRule *)positiveRule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.positiveRule];
+-(HammerLookaheadRuleRef)positiveRule {
+ return [[HammerRuleCompiler compiler] compileRule: super.positiveRule];
}
--(HammerRule *)negativeRule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.negativeRule];
+-(HammerLookaheadRuleRef)negativeRule {
+ return [[HammerRuleCompiler compiler] compileRule: super.negativeRule];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledNamedRuleTests.m b/Tests/HammerCompiledNamedRuleTests.m
index 7934a8d..729740a 100644
--- a/Tests/HammerCompiledNamedRuleTests.m
+++ b/Tests/HammerCompiledNamedRuleTests.m
@@ -1,17 +1,17 @@
// HammerCompiledNamedRuleTests.m
// Created by Rob Rix on 2010-01-06
// Copyright 2010 Monochrome Industries
#import "HammerNamedRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledNamedRuleTests : HammerNamedRuleTests
@end
@implementation HammerCompiledNamedRuleTests
--(HammerRule *)rule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.rule];
+-(HammerRuleRef)rule {
+ return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledReferenceRuleTests.m b/Tests/HammerCompiledReferenceRuleTests.m
index 0a58a37..b1c27bf 100644
--- a/Tests/HammerCompiledReferenceRuleTests.m
+++ b/Tests/HammerCompiledReferenceRuleTests.m
@@ -1,31 +1,30 @@
// HammerCompiledReferenceRuleTests.m
// Created by Rob Rix on 2010-01-30
// Copyright 2010 Monochrome Industries
#import "HammerCharacterRule.h"
#import "HammerConcatenationRule.h"
#import "HammerReferenceRule.h"
#import "HammerReferenceRuleTests.h"
#import "HammerRuleCompiler.h"
-#import "HammerTestParser.h"
@interface HammerCompiledReferenceRuleTests : HammerReferenceRuleTests
@end
@implementation HammerCompiledReferenceRuleTests
--(HammerRule *)rule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.rule];
+-(HammerRuleRef)rule {
+ return [[HammerRuleCompiler compiler] compileRule: super.rule];
}
-(void)setUp {
[super setUp];
HammerRuleCompiler *compiler = [[HammerRuleCompiler alloc] init];
- parser.rules = [NSMutableDictionary dictionaryWithObjectsAndKeys:
- [compiler compileRule: [HammerCharacterRule rule]], @"any",
- [compiler compileRule: [HammerConcatenationRule ruleWithSubrules: [NSArray arrayWithObjects: [HammerReferenceRule ruleWithReference: @"any"], [HammerReferenceRule ruleWithReference: @"any"], nil]]], @"anyTwo",
- nil];
+ state.ruleGraph = (HammerRuleGraphRef)RXDictionary(
+ [compiler compileRule: HammerCharacterRuleCreate()], @"any",
+ [compiler compileRule: HammerConcatenationRuleCreate(RXArray(HammerReferenceRuleCreate(@"any"), HammerReferenceRuleCreate(@"any"), NULL))], @"anyTwo",
+ NULL);
[compiler release];
}
@end
\ No newline at end of file
diff --git a/Tests/HammerCompiledRepetitionRuleTests.m b/Tests/HammerCompiledRepetitionRuleTests.m
index 9f50c51..c95ccaf 100644
--- a/Tests/HammerCompiledRepetitionRuleTests.m
+++ b/Tests/HammerCompiledRepetitionRuleTests.m
@@ -1,25 +1,25 @@
// HammerCompiledRepetitionRuleTests.m
// Created by Rob Rix on 2010-02-01
// Copyright 2010 Monochrome Industries
#import "HammerRepetitionRuleTests.h"
#import "HammerRuleCompiler.h"
@interface HammerCompiledRepetitionRuleTests : HammerRepetitionRuleTests
@end
@implementation HammerCompiledRepetitionRuleTests
--(HammerRule *)optionalRule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.optionalRule];
+-(HammerRepetitionRuleRef)optionalRule {
+ return [[HammerRuleCompiler compiler] compileRule: super.optionalRule];
}
--(HammerRule *)optionallyRepeatedRule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.optionallyRepeatedRule];
+-(HammerRepetitionRuleRef)optionallyRepeatedRule {
+ return [[HammerRuleCompiler compiler] compileRule: super.optionallyRepeatedRule];
}
--(HammerRule *)repeatedRule {
- return [[[[HammerRuleCompiler alloc] init] autorelease] compileRule: super.repeatedRule];
+-(HammerRepetitionRuleRef)repeatedRule {
+ return [[HammerRuleCompiler compiler] compileRule: super.repeatedRule];
}
@end
diff --git a/Tests/HammerRuleCompilerTests.m b/Tests/HammerRuleCompilerTests.m
index 1b0d5ab..6d77227 100644
--- a/Tests/HammerRuleCompilerTests.m
+++ b/Tests/HammerRuleCompilerTests.m
@@ -1,36 +1,36 @@
// HammerRuleCompilerTests.m
// Created by Rob Rix on 2009-12-11
// Copyright 2009 Monochrome Industries
#import "Hammer.h"
#import "HammerRuleCompiler.h"
#import "RXAssertions.h"
@interface HammerRuleCompilerTests : SenTestCase {
HammerRuleCompiler *compiler;
}
@end
@implementation HammerRuleCompilerTests
-(void)setUp {
compiler = [[HammerRuleCompiler alloc] init];
}
-(void)tearDown {
[compiler release];
}
// rule functionality is tested in HammerCompiled*RuleTests suites
-(void)testCompilesCharacterRules {
- HammerRule *compiledRule = [compiler compileRule: [HammerCharacterRule rule]];
+ HammerRuleRef compiledRule = [compiler compileRule: HammerCharacterRuleCreate()];
RXAssertNotNil(compiledRule);
}
-(void)testCompilesLiteralRules {
- HammerRule *compiledRule = [compiler compileRule: [HammerLiteralRule ruleWithLiteral: @"literal"]];
+ HammerRuleRef compiledRule = [compiler compileRule: HammerLiteralRuleCreate(@"literal")];
RXAssertNotNil(compiledRule);
}
@end
\ No newline at end of file
diff --git a/hammerc.xcodeproj/project.pbxproj b/hammerc.xcodeproj/project.pbxproj
index 0d21f30..8e5fe2b 100644
--- a/hammerc.xcodeproj/project.pbxproj
+++ b/hammerc.xcodeproj/project.pbxproj
@@ -1,1065 +1,1063 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 45;
objects = {
/* Begin PBXBuildFile section */
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859EA3029092ED04C91782 /* hammerc.1 */; };
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */; };
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */; };
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */; };
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */; };
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */; };
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */; };
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */; };
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */; };
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */; };
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */; };
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */; };
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E51113F5FEF0086F21C /* hammerc.m */; };
D4551E82113F85830086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
- D4551E9A113F85CA0086F21C /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E95113F85C20086F21C /* libAuspicion.a */; };
- D4551E9B113F85CC0086F21C /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E95113F85C20086F21C /* libAuspicion.a */; };
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EBA113F88300086F21C /* bootstrap-hammerc.m */; };
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551EE3113F88700086F21C /* digit.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC3113F88700086F21C /* digit.grammar */; };
D4551EE4113F88700086F21C /* letter.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC4113F88700086F21C /* letter.grammar */; };
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */; };
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC7113F88700086F21C /* HammerBuilderTests.m */; };
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */; };
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */; };
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */; };
- D4551EEA113F88700086F21C /* HammerContainerRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */; };
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */; };
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */; };
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */; };
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */; };
- D4551EEF113F88700086F21C /* HammerParserTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED7113F88700086F21C /* HammerParserTests.m */; };
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */; };
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */; };
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */; };
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDE113F88700086F21C /* HammerRuleTests.m */; };
- D4551EF4113F88700086F21C /* HammerTestParser.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EE0113F88700086F21C /* HammerTestParser.m */; };
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */; };
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EF7113F88A00086F21C /* Hammer.grammar */; };
- D4551EFB113F88B80086F21C /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E95113F85C20086F21C /* libAuspicion.a */; };
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D48B23EB11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */; };
D48B23EC11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */; };
D48B23ED11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */; };
D48B23EE11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */; };
D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B24BC11B25720007CBBB4 /* RXAssertions.m */; };
+ D4D74F1511C38023002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
+ D4D74F1611C38031002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
+ D4D74F1711C38034002FF2F1 /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */; };
+ D4D74F2411C3817B002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
+ D4D74F2511C38195002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
+ D4D74F2611C38196002FF2F1 /* NSObject+UniqueFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */; };
+ D4D74F3011C38209002FF2F1 /* LLVMModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */; };
+ D4D74F3111C3820E002FF2F1 /* LLVMType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D4551DFE113E48B20086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
proxyType = 1;
remoteGlobalIDString = D4551DF9113E48A90086F21C;
remoteInfo = "bootstrap-hammerc";
};
D4551E7A113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4041AB1113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D4551E7E113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D4DB11D60D138C7400C730A3;
remoteInfo = Tests;
};
D4551E80113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D404EB4610F5791C007612E9;
remoteInfo = "Measure Performance";
};
- D4551E94113F85C20086F21C /* PBXContainerItemProxy */ = {
- isa = PBXContainerItemProxy;
- containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
- proxyType = 2;
- remoteGlobalIDString = D2AAC07E0554694100DB518D;
- remoteInfo = "Auspicion (Static Library)";
- };
- D4551E96113F85C20086F21C /* PBXContainerItemProxy */ = {
- isa = PBXContainerItemProxy;
- containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
- proxyType = 2;
- remoteGlobalIDString = D407954F10EB27140061CF6C;
- remoteInfo = "Auspicion (Framework)";
- };
- D4551E98113F85C20086F21C /* PBXContainerItemProxy */ = {
- isa = PBXContainerItemProxy;
- containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
- proxyType = 2;
- remoteGlobalIDString = D4D9DE5510EB5F4F003EEE90;
- remoteInfo = AuspicionLLVM;
- };
D4551E9C113F85D70086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
- D4551E9E113F85DA0086F21C /* PBXContainerItemProxy */ = {
- isa = PBXContainerItemProxy;
- containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
- proxyType = 1;
- remoteGlobalIDString = D2AAC07D0554694100DB518D;
- remoteInfo = "Auspicion (Static Library)";
- };
- D4551EFD113F88CA0086F21C /* PBXContainerItemProxy */ = {
- isa = PBXContainerItemProxy;
- containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
- proxyType = 1;
- remoteGlobalIDString = D2AAC07D0554694100DB518D;
- remoteInfo = "Auspicion (Static Library)";
- };
D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D2AAC046055464E500DB518D /* libPolymorph.a */;
+ remoteGlobalIDString = D2AAC046055464E500DB518D;
remoteInfo = Polymorph;
};
D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D4AB04351180335A0048BBA1 /* Tests.octest */;
+ remoteGlobalIDString = D4AB04351180335A0048BBA1;
remoteInfo = Tests;
};
D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D2AAC07E0554694100DB518D /* libRXAssertions.a */;
+ remoteGlobalIDString = D2AAC07E0554694100DB518D;
remoteInfo = RXAssertions;
};
D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D442A488106FD94900944F07 /* Tests.octest */;
+ remoteGlobalIDString = D442A488106FD94900944F07;
remoteInfo = Tests;
};
+ D4D74F0B11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
+ proxyType = 2;
+ remoteGlobalIDString = D2AAC07E0554694100DB518D /* libAuspicion.a */;
+ remoteInfo = "Auspicion (Static Library)";
+ };
+ D4D74F0D11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
+ proxyType = 2;
+ remoteGlobalIDString = D4D9DE5510EB5F4F003EEE90 /* libAuspicionLLVM.a */;
+ remoteInfo = AuspicionLLVM;
+ };
+ D4D74F0F11C37FFC002FF2F1 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
+ proxyType = 2;
+ remoteGlobalIDString = D4CF603311C32F8000C9DD15 /* Tests.octest */;
+ remoteInfo = Tests;
+ };
+ D4D74F1111C38010002FF2F1 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
+ proxyType = 1;
+ remoteGlobalIDString = D2AAC07D0554694100DB518D /* Auspicion (Static Library) */;
+ remoteInfo = "Auspicion (Static Library)";
+ };
+ D4D74F1311C3801B002FF2F1 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
+ proxyType = 1;
+ remoteGlobalIDString = D2AAC07D0554694100DB518D /* Auspicion (Static Library) */;
+ remoteInfo = "Auspicion (Static Library)";
+ };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
8DD76F9E0486AA7600D96B5E /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 8;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
8DD76FA10486AA7600D96B5E /* hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = hammerc; sourceTree = BUILT_PRODUCTS_DIR; };
C6859EA3029092ED04C91782 /* hammerc.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = hammerc.1; sourceTree = "<group>"; };
D4551DFA113E48A90086F21C /* bootstrap-hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "bootstrap-hammerc"; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E28113F5F6D0086F21C /* Tests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Tests.octest; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E29113F5F6D0086F21C /* Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Tests-Info.plist"; sourceTree = "<group>"; };
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledAlternationRuleTests.m; sourceTree = "<group>"; };
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterRuleTests.m; sourceTree = "<group>"; };
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralRuleTests.m; sourceTree = "<group>"; };
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledNamedRuleTests.m; sourceTree = "<group>"; };
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledReferenceRuleTests.m; sourceTree = "<group>"; };
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompilerTests.m; sourceTree = "<group>"; };
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCompiledRule.h; sourceTree = "<group>"; };
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRule.m; sourceTree = "<group>"; };
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleCompiler.h; sourceTree = "<group>"; };
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompiler.m; sourceTree = "<group>"; };
D4551E51113F5FEF0086F21C /* hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = hammerc.m; sourceTree = "<group>"; };
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hammerc_Prefix.pch; sourceTree = "<group>"; };
D4551E6E113F85780086F21C /* Hammer.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Hammer.xcodeproj; sourceTree = "<group>"; };
- D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Auspicion.xcodeproj; sourceTree = "<group>"; };
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "bootstrap-hammerc.m"; sourceTree = "<group>"; };
D4551EC3113F88700086F21C /* digit.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = digit.grammar; sourceTree = "<group>"; };
D4551EC4113F88700086F21C /* letter.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = letter.grammar; sourceTree = "<group>"; };
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerAlternationRuleTests.h; sourceTree = "<group>"; };
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerAlternationRuleTests.m; sourceTree = "<group>"; };
D4551EC7113F88700086F21C /* HammerBuilderTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerBuilderTests.m; sourceTree = "<group>"; };
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterRuleTests.h; sourceTree = "<group>"; };
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterRuleTests.m; sourceTree = "<group>"; };
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterSetRuleTests.h; sourceTree = "<group>"; };
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerContainerRuleTests.m; sourceTree = "<group>"; };
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralRuleTests.h; sourceTree = "<group>"; };
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralRuleTests.m; sourceTree = "<group>"; };
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLookaheadRuleTests.h; sourceTree = "<group>"; };
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerNamedRuleTests.h; sourceTree = "<group>"; };
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerNamedRuleTests.m; sourceTree = "<group>"; };
D4551ED7113F88700086F21C /* HammerParserTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerParserTests.m; sourceTree = "<group>"; };
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerReferenceRuleTests.h; sourceTree = "<group>"; };
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerReferenceRuleTests.m; sourceTree = "<group>"; };
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRepetitionRuleTests.h; sourceTree = "<group>"; };
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRulePrinterTests.m; sourceTree = "<group>"; };
D4551EDD113F88700086F21C /* HammerRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleTests.h; sourceTree = "<group>"; };
D4551EDE113F88700086F21C /* HammerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleTests.m; sourceTree = "<group>"; };
D4551EDF113F88700086F21C /* HammerTestParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestParser.h; sourceTree = "<group>"; };
D4551EE0113F88700086F21C /* HammerTestParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestParser.m; sourceTree = "<group>"; };
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestRuleVisitor.h; sourceTree = "<group>"; };
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestRuleVisitor.m; sourceTree = "<group>"; };
- D4551EF7113F88A00086F21C /* Hammer.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Hammer.grammar; sourceTree = "<group>"; };
+ D4551EF7113F88A00086F21C /* Hammer.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = Hammer.grammar; path = "../Other Sources/Hammer.grammar"; sourceTree = "<group>"; };
D48B23E711B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "LLVMModule+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "LLVMModule+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
D48B23E911B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "LLVMType+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "LLVMType+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
D48B247911B25720007CBBB4 /* RXAllocation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAllocation.h; sourceTree = "<group>"; };
D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXCoreFoundationIntegration.h; sourceTree = "<group>"; };
D48B247D11B25720007CBBB4 /* RXObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObject.h; sourceTree = "<group>"; };
D48B248011B25720007CBBB4 /* RXObjectType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObjectType.h; sourceTree = "<group>"; };
D48B248111B25720007CBBB4 /* RXShadowObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXShadowObject.h; sourceTree = "<group>"; };
D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Polymorph.xcodeproj; sourceTree = "<group>"; };
D48B24BB11B25720007CBBB4 /* RXAssertions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAssertions.h; sourceTree = "<group>"; };
D48B24BC11B25720007CBBB4 /* RXAssertions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RXAssertions.m; sourceTree = "<group>"; };
D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = RXAssertions.xcodeproj; sourceTree = "<group>"; };
+ D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Auspicion.xcodeproj; sourceTree = "<group>"; };
+ D4D74F2211C3817B002FF2F1 /* NSObject+UniqueFactory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSObject+UniqueFactory.h"; path = "Classes/NSObject+UniqueFactory.h"; sourceTree = "<group>"; };
+ D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSObject+UniqueFactory.m"; path = "Classes/NSObject+UniqueFactory.m"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
8DD76F9B0486AA7600D96B5E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- D4551E9A113F85CA0086F21C /* libAuspicion.a in Frameworks */,
+ D4D74F1611C38031002FF2F1 /* libAuspicion.a in Frameworks */,
D4551E82113F85830086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF8113E48A90086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- D4551E9B113F85CC0086F21C /* libAuspicion.a in Frameworks */,
+ D4D74F1711C38034002FF2F1 /* libAuspicion.a in Frameworks */,
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E25113F5F6D0086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- D4551EFB113F88B80086F21C /* libAuspicion.a in Frameworks */,
+ D4D74F1511C38023002FF2F1 /* libAuspicion.a in Frameworks */,
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
08FB7794FE84155DC02AAC07 /* hammerc */ = {
isa = PBXGroup;
children = (
D48B23E611B24D5E007CBBB4 /* Categories */,
08FB7795FE84155DC02AAC07 /* Classes */,
D4551E50113F5FEF0086F21C /* Other Sources */,
D4551E30113F5FB10086F21C /* Tests */,
C6859EA2029092E104C91782 /* Documentation */,
D4551E6B113F85410086F21C /* External */,
D4551E2F113F5F7D0086F21C /* Resources */,
1AB674ADFE9D54B511CA2CBB /* Products */,
);
name = hammerc;
sourceTree = "<group>";
};
08FB7795FE84155DC02AAC07 /* Classes */ = {
isa = PBXGroup;
children = (
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */,
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */,
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */,
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */,
);
path = Classes;
sourceTree = "<group>";
};
1AB674ADFE9D54B511CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
8DD76FA10486AA7600D96B5E /* hammerc */,
D4551DFA113E48A90086F21C /* bootstrap-hammerc */,
D4551E28113F5F6D0086F21C /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
C6859EA2029092E104C91782 /* Documentation */ = {
isa = PBXGroup;
children = (
C6859EA3029092ED04C91782 /* hammerc.1 */,
);
path = Documentation;
sourceTree = "<group>";
};
D4551E2F113F5F7D0086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551E29113F5F6D0086F21C /* Tests-Info.plist */,
);
path = Resources;
sourceTree = "<group>";
};
D4551E30113F5FB10086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */,
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */,
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */,
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */,
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */,
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */,
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */,
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */,
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */,
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */,
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551E50113F5FEF0086F21C /* Other Sources */ = {
isa = PBXGroup;
children = (
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */,
D4551E51113F5FEF0086F21C /* hammerc.m */,
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */,
);
path = "Other Sources";
sourceTree = "<group>";
};
D4551E6B113F85410086F21C /* External */ = {
isa = PBXGroup;
children = (
D4551E6D113F855E0086F21C /* Auspicion */,
D4551E6C113F85530086F21C /* Hammer */,
);
path = External;
sourceTree = "<group>";
};
D4551E6C113F85530086F21C /* Hammer */ = {
isa = PBXGroup;
children = (
D4551E6E113F85780086F21C /* Hammer.xcodeproj */,
D48B244C11B25720007CBBB4 /* External */,
D4551EF6113F88930086F21C /* Resources */,
D4551EC1113F88700086F21C /* Tests */,
);
path = Hammer;
sourceTree = "<group>";
};
D4551E6D113F855E0086F21C /* Auspicion */ = {
isa = PBXGroup;
children = (
- D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */,
+ D4D74F2211C3817B002FF2F1 /* NSObject+UniqueFactory.h */,
+ D4D74F2311C3817B002FF2F1 /* NSObject+UniqueFactory.m */,
+ D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */,
);
path = Auspicion;
sourceTree = "<group>";
};
D4551E6F113F85780086F21C /* Products */ = {
isa = PBXGroup;
children = (
D4551E7B113F85780086F21C /* libHammer.a */,
D4551E7F113F85780086F21C /* Tests.octest */,
D4551E81113F85780086F21C /* Measure Performance */,
);
name = Products;
sourceTree = "<group>";
};
- D4551E8C113F85C20086F21C /* Products */ = {
- isa = PBXGroup;
- children = (
- D4551E95113F85C20086F21C /* libAuspicion.a */,
- D4551E97113F85C20086F21C /* Auspicion.framework */,
- D4551E99113F85C20086F21C /* libAuspicionLLVM.a */,
- );
- name = Products;
- sourceTree = "<group>";
- };
D4551EC1113F88700086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551EC2113F88700086F21C /* Fixtures */,
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */,
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */,
D4551EC7113F88700086F21C /* HammerBuilderTests.m */,
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */,
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */,
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */,
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */,
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */,
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */,
D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */,
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */,
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */,
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */,
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */,
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */,
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */,
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */,
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */,
D4551ED7113F88700086F21C /* HammerParserTests.m */,
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */,
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */,
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */,
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */,
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */,
D4551EDD113F88700086F21C /* HammerRuleTests.h */,
D4551EDE113F88700086F21C /* HammerRuleTests.m */,
D4551EDF113F88700086F21C /* HammerTestParser.h */,
D4551EE0113F88700086F21C /* HammerTestParser.m */,
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */,
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551EC2113F88700086F21C /* Fixtures */ = {
isa = PBXGroup;
children = (
D4551EC3113F88700086F21C /* digit.grammar */,
D4551EC4113F88700086F21C /* letter.grammar */,
);
path = Fixtures;
sourceTree = "<group>";
};
D4551EF6113F88930086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551EF7113F88A00086F21C /* Hammer.grammar */,
);
path = Resources;
sourceTree = "<group>";
};
D48B23E611B24D5E007CBBB4 /* Categories */ = {
isa = PBXGroup;
children = (
D48B23E711B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.h */,
D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */,
D48B23E911B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.h */,
D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */,
);
path = Categories;
sourceTree = "<group>";
};
D48B244C11B25720007CBBB4 /* External */ = {
isa = PBXGroup;
children = (
D48B244D11B25720007CBBB4 /* Polymorph */,
D48B249111B25720007CBBB4 /* RXAssertions */,
);
path = External;
sourceTree = "<group>";
};
D48B244D11B25720007CBBB4 /* Polymorph */ = {
isa = PBXGroup;
children = (
D48B247811B25720007CBBB4 /* Classes */,
D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */,
);
path = Polymorph;
sourceTree = "<group>";
};
D48B247811B25720007CBBB4 /* Classes */ = {
isa = PBXGroup;
children = (
D48B247911B25720007CBBB4 /* RXAllocation.h */,
D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */,
D48B247D11B25720007CBBB4 /* RXObject.h */,
D48B248011B25720007CBBB4 /* RXObjectType.h */,
D48B248111B25720007CBBB4 /* RXShadowObject.h */,
);
path = Classes;
sourceTree = "<group>";
};
D48B248B11B25720007CBBB4 /* Products */ = {
isa = PBXGroup;
children = (
D48B24E211B25721007CBBB4 /* libPolymorph.a */,
D48B24E411B25721007CBBB4 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
D48B249111B25720007CBBB4 /* RXAssertions */ = {
isa = PBXGroup;
children = (
D48B24BB11B25720007CBBB4 /* RXAssertions.h */,
D48B24BC11B25720007CBBB4 /* RXAssertions.m */,
D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */,
);
path = RXAssertions;
sourceTree = "<group>";
};
D48B24BF11B25720007CBBB4 /* Products */ = {
isa = PBXGroup;
children = (
D48B24EB11B25721007CBBB4 /* libRXAssertions.a */,
D48B24ED11B25721007CBBB4 /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
+ D4D74F0611C37FFC002FF2F1 /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */,
+ D4D74F0E11C37FFC002FF2F1 /* libAuspicionLLVM.a */,
+ D4D74F1011C37FFC002FF2F1 /* Tests.octest */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
8DD76F960486AA7600D96B5E /* hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */;
buildPhases = (
8DD76F990486AA7600D96B5E /* Sources */,
8DD76F9B0486AA7600D96B5E /* Frameworks */,
8DD76F9E0486AA7600D96B5E /* CopyFiles */,
);
buildRules = (
);
dependencies = (
D4551DFF113E48B20086F21C /* PBXTargetDependency */,
);
name = hammerc;
productInstallPath = "$(HOME)/bin";
productName = hammerc;
productReference = 8DD76FA10486AA7600D96B5E /* hammerc */;
productType = "com.apple.product-type.tool";
};
D4551DF9113E48A90086F21C /* bootstrap-hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */;
buildPhases = (
D4551DF7113E48A90086F21C /* Sources */,
D4551DF8113E48A90086F21C /* Frameworks */,
);
buildRules = (
);
dependencies = (
D4551E9D113F85D70086F21C /* PBXTargetDependency */,
- D4551E9F113F85DA0086F21C /* PBXTargetDependency */,
+ D4D74F1211C38010002FF2F1 /* PBXTargetDependency */,
);
name = "bootstrap-hammerc";
productName = "bootstrap-hammerc";
productReference = D4551DFA113E48A90086F21C /* bootstrap-hammerc */;
productType = "com.apple.product-type.tool";
};
D4551E27113F5F6D0086F21C /* Tests */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */;
buildPhases = (
D4551E24113F5F6D0086F21C /* Sources */,
D4551E23113F5F6D0086F21C /* Resources */,
D4551E25113F5F6D0086F21C /* Frameworks */,
D4551E26113F5F6D0086F21C /* ShellScript */,
);
buildRules = (
);
dependencies = (
- D4551EFE113F88CA0086F21C /* PBXTargetDependency */,
D4551F00113F88CA0086F21C /* PBXTargetDependency */,
+ D4D74F1411C3801B002FF2F1 /* PBXTargetDependency */,
);
name = Tests;
productName = Tests;
productReference = D4551E28113F5F6D0086F21C /* Tests.octest */;
productType = "com.apple.product-type.bundle";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
08FB7793FE84155DC02AAC07 /* Project object */ = {
isa = PBXProject;
buildConfigurationList = 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */;
compatibilityVersion = "Xcode 3.1";
hasScannedForEncodings = 1;
mainGroup = 08FB7794FE84155DC02AAC07 /* hammerc */;
projectDirPath = "";
projectReferences = (
{
- ProductGroup = D4551E8C113F85C20086F21C /* Products */;
- ProjectRef = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
+ ProductGroup = D4D74F0611C37FFC002FF2F1 /* Products */;
+ ProjectRef = D4D74F0511C37FFC002FF2F1 /* Auspicion.xcodeproj */;
},
{
ProductGroup = D4551E6F113F85780086F21C /* Products */;
ProjectRef = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
},
{
ProductGroup = D48B248B11B25720007CBBB4 /* Products */;
ProjectRef = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
},
{
ProductGroup = D48B24BF11B25720007CBBB4 /* Products */;
ProjectRef = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
},
);
projectRoot = "";
targets = (
8DD76F960486AA7600D96B5E /* hammerc */,
D4551DF9113E48A90086F21C /* bootstrap-hammerc */,
D4551E27113F5F6D0086F21C /* Tests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
D4551E7B113F85780086F21C /* libHammer.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libHammer.a;
remoteRef = D4551E7A113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E7F113F85780086F21C /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D4551E7E113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E81113F85780086F21C /* Measure Performance */ = {
isa = PBXReferenceProxy;
fileType = "compiled.mach-o.executable";
path = "Measure Performance";
remoteRef = D4551E80113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
- D4551E95113F85C20086F21C /* libAuspicion.a */ = {
- isa = PBXReferenceProxy;
- fileType = archive.ar;
- path = libAuspicion.a;
- remoteRef = D4551E94113F85C20086F21C /* PBXContainerItemProxy */;
- sourceTree = BUILT_PRODUCTS_DIR;
- };
- D4551E97113F85C20086F21C /* Auspicion.framework */ = {
- isa = PBXReferenceProxy;
- fileType = wrapper.framework;
- path = Auspicion.framework;
- remoteRef = D4551E96113F85C20086F21C /* PBXContainerItemProxy */;
- sourceTree = BUILT_PRODUCTS_DIR;
- };
- D4551E99113F85C20086F21C /* libAuspicionLLVM.a */ = {
- isa = PBXReferenceProxy;
- fileType = archive.ar;
- path = libAuspicionLLVM.a;
- remoteRef = D4551E98113F85C20086F21C /* PBXContainerItemProxy */;
- sourceTree = BUILT_PRODUCTS_DIR;
- };
D48B24E211B25721007CBBB4 /* libPolymorph.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libPolymorph.a;
remoteRef = D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24E411B25721007CBBB4 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24EB11B25721007CBBB4 /* libRXAssertions.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRXAssertions.a;
remoteRef = D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D48B24ED11B25721007CBBB4 /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
+ D4D74F0C11C37FFC002FF2F1 /* libAuspicion.a */ = {
+ isa = PBXReferenceProxy;
+ fileType = archive.ar;
+ path = libAuspicion.a;
+ remoteRef = D4D74F0B11C37FFC002FF2F1 /* PBXContainerItemProxy */;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ D4D74F0E11C37FFC002FF2F1 /* libAuspicionLLVM.a */ = {
+ isa = PBXReferenceProxy;
+ fileType = archive.ar;
+ path = libAuspicionLLVM.a;
+ remoteRef = D4D74F0D11C37FFC002FF2F1 /* PBXContainerItemProxy */;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ D4D74F1011C37FFC002FF2F1 /* Tests.octest */ = {
+ isa = PBXReferenceProxy;
+ fileType = wrapper.cfbundle;
+ path = Tests.octest;
+ remoteRef = D4D74F0F11C37FFC002FF2F1 /* PBXContainerItemProxy */;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
D4551E23113F5F6D0086F21C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551EE3113F88700086F21C /* digit.grammar in Resources */,
D4551EE4113F88700086F21C /* letter.grammar in Resources */,
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
D4551E26113F5F6D0086F21C /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
8DD76F990486AA7600D96B5E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */,
D48B23ED11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */,
D48B23EE11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */,
+ D4D74F2611C38196002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF7113E48A90086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */,
D48B23EB11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */,
D48B23EC11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */,
+ D4D74F2511C38195002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E24113F5F6D0086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */,
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */,
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */,
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */,
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */,
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */,
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */,
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */,
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */,
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */,
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */,
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */,
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */,
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */,
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */,
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */,
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */,
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */,
- D4551EEA113F88700086F21C /* HammerContainerRuleTests.m in Sources */,
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */,
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */,
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */,
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */,
- D4551EEF113F88700086F21C /* HammerParserTests.m in Sources */,
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */,
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */,
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */,
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */,
- D4551EF4113F88700086F21C /* HammerTestParser.m in Sources */,
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */,
D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */,
+ D4D74F2411C3817B002FF2F1 /* NSObject+UniqueFactory.m in Sources */,
+ D4D74F3011C38209002FF2F1 /* LLVMModule+RuntimeTypeEncodings.m in Sources */,
+ D4D74F3111C3820E002FF2F1 /* LLVMType+RuntimeTypeEncodings.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D4551DFF113E48B20086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D4551DF9113E48A90086F21C /* bootstrap-hammerc */;
targetProxy = D4551DFE113E48B20086F21C /* PBXContainerItemProxy */;
};
D4551E9D113F85D70086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551E9C113F85D70086F21C /* PBXContainerItemProxy */;
};
- D4551E9F113F85DA0086F21C /* PBXTargetDependency */ = {
+ D4551F00113F88CA0086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
- name = "Auspicion (Static Library)";
- targetProxy = D4551E9E113F85DA0086F21C /* PBXContainerItemProxy */;
+ name = "Hammer (Static Library)";
+ targetProxy = D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */;
};
- D4551EFE113F88CA0086F21C /* PBXTargetDependency */ = {
+ D4D74F1211C38010002FF2F1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
- targetProxy = D4551EFD113F88CA0086F21C /* PBXContainerItemProxy */;
+ targetProxy = D4D74F1111C38010002FF2F1 /* PBXContainerItemProxy */;
};
- D4551F00113F88CA0086F21C /* PBXTargetDependency */ = {
+ D4D74F1411C3801B002FF2F1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
- name = "Hammer (Static Library)";
- targetProxy = D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */;
+ name = "Auspicion (Static Library)";
+ targetProxy = D4D74F1311C3801B002FF2F1 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
1DEB927508733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_FIX_AND_CONTINUE = YES;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
+ "$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Debug;
};
1DEB927608733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
- GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_MODEL_TUNING = G5;
- GCC_PRECOMPILE_PREFIX_HEADER = YES;
- GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
- HEADER_SEARCH_PATHS = External/Include/;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
+ "$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Release;
};
1DEB927908733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_GC = required;
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
- HEADER_SEARCH_PATHS = External/Include/;
+ HEADER_SEARCH_PATHS = "External/Include/**";
ONLY_ACTIVE_ARCH = YES;
+ OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = macosx10.6;
};
name = Debug;
};
1DEB927A08733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
- GCC_ENABLE_OBJC_GC = supported;
- GCC_VERSION = com.apple.compilers.llvmgcc42;
+ GCC_ENABLE_OBJC_GC = required;
+ GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
+ GCC_PRECOMPILE_PREFIX_HEADER = YES;
+ GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
+ GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
+ HEADER_SEARCH_PATHS = "External/Include/**";
+ OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = macosx10.5;
};
name = Release;
};
D4551DFC113E48A90086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
+ "$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
};
name = Debug;
};
D4551DFD113E48A90086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_MODEL_TUNING = G5;
- GCC_PRECOMPILE_PREFIX_HEADER = YES;
- GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h";
- HEADER_SEARCH_PATHS = External/Include/;
INSTALL_PATH = /usr/local/bin;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
);
OTHER_LDFLAGS = (
+ "$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
- ZERO_LINK = NO;
};
name = Release;
};
D4551E2A113F5F6D0086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = NO;
FRAMEWORK_SEARCH_PATHS = "$(DEVELOPER_LIBRARY_DIR)/Frameworks";
GCC_DYNAMIC_NO_PIC = NO;
- GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_MODEL_TUNING = G5;
GCC_OPTIMIZATION_LEVEL = 0;
- GCC_PRECOMPILE_PREFIX_HEADER = YES;
- GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h";
- HEADER_SEARCH_PATHS = External/Include/;
INFOPLIST_FILE = "Resources/Tests-Info.plist";
INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles";
+ OTHER_CFLAGS = "-DHAMMERC_UNIT_TESTS";
OTHER_LDFLAGS = (
+ "$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-framework",
SenTestingKit,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = Tests;
- USER_HEADER_SEARCH_PATHS = External/Include/Hammer/;
WRAPPER_EXTENSION = octest;
};
name = Debug;
};
D4551E2B113F5F6D0086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = "$(DEVELOPER_LIBRARY_DIR)/Frameworks";
- GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_MODEL_TUNING = G5;
- GCC_PRECOMPILE_PREFIX_HEADER = YES;
- GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h";
- HEADER_SEARCH_PATHS = External/Include/;
INFOPLIST_FILE = "Resources/Tests-Info.plist";
INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles";
+ OTHER_CFLAGS = "-DHAMMERC_UNIT_TESTS";
OTHER_LDFLAGS = (
+ "$(OTHER_LDFLAGS)",
"-framework",
Foundation,
"-framework",
SenTestingKit,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = Tests;
- USER_HEADER_SEARCH_PATHS = External/Include/Hammer/;
WRAPPER_EXTENSION = octest;
- ZERO_LINK = NO;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB927508733DD40010E9CD /* Debug */,
1DEB927608733DD40010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB927908733DD40010E9CD /* Debug */,
1DEB927A08733DD40010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D4551DFC113E48A90086F21C /* Debug */,
D4551DFD113E48A90086F21C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D4551E2A113F5F6D0086F21C /* Debug */,
D4551E2B113F5F6D0086F21C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
}
|
robrix/hammerc
|
26396b7422f04306705a2f5724b52e8da4ff4a59
|
Fixed compilation errors due to Hammer updates.
|
diff --git a/Categories/LLVMModule+RuntimeTypeEncodings.h b/Categories/LLVMModule+RuntimeTypeEncodings.h
new file mode 100644
index 0000000..c6d289e
--- /dev/null
+++ b/Categories/LLVMModule+RuntimeTypeEncodings.h
@@ -0,0 +1,13 @@
+// LLVMModule+RuntimeTypeEncodings.h
+// Created by Rob Rix on 2010-05-30
+// Copyright 2010 Monochrome Industries
+
+#import <Auspicion/Auspicion.h>
+
+#define LLVMModuleImportType(module, type) [module setObjCType: @encode(type) forName: @#type]
+
+@interface LLVMModule (LLVMModuleRuntimeTypeEncodings)
+
+-(void)setObjCType:(const char *)type forName:(NSString *)name;
+
+@end
\ No newline at end of file
diff --git a/Categories/LLVMModule+RuntimeTypeEncodings.m b/Categories/LLVMModule+RuntimeTypeEncodings.m
new file mode 100644
index 0000000..64a81be
--- /dev/null
+++ b/Categories/LLVMModule+RuntimeTypeEncodings.m
@@ -0,0 +1,14 @@
+// LLVMModule+RuntimeTypeEncodings.m
+// Created by Rob Rix on 2010-05-30
+// Copyright 2010 Monochrome Industries
+
+#import "LLVMModule+RuntimeTypeEncodings.h"
+#import "LLVMType+RuntimeTypeEncodings.h"
+
+@implementation LLVMModule (LLVMModuleRuntimeTypeEncodings)
+
+-(void)setObjCType:(const char *)type forName:(NSString *)name {
+ [self setType: [LLVMType typeForObjCType: type] forName: name];
+}
+
+@end
\ No newline at end of file
diff --git a/Categories/LLVMType+RuntimeTypeEncodings.h b/Categories/LLVMType+RuntimeTypeEncodings.h
new file mode 100644
index 0000000..4aa49a1
--- /dev/null
+++ b/Categories/LLVMType+RuntimeTypeEncodings.h
@@ -0,0 +1,11 @@
+// LLVMType+RuntimeTypeEncodings.h
+// Created by Rob Rix on 2010-05-30
+// Copyright 2010 Monochrome Industries
+
+#import <Auspicion/Auspicion.h>
+
+@interface LLVMType (LLVMTypeRuntimeTypeEncodings)
+
++(LLVMType *)typeForObjCType:(const char *)type;
+
+@end
\ No newline at end of file
diff --git a/Categories/LLVMType+RuntimeTypeEncodings.m b/Categories/LLVMType+RuntimeTypeEncodings.m
new file mode 100644
index 0000000..4b3eb25
--- /dev/null
+++ b/Categories/LLVMType+RuntimeTypeEncodings.m
@@ -0,0 +1,13 @@
+// LLVMType+RuntimeTypeEncodings.m
+// Created by Rob Rix on 2010-05-30
+// Copyright 2010 Monochrome Industries
+
+#import "LLVMType+RuntimeTypeEncodings.h"
+
+@implementation LLVMType (LLVMTypeRuntimeTypeEncodings)
+
++(LLVMType *)typeForObjCType:(const char *)type {
+ // HammerRuleGraphRef ruleGraph = HammerRuleGraph
+}
+
+@end
\ No newline at end of file
diff --git a/Classes/HammerCompiledRule.h b/Classes/HammerCompiledRule.h
index 596db87..92640f4 100644
--- a/Classes/HammerCompiledRule.h
+++ b/Classes/HammerCompiledRule.h
@@ -1,40 +1,49 @@
// HammerCompiledRule.h
// Created by Rob Rix on 2009-12-23
// Copyright 2009 Monochrome Industries
-#import <Hammer/HammerRule.h>
+#import <Hammer/Hammer.h>
@class LLVMCompiler, LLVMFunction;
@interface HammerBuiltRuleFunctions : NSObject {
LLVMFunction *lengthOfMatch;
LLVMFunction *rangeOfMatch;
}
@property (nonatomic, retain) LLVMFunction *lengthOfMatch;
@property (nonatomic, retain) LLVMFunction *rangeOfMatch;
@end
-typedef NSUInteger(*HammerCompiledRuleLengthOfMatchFunction)(NSUInteger, HammerParser *);
-typedef BOOL(*HammerCompiledRuleRangeOfMatchFunction)(NSRange *, NSUInteger, HammerParser *);
-
-@interface HammerCompiledRule : HammerRule {
- HammerRule *original;
- HammerCompiledRuleLengthOfMatchFunction lengthOfMatchFunction;
- HammerCompiledRuleRangeOfMatchFunction rangeOfMatchFunction;
-}
-
-+(id)ruleWithOriginalRule:(HammerRule *)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions;
--(id)initWithOriginalRule:(HammerRule *)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions;
-
-@property (nonatomic, readonly) HammerRule *original;
-
-@property (nonatomic, readonly) HammerCompiledRuleLengthOfMatchFunction lengthOfMatchFunction;
-// @property (nonatomic, readonly) HammerCompiledRuleRangeOfMatchFunction rangeOfMatchFunction;
-
-@end
-
-
-HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference);
-// HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference);
+typedef HammerIndex(*HammerCompiledRuleLengthOfMatchFunction)(HammerIndex, HammerParserState *);
+typedef BOOL(*HammerCompiledRuleRangeOfMatchFunction)(NSRange *, HammerIndex, HammerParserState *);
+
+typedef struct HammerCompiledRule * HammerCompiledRuleRef;
+
+HammerCompiledRuleRef HammerCompiledRuleCreate(HammerRuleRef source, HammerCompiledRuleLengthOfMatchFunction lengthOfMatch, HammerCompiledRuleRangeOfMatchFunction rangeOfMatch);
+
+HammerRuleRef HammerCompiledRuleGetSourceRule(HammerCompiledRuleRef self);
+
+HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleGetLengthOfMatchFunction(HammerCompiledRuleRef self);
+HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleGetRangeOfMatchFunction(HammerCompiledRuleRef self);
+
+// @interface HammerCompiledRule : HammerRule {
+// HammerRuleRef original;
+// HammerCompiledRuleLengthOfMatchFunction lengthOfMatchFunction;
+// HammerCompiledRuleRangeOfMatchFunction rangeOfMatchFunction;
+// }
+//
+// +(id)ruleWithOriginalRule:(HammerRuleRef)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions;
+// -(id)initWithOriginalRule:(HammerRuleRef)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions;
+//
+// @property (nonatomic, readonly) HammerRuleRef original;
+//
+// @property (nonatomic, readonly) HammerCompiledRuleLengthOfMatchFunction lengthOfMatchFunction;
+// // @property (nonatomic, readonly) HammerCompiledRuleRangeOfMatchFunction rangeOfMatchFunction;
+//
+// @end
+//
+//
+// HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParserState *parser, NSString *reference);
+// // HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference);
diff --git a/Classes/HammerCompiledRule.m b/Classes/HammerCompiledRule.m
index 9a25c45..eee3e81 100644
--- a/Classes/HammerCompiledRule.m
+++ b/Classes/HammerCompiledRule.m
@@ -1,94 +1,158 @@
// HammerCompiledRule.m
// Created by Rob Rix on 2009-12-23
// Copyright 2009 Monochrome Industries
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
#import <Auspicion/Auspicion.h>
-#import <Hammer/HammerParser.h>
@implementation HammerBuiltRuleFunctions
@synthesize lengthOfMatch, rangeOfMatch;
@end
+static struct HammerRuleType HammerCompiledRuleType;
-@implementation HammerCompiledRule
+typedef struct HammerCompiledRule {
+ HammerRuleRef sourceRule;
+ HammerCompiledRuleLengthOfMatchFunction lengthOfMatch;
+ HammerCompiledRuleRangeOfMatchFunction rangeOfMatch;
+} HammerCompiledRule;
-+(id)ruleWithOriginalRule:(HammerRule *)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions {
- return [[[self alloc] initWithOriginalRule: _original compiler: _compiler functions: _functions] autorelease];
-}
-
--(id)initWithOriginalRule:(HammerRule *)_original compiler:(LLVMCompiler *)compiler functions:(HammerBuiltRuleFunctions *)functions {
- if(self = [super init]) {
- original = [_original retain];
- NSParameterAssert(original != nil);
- NSParameterAssert(compiler != nil);
- NSParameterAssert(functions != nil);
- NSParameterAssert(functions.lengthOfMatch != nil);
- lengthOfMatchFunction = [compiler compiledFunction: functions.lengthOfMatch];
- NSParameterAssert(lengthOfMatchFunction != NULL);
-
- if(functions.rangeOfMatch) { // remove this if we compile HammerRuleâs version too
- rangeOfMatchFunction = [compiler compiledFunction: functions.rangeOfMatch];
- NSParameterAssert(rangeOfMatchFunction != NULL);
- }
- }
+HammerCompiledRuleRef HammerCompiledRuleCreate(HammerRuleRef sourceRule, HammerCompiledRuleLengthOfMatchFunction lengthOfMatch, HammerCompiledRuleRangeOfMatchFunction rangeOfMatch) {
+ HammerCompiledRuleRef self = RXCreate(sizeof(HammerCompiledRule), &HammerCompiledRuleType);
+ self->sourceRule = HammerRuleRetain(sourceRule);
+ self->lengthOfMatch = lengthOfMatch;
+ self->rangeOfMatch = rangeOfMatch;
return self;
}
--(void)dealloc {
- [original release];
- [super dealloc];
+void HammerCompiledRuleDeallocate(HammerCompiledRuleRef self) {
+ HammerRuleRelease(self->sourceRule);
}
-@synthesize original;
-
-@synthesize lengthOfMatchFunction;
-
-
--(NSUInteger)lengthOfMatchFromCursor:(NSUInteger)initial withParser:(HammerParser *)parser {
- return lengthOfMatchFunction(initial, parser);
+bool HammerCompiledRuleIsEqual(HammerCompiledRuleRef self, HammerCompiledRuleRef other) {
+ return
+ (RXGetType(self) == RXGetType(other))
+ && RXEquals(self->sourceRule, other->sourceRule);
}
--(BOOL)range:(NSRange *)outrange ofMatchFromCursor:(NSUInteger)initial withParser:(HammerParser *)parser {
- return rangeOfMatchFunction(outrange, initial, parser);
+
+HammerRuleRef HammerCompiledRuleGetSourceRule(HammerCompiledRuleRef self) {
+ return self->sourceRule;
}
--(void)acceptVisitor:(id<HammerRuleVisitor>)visitor {
- [original acceptVisitor: visitor];
+HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleGetLengthOfMatchFunction(HammerCompiledRuleRef self) {
+ return self->lengthOfMatch;
}
-
-// 10.6-only
--(id)forwardingTargetForSelector:(SEL)selector {
- return original;
+HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleGetRangeOfMatchFunction(HammerCompiledRuleRef self) {
+ return self->rangeOfMatch;
}
-// 10.5
--(void)forwardInvocation:(NSInvocation *)invocation {
- if([original respondsToSelector: invocation.selector]) {
- [invocation invokeWithTarget: original];
- } else {
- [original doesNotRecognizeSelector: invocation.selector];
- }
+HammerIndex HammerCompiledRuleLengthOfMatch(HammerCompiledRuleRef self, HammerIndex initial, HammerParserState *state) {
+ return self->lengthOfMatch(initial, state);
}
--(NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
- return [original methodSignatureForSelector: selector];
+HammerIndex HammerCompiledRuleRangeOfMatch(HammerCompiledRuleRef self, NSRange *outrange, HammerIndex initial, HammerParserState *state) {
+ return self->rangeOfMatch(outrange, initial, state);
}
-@end
-
-HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference) {
- HammerCompiledRule *compiledRule = (HammerCompiledRule *)[parser ruleForReference: reference];
- return compiledRule.lengthOfMatchFunction;
+id HammerCompiledRuleAcceptVisitor(HammerCompiledRuleRef self, id<HammerRuleVisitor> visitor) {
+ return HammerRuleAcceptVisitor(self->sourceRule, visitor);
}
-// HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference) {
-//
+
+static struct HammerRuleType HammerCompiledRuleType = {
+ .name = "HammerCompiledRule",
+ .deallocate = (RXDeallocateMethod)HammerCompiledRuleDeallocate,
+ .isEqual = (RXIsEqualMethod)HammerCompiledRuleIsEqual,
+
+ .lengthOfMatch = (HammerRuleLengthOfMatchMethod)HammerCompiledRuleLengthOfMatch,
+ .rangeOfMatch = (HammerRuleRangeOfMatchMethod)HammerCompiledRuleRangeOfMatch,
+ .acceptVisitor = (HammerRuleAcceptVisitorMethod)HammerCompiledRuleAcceptVisitor,
+};
+
+// @implementation HammerCompiledRule
+//
+// +(id)ruleWithOriginalRule:(HammerRule *)_original compiler:(LLVMCompiler *)_compiler functions:(HammerBuiltRuleFunctions *)_functions {
+// return [[[self alloc] initWithOriginalRule: _original compiler: _compiler functions: _functions] autorelease];
+// }
+//
+// -(id)initWithOriginalRule:(HammerRule *)_original compiler:(LLVMCompiler *)compiler functions:(HammerBuiltRuleFunctions *)functions {
+// if(self = [super init]) {
+// original = [_original retain];
+// NSParameterAssert(original != nil);
+// NSParameterAssert(compiler != nil);
+// NSParameterAssert(functions != nil);
+// NSParameterAssert(functions.lengthOfMatch != nil);
+// lengthOfMatchFunction = [compiler compiledFunction: functions.lengthOfMatch];
+// NSParameterAssert(lengthOfMatchFunction != NULL);
+//
+// if(functions.rangeOfMatch) { // remove this if we compile HammerRuleâs version too
+// rangeOfMatchFunction = [compiler compiledFunction: functions.rangeOfMatch];
+// NSParameterAssert(rangeOfMatchFunction != NULL);
+// }
+// }
+// return self;
+// }
+//
+// -(void)dealloc {
+// [original release];
+// [super dealloc];
+// }
+//
+//
+// @synthesize original;
+//
+// @synthesize lengthOfMatchFunction;
+//
+//
+// -(NSUInteger)lengthOfMatchFromCursor:(NSUInteger)initial withParser:(HammerParser *)parser {
+// return lengthOfMatchFunction(initial, parser);
+// }
+//
+// -(BOOL)range:(NSRange *)outrange ofMatchFromCursor:(NSUInteger)initial withParser:(HammerParser *)parser {
+// return rangeOfMatchFunction(outrange, initial, parser);
+// }
+//
+//
+// -(void)acceptVisitor:(id<HammerRuleVisitor>)visitor {
+// [original acceptVisitor: visitor];
+// }
+//
+//
+// // 10.6-only
+// -(id)forwardingTargetForSelector:(SEL)selector {
+// return original;
+// }
+//
+//
+// // 10.5
+// -(void)forwardInvocation:(NSInvocation *)invocation {
+// if([original respondsToSelector: invocation.selector]) {
+// [invocation invokeWithTarget: original];
+// } else {
+// [original doesNotRecognizeSelector: invocation.selector];
+// }
+// }
+//
+// -(NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
+// return [original methodSignatureForSelector: selector];
+// }
+//
+// @end
+//
+//
+// HammerCompiledRuleLengthOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference) {
+// HammerCompiledRule *compiledRule = (HammerCompiledRule *)[parser ruleForReference: reference];
+// return compiledRule.lengthOfMatchFunction;
// }
+//
+// // HammerCompiledRuleRangeOfMatchFunction HammerCompiledRuleLengthOfMatchFunctionForReference(HammerParser *parser, NSString *reference) {
+// //
+// // }
diff --git a/Classes/HammerRuleCompiler.h b/Classes/HammerRuleCompiler.h
index f7b7cef..eadff5a 100644
--- a/Classes/HammerRuleCompiler.h
+++ b/Classes/HammerRuleCompiler.h
@@ -1,28 +1,23 @@
// HammerRuleCompiler.h
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import <Foundation/Foundation.h>
+#import <Hammer/Hammer.h>
-@class HammerParser, HammerRulePrinter;
@class LLVMBuilder, LLVMContext, LLVMModule, LLVMType;
-@protocol HammerRuleVisitor;
-@interface HammerRuleCompiler : NSObject {
- HammerParser *parser;
-
+@interface HammerRuleCompiler : HammerRuleVisitor {
LLVMBuilder *builder;
LLVMContext *context;
LLVMModule *module;
HammerRulePrinter *printer;
NSMutableArray *builtFunctionsStack;
}
-@property (nonatomic, retain) HammerParser *parser;
-
--(HammerRule *)compileRule:(HammerRule *)rule;
+-(HammerRuleRef)compileRule:(HammerRuleRef)rule;
@end
diff --git a/Classes/HammerRuleCompiler.m b/Classes/HammerRuleCompiler.m
index 0c8c9aa..a6ef892 100644
--- a/Classes/HammerRuleCompiler.m
+++ b/Classes/HammerRuleCompiler.m
@@ -1,626 +1,640 @@
// HammerRuleCompiler.m
// Created by Rob Rix on 2009-12-06
// Copyright 2009 Monochrome Industries
#import "HammerCompiledRule.h"
#import "HammerRuleCompiler.h"
#import <Auspicion/Auspicion.h>
#import <Hammer/Hammer.h>
-#import <Hammer/HammerRulePrinter.h>
+
+#import "LLVMModule+RuntimeTypeEncodings.h"
@interface HammerRuleCompiler () <HammerRuleVisitor>
-(void)pushRule;
-(NSArray *)popRule;
--(NSString *)nameForFunction:(NSString *)function forRule:(HammerRule *)rule;
--(NSString *)nameForRule:(HammerRule *)rule;
+-(NSString *)nameForFunction:(NSString *)function forRule:(HammerRuleRef)rule;
+-(NSString *)nameForRule:(HammerRuleRef)rule;
@end
@implementation HammerRuleCompiler
-(id)init {
if(self = [super init]) {
context = [[LLVMContext context] retain];
builder = [[LLVMBuilder builderWithContext: context] retain];
module = [[LLVMModule moduleWithName: @"HammerRuleCompilerModule" inContext: context] retain];
- [module setType: context.integerType forName: @"NSUInteger"];
- [module setType: [context structTypeWithTypes: [module typeForName: @"NSUInteger"], [module typeForName: @"NSUInteger"], nil] forName: @"NSRange"];
+ LLVMModuleImportType(module, HammerIndex);
+ LLVMModuleImportType(module, NSRange);
- [module setType: context.untypedPointerType forName: @"HammerParser"];
- [module setType: context.untypedPointerType forName: @"HammerRule"];
- [module setType: context.untypedPointerType forName: @"NSString"];
+ LLVMModuleImportType(module, HammerRuleRef);
+ LLVMModuleImportType(module, HammerSequenceRef);
+ LLVMModuleImportType(module, HammerMatchRef);
+ LLVMModuleImportType(module, NSString *);
+ LLVMModuleImportType(module, HammerParserState *);
[module setType: [LLVMType functionType: context.integerType,
- [module typeForName: @"NSUInteger"],
- [module typeForName: @"HammerParser"],
+ [module typeNamed: @"HammerIndex"],
+ [module typeNamed: @"HammerParserState *"],
nil] forName: @"HammerRuleLengthOfMatchFunction"];
[module setType: [LLVMType functionType: context.int1Type,
- [LLVMType pointerTypeToType: [module typeForName: @"NSRange"]],
- [module typeForName: @"NSUInteger"],
- [module typeForName: @"HammerParser"],
+ [LLVMType pointerTypeToType: [module typeNamed: @"NSRange"]],
+ [module typeNamed: @"HammerIndex"],
+ [module typeNamed: @"HammerParserState *"],
nil] forName: @"HammerRuleRangeOfMatchFunction"];
printer = [[HammerRulePrinter alloc] init];
}
return self;
}
-(void)dealloc {
[context release];
[builder release];
[module release];
[printer release];
[super dealloc];
}
-@synthesize parser;
-
-
--(HammerRule *)compileRule:(HammerRule *)rule {
+-(HammerRuleRef)compileRule:(HammerRuleRef)rule {
NSArray *builtFunctionsArray = nil;
builtFunctionsStack = [[NSMutableArray alloc] init];
[self pushRule];
@try {
- [rule acceptVisitor: self];
+ HammerRuleAcceptVisitor(rule, self);
}
@catch(NSException *exception) {
- // NSLog(@"%@", [[exception callStackSymbols] componentsJoinedByString: @"\n"]);
+ NSLog(@"%@", [[exception callStackSymbols] componentsJoinedByString: @"\n"]);
@throw exception;
}
builtFunctionsArray = [self popRule];
NSError *error = nil;
if(![module verifyWithError: &error]) {
// LLVMDumpModule([module moduleRef]);
NSLog(@"Error in module: %@", error.localizedDescription);
return nil;
}
LLVMCompiler *compiler = [LLVMCompiler sharedCompiler];
[compiler addModule: module];
LLVMOptimizer *optimizer = [LLVMOptimizer optimizerWithCompiler: compiler];
[optimizer addConstantPropagationPass];
[optimizer addInstructionCombiningPass];
[optimizer addPromoteMemoryToRegisterPass];
// [optimizer addGVNPass];
// [optimizer addCFGSimplificationPass];
[optimizer optimizeModule: module];
NSAssert(builtFunctionsArray.count >= 1, @"No functions were built.");
HammerBuiltRuleFunctions *builtFunctions = builtFunctionsArray.lastObject;
- HammerCompiledRule *compiledRule = [HammerCompiledRule ruleWithOriginalRule: rule compiler: compiler functions: builtFunctions];
+ HammerCompiledRuleRef compiledRule = HammerCompiledRuleCreate(rule, [compiler compiledFunction: builtFunctions.lengthOfMatch], [compiler compiledFunction: builtFunctions.rangeOfMatch]);
[builtFunctionsStack release];
return compiledRule;
}
--(LLVMFunction *)defaultRangeOfMatchFunctionForRule:(HammerRule *)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
+/*
+-(LLVMFunction *)lengthOfIgnorableCharactersFunction {
+ return [module functionWithName: @"HammerRuleLengthOfIgnorableCharactersFromCursor" type: [LLVMType functionType: [module typeNamed: @"HammerIndex"], [module typeNamed: @"HammerParserState *"], [module typeNamed: @"HammerIndex"]] definition: ^(LLVMFunctionBuilder *) {
+ LLVMValue
+ *length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: LLVMConstant(NSNotFound)],
+ *ignorableRule = [function allocateVariableOfType: [module typeNamed: @"HammerRuleRef"] value: [[self ruleGraphGetRuleForNameFunction] call: ]];
+
+ }];
+}
+
+
+-(LLVMFunction *)rangeOfMatchSkippingIgnorableCharactersFunctionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
+ return [module functionWithName: [self nameForFunction: @"rangeOfMatchSkppingIgnorableCharacters" forRule: rule] type: [module typeNamed: @"HammerRuleRangeOfMatchFunction"] definitionBlock: ^(LLVMFunctionBuilder *function) {
+ [function declareArguments: [NSArray arrayWithObjects: @"outrange", @"initial", @"state", nil]];
+
+ LLVMValue
+ *length = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: [lengthOfMatch call: [function argumentNamed: @"initial"], [function argumentNamed: @"state"]]],
+ *ignorable = [function allocateVariableOfType: [module typeNamed: @"HammerIndex"] value: LLVMConstant(NSNotFound)];
+
+ [[length.value equals: LLVMConstant(NSNotFound)] ifTrue: ^{
+ ignorable.value = [[self lengthOfIgnorableCharactersFunction] call: [function argumentNamed: @"state"], [function argumentNamed: @"initial"]];
+ [[ignorable.value notEquals: LLVMConstant(NSNotFound)] ifTrue: ^{
+ length.value = [lengthOfMatch call: [[function argumentNamed: @"initial"] plus: ignorable.value], [function argumentNamed: @"state"]];
+ }];
+ }];
+
+ [function argumentNamed: @"outrange"].value = [LLVMStruct structWithValues:
+ [[function argumentNamed: @"initial"] plus: [[ignorable.value equals: LLVMConstant(NSNotFound)] select: LLVMConstant(0) or: ignorable.value]],
+ length.value,
+ nil];
+ [function return: [length notEquals: LLVMConstant(NSNotFound)]];
+ }];
+}
+*/
+
+
+-(LLVMFunction *)defaultRangeOfMatchFunctionForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
NSString *name = [self nameForFunction: @"rangeOfMatchFromCursor:withParser:" forRule: rule];
LLVMFunction *ignorableCharactersFromCursor = [module declareExternalFunctionWithName: @"HammerParserIgnorableCharactersFromCursor" type: [LLVMType functionType: context.integerType, context.untypedPointerType, context.integerType, nil]];
LLVMFunction *rangeOfMatch = [module functionWithName: name];
if(!rangeOfMatch) {
rangeOfMatch = [module functionWithName: name typeName: @"HammerRuleRangeOfMatchFunction"];
[builder positionAtEndOfFunction: rangeOfMatch];
LLVMBlock
*tryIgnorableBlock = [rangeOfMatch appendBlockWithName: @"tryIgnorable"],
*retryAfterIgnorableBlock = [rangeOfMatch appendBlockWithName: @"retryAfterIgnorable"],
*returnBlock = [rangeOfMatch appendBlockWithName: @"return"];
LLVMValue
*notFound = [context constantUnsignedInteger: NSNotFound],
*zero = [context constantUnsignedInteger: 0],
*length = [builder allocateLocal: @"length" type: context.integerType],
*ignorable = [builder allocateLocal: @"ignorable" type: context.integerType];
// NSUInteger length = [self lengthOfMatchFromCursor: initial withParser: parser];
[builder set: length, [builder call: lengthOfMatch, [rangeOfMatch parameterAtIndex: 1], [rangeOfMatch parameterAtIndex: 2], nil]];
// NSUInteger ignorable = NSNotFound;
[builder set: ignorable, notFound];
// if(length == NSNotFound)
[builder if: [builder equal: [builder get: length], notFound] then: tryIgnorableBlock else: returnBlock];
[builder positionAtEndOfBlock: tryIgnorableBlock]; {
// ignorable = HammerParserIgnorableCharactersFromCursor(parser, initial);
[builder set: ignorable, [builder call: ignorableCharactersFromCursor, [rangeOfMatch parameterAtIndex: 2], [rangeOfMatch parameterAtIndex: 1], nil]];
// if(ignorable != NSNotFound)
[builder if: [builder notEqual: [builder get: ignorable], notFound] then: retryAfterIgnorableBlock else: returnBlock];
[builder positionAtEndOfBlock: retryAfterIgnorableBlock]; {
// length = [self lengthOfMatchFromCursor: initial + ignorable withParser: parser];
[builder set: length, [builder call: lengthOfMatch, [builder add: [rangeOfMatch parameterAtIndex: 1], [builder get: ignorable]], [rangeOfMatch parameterAtIndex: 2], nil]];
[builder jumpToBlock: returnBlock];
}
}
[builder positionAtEndOfBlock: returnBlock]; {
[builder setElements: [rangeOfMatch parameterAtIndex: 0],
[builder add:
[rangeOfMatch parameterAtIndex: 1],
[builder condition: [builder equal: [builder get: ignorable], notFound]
then: zero
else: [builder get: ignorable]
]
],
[builder get: length],
nil];
[builder return: [builder notEqual: [builder get: length], notFound]];
}
}
return rangeOfMatch;
}
--(HammerBuiltRuleFunctions *)defaultFunctionsForRule:(HammerRule *)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
+-(HammerBuiltRuleFunctions *)defaultFunctionsForRule:(HammerRuleRef)rule withLengthOfMatchFunction:(LLVMFunction *)lengthOfMatch {
HammerBuiltRuleFunctions *functions = [[[HammerBuiltRuleFunctions alloc] init] autorelease];
functions.lengthOfMatch = lengthOfMatch;
functions.rangeOfMatch = [self defaultRangeOfMatchFunctionForRule: rule withLengthOfMatchFunction: lengthOfMatch];
return functions;
}
-(void)addBuiltFunctions:(HammerBuiltRuleFunctions *)functions {
[builtFunctionsStack.lastObject addObject: functions];
}
-(void)pushRule {
[builtFunctionsStack addObject: [NSMutableArray array]];
}
-(NSArray *)popRule {
NSArray *lastFunctions = [[builtFunctionsStack.lastObject retain] autorelease];
[builtFunctionsStack removeLastObject];
return lastFunctions;
}
-(LLVMFunction *)parserIsAtEndFunction {
return [module declareExternalFunctionWithName: @"HammerParserCursorIsAtEnd" type: [LLVMType functionType: context.int1Type,
context.untypedPointerType,
context.integerType,
nil]];
}
-(LLVMFunction *)parserGetInputStringFunction {
return [module declareExternalFunctionWithName: @"HammerParserGetInputString" type: [LLVMType functionType: context.untypedPointerType, context.untypedPointerType, nil]];
}
--(void)visitRule:(HammerRule *)rule {
- [self pushRule];
-}
-
--(void)leaveRule:(HammerRule *)rule {
- NSArray *subrules = [self popRule];
- NSString *ruleClassNameFragment = [NSStringFromClass([rule class]) substringFromIndex: 6];
- SEL subrulesSelector = NSSelectorFromString([NSString stringWithFormat: @"leave%@:withVisitedSubrules:", ruleClassNameFragment]);
- SEL subruleSelector = NSSelectorFromString([NSString stringWithFormat: @"leave%@:withVisitedSubrule:", ruleClassNameFragment]);
- SEL terminalSelector = NSSelectorFromString([NSString stringWithFormat: @"leave%@:", ruleClassNameFragment]);
- if([self respondsToSelector: subrulesSelector]) {
- [self performSelector: subrulesSelector withObject: rule withObject: subrules];
- } else if([self respondsToSelector: subruleSelector]) {
- [self performSelector: subruleSelector withObject: rule withObject: subrules.lastObject];
- } else if([self respondsToSelector: terminalSelector]) {
- [self performSelector: terminalSelector withObject: rule];
- } else {
- NSLog(@"Donât know how to compile rules of class %@", [rule class]);
- }
-}
-
-
--(NSString *)nameForFunction:(NSString *)function forRule:(HammerRule *)rule {
- return [NSString stringWithFormat: @"-[%@(%@) %@]", NSStringFromClass([rule class]), [printer printRule: rule], function];
+-(NSString *)nameForFunction:(NSString *)function forRule:(HammerRuleRef)rule {
+ return [NSString stringWithFormat: @"%s(%@) %@", RXObjectTypeGetName(RXGetType(rule)), [printer printRule: rule], function];
}
--(NSString *)nameForRule:(HammerRule *)rule {
+-(NSString *)nameForRule:(HammerRuleRef)rule {
return [self nameForFunction: @"lengthOfMatchFromCursor:withParser:" forRule: rule];
}
--(void)leaveAlternationRule:(HammerAlternationRule *)rule withVisitedSubrules:(NSArray *)subrules {
+-(void)leaveAlternationRule:(HammerAlternationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
NSString *name = [self nameForRule: rule];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
LLVMValue *length = [builder allocateLocal: @"length" type: context.integerType];
LLVMBlock *returnBlock = [lengthOfMatch appendBlockWithName: @"return"];
NSUInteger i = 0;
for(HammerBuiltRuleFunctions *subrule in subrules) {
LLVMBlock *subruleBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d", i]];
[builder jumpToBlock: subruleBlock];
[builder positionAtEndOfBlock: subruleBlock];
[builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil]];
LLVMBlock *subruleNotMatchedBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d not matched", i]];
[builder if: [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]] then: returnBlock else: subruleNotMatchedBlock];
[builder positionAtEndOfBlock: subruleNotMatchedBlock];
i++;
}
[builder jumpToBlock: returnBlock];
[builder positionAtEndOfBlock: returnBlock];
[builder return: [builder get: length]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
--(void)leaveCharacterRule:(HammerCharacterRule *)rule {
+-(void)leaveCharacterRule:(HammerCharacterRuleRef)rule {
NSString *name = [self nameForRule: rule];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder return: [builder condition:
[builder not: [builder call: [self parserIsAtEndFunction], [lengthOfMatch parameterAtIndex: 1], [lengthOfMatch parameterAtIndex: 0], nil]]
then: [context constantUnsignedInteger: 1]
else: [context constantUnsignedInteger: NSNotFound]
]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
--(void)leaveCharacterSetRule:(HammerCharacterSetRule *)rule {
+-(void)leaveCharacterSetRule:(HammerCharacterSetRuleRef)rule {
NSString *name = [self nameForRule: rule];
LLVMFunction *isCharacterMemberFunction = [module declareExternalFunctionWithName: @"CFCharacterSetIsCharacterMember" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, context.int16Type, nil]];
LLVMFunction *characterAtIndexFunction = [module declareExternalFunctionWithName: @"CFStringGetCharacterAtIndex" type: [LLVMType functionType: context.int16Type, context.untypedPointerType, context.integerType, nil]];
LLVMValue *notFound = [context constantUnsignedInteger: NSNotFound];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder return: [builder condition: [builder and:
[builder not: [builder call: [self parserIsAtEndFunction], [lengthOfMatch parameterAtIndex: 1], [lengthOfMatch parameterAtIndex: 0], nil]],
[builder call: isCharacterMemberFunction,
- [context constantUntypedPointer: rule.characterSet],
+ [context constantUntypedPointer: HammerCharacterSetRuleGetCharacterSet(rule)],
[builder call: characterAtIndexFunction,
[builder call: [self parserGetInputStringFunction], [lengthOfMatch parameterAtIndex: 1], nil],
[lengthOfMatch parameterAtIndex: 0],
nil],
nil]
]
then: [context constantUnsignedInteger: 1]
else: notFound
]];
}
name = [self nameForFunction: @"range:ofMatchFromCursor:withParser:" forRule: rule];
LLVMFunction *rangeOfMatch = [module functionWithName: name];
if(!rangeOfMatch) {
rangeOfMatch = [module functionWithName: name typeName: @"HammerRuleRangeOfMatchFunction"];
[builder positionAtEndOfFunction: rangeOfMatch];
[builder setElements: [rangeOfMatch parameterAtIndex: 0],
[rangeOfMatch parameterAtIndex: 1],
[context constantUnsignedInteger: 1],
nil];
[builder return: [builder notEqual: [builder call: lengthOfMatch, [rangeOfMatch parameterAtIndex: 1], [rangeOfMatch parameterAtIndex: 2], nil], notFound]];
}
HammerBuiltRuleFunctions *functions = [[[HammerBuiltRuleFunctions alloc] init] autorelease];
functions.lengthOfMatch = lengthOfMatch;
functions.rangeOfMatch = rangeOfMatch;
[self addBuiltFunctions: functions];
}
--(void)leaveConcatenationRule:(HammerConcatenationRule *)rule withVisitedSubrules:(NSArray *)subrules {
+-(void)leaveConcatenationRule:(HammerConcatenationRuleRef)rule withVisitedSubrules:(NSArray *)subrules {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeForName: @"HammerParser"], nil]],
- *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeForName: @"HammerParser"], context.int1Type, nil]];
+ *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
+ *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, nil]];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
[builder call: pushMatchContext, [lengthOfMatch parameterAtIndex: 1], nil];
LLVMValue
*length = [builder allocateLocal: @"length" type: context.integerType],
- *subrange = [builder allocateLocal: @"subrange" type: [module typeForName: @"NSRange"]];
+ *subrange = [builder allocateLocal: @"subrange" type: [module typeNamed: @"NSRange"]];
[builder set: length, [context constantUnsignedInteger: 0]];
LLVMBlock
*notFoundBlock = [lengthOfMatch appendBlockWithName: @"notFound"],
*returnLengthBlock = [lengthOfMatch appendBlockWithName: @"returnLength"];
NSUInteger i = 0;
for(HammerBuiltRuleFunctions *subruleFunctions in subrules) {
LLVMBlock *subruleBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d", i]];
LLVMBlock *subruleFoundBlock = [lengthOfMatch appendBlockWithName: [NSString stringWithFormat: @"subrule %d found", i]];
[builder jumpToBlock: subruleBlock];
[builder positionAtEndOfBlock: subruleBlock]; {
[builder if: [builder call: subruleFunctions.rangeOfMatch,
subrange,
[builder add: [lengthOfMatch parameterAtIndex: 0], [builder get: length]],
[lengthOfMatch parameterAtIndex: 1],
nil] then: subruleFoundBlock else: notFoundBlock];
}
[builder positionAtEndOfBlock: subruleFoundBlock]; {
// length = NSMaxRange(subrange) - initial;
[builder set: length, [builder subtract: [builder add: [builder getElement: subrange atIndex: 0], [builder getElement: subrange atIndex: 1]], [lengthOfMatch parameterAtIndex: 0]]];
}
i++;
}
[builder jumpToBlock: returnLengthBlock];
[builder positionAtEndOfBlock: notFoundBlock]; {
[builder set: length, [context constantUnsignedInteger: NSNotFound]];
[builder jumpToBlock: returnLengthBlock];
}
[builder positionAtEndOfBlock: returnLengthBlock]; {
[builder call: popMatchContext, [lengthOfMatch parameterAtIndex: 1], [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]], nil];
[builder return: [builder get: length]];
}
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
--(void)leaveLiteralConcatenationRule:(HammerLiteralConcatenationRule *)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
+-(void)leaveLiteralConcatenationRule:(HammerLiteralConcatenationRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
NSString *name = [self nameForRule: rule];
LLVMFunction
*getAttemptsIgnorableRule = [module declareExternalFunctionWithName: @"HammerParserGetAttemptsIgnorableRule" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, nil]],
*setAttemptsIgnorableRule = [module declareExternalFunctionWithName: @"HammerParserSetAttemptsIgnorableRule" type: [LLVMType functionType: context.voidType, context.untypedPointerType, context.int1Type, nil]];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfBlock: lengthOfMatch.entryBlock];
LLVMValue
*attemptsIgnorableRule = [builder allocateLocal: @"attemptsIgnorableRule" type: context.int1Type],
*length = [builder allocateLocal: @"length" type: context.integerType];
[builder set: attemptsIgnorableRule, [builder call: getAttemptsIgnorableRule, [lengthOfMatch parameterAtIndex: 1], nil]];
[builder call: setAttemptsIgnorableRule, [lengthOfMatch parameterAtIndex: 1], [context constantNullOfType: context.int1Type], nil];
[builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil]];
[builder call: setAttemptsIgnorableRule, [lengthOfMatch parameterAtIndex: 1], [builder get: attemptsIgnorableRule], nil];
[builder return: [builder get: length]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
--(void)leaveLiteralRule:(HammerLiteralRule *)rule {
+-(void)leaveLiteralRule:(HammerLiteralRuleRef)rule {
NSString *name = [self nameForRule: rule];
LLVMFunction *stringContainsStringAtIndexFunction = [module declareExternalFunctionWithName: @"HammerLiteralRuleStringContainsStringAtIndex" type: [LLVMType functionType: context.int1Type, context.untypedPointerType, context.untypedPointerType, context.integerType, nil]];
LLVMFunction *parserGetInputLengthFunction = [module declareExternalFunctionWithName: @"HammerParserGetInputLength" type: [LLVMType functionType: context.integerType, context.untypedPointerType, nil]];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder return: [builder condition: [builder and:
- [builder unsignedLessOrEqual: [builder add: [lengthOfMatch parameterAtIndex: 0], [context constantUnsignedInteger: rule.literal.length]], [builder call: parserGetInputLengthFunction, [lengthOfMatch parameterAtIndex: 1], nil]],
+ [builder unsignedLessOrEqual: [builder add: [lengthOfMatch parameterAtIndex: 0], [context constantUnsignedInteger: HammerLiteralRuleGetLiteral(rule).length]], [builder call: parserGetInputLengthFunction, [lengthOfMatch parameterAtIndex: 1], nil]],
[builder call: stringContainsStringAtIndexFunction,
[builder call: [self parserGetInputStringFunction], [lengthOfMatch parameterAtIndex: 1], nil],
- [context constantUntypedPointer: rule.literal],
+ [context constantUntypedPointer: HammerLiteralRuleGetLiteral(rule)],
[lengthOfMatch parameterAtIndex: 0],
nil]
]
- then: [context constantUnsignedInteger: rule.literal.length]
+ then: [context constantUnsignedInteger: HammerLiteralRuleGetLiteral(rule).length]
else: [context constantUnsignedInteger: NSNotFound]
]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
--(void)leaveLookaheadRule:(HammerLookaheadRule *)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
+-(void)leaveLookaheadRule:(HammerLookaheadRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
NSString *name = [self nameForRule: rule];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder return: [builder condition: [builder notEqual: [builder call: subrule.lengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil], [context constantUnsignedInteger: NSNotFound]]
- then: [context constantUnsignedInteger: rule.shouldNegate? NSNotFound : 0]
- else: [context constantUnsignedInteger: rule.shouldNegate? 0 : NSNotFound]
+ then: [context constantUnsignedInteger: HammerLookaheadRuleGetNegative(rule)? NSNotFound : 0]
+ else: [context constantUnsignedInteger: HammerLookaheadRuleGetNegative(rule)? 0 : NSNotFound]
]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
--(void)leaveNamedRule:(HammerNamedRule *)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
+-(void)leaveNamedRule:(HammerNamedRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeForName: @"HammerParser"], nil]],
- *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeForName: @"HammerParser"], context.int1Type, [module typeForName: @"HammerRule"], [module typeForName: @"NSString"], [module typeForName: @"NSRange"], nil]];
+ *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
+ *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, [module typeNamed: @"HammerRule"], [module typeNamed: @"NSString"], [module typeNamed: @"NSRange"], nil]];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder call: pushMatchContext, [lengthOfMatch parameterAtIndex: 1], nil];
LLVMValue
- *length = [builder allocateLocal: @"length" type: [module typeForName: @"NSUInteger"]],
- *range = [builder allocateLocal: @"range" type: [module typeForName: @"NSRange"]];
+ *length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
+ *range = [builder allocateLocal: @"range" type: [module typeNamed: @"NSRange"]];
[builder set: length, [builder call: subrule.lengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil]];
[builder setElements: range, [lengthOfMatch parameterAtIndex: 0], [builder get: length], nil];
[builder call: popMatchContext,
[lengthOfMatch parameterAtIndex: 1],
[builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]],
[context constantUntypedPointer: rule],
- [context constantUntypedPointer: rule.name],
+ [context constantUntypedPointer: HammerNamedRuleGetName(rule)],
[builder get: range],
nil];
[builder return: [builder get: length]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
--(void)leaveReferenceRule:(HammerReferenceRule *)rule {
+-(void)leaveReferenceRule:(HammerReferenceRuleRef)rule {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *lengthOfMatchFunctionForReference = [module declareExternalFunctionWithName: @"HammerCompiledRuleLengthOfMatchFunctionForReference" type: [LLVMType functionType: [LLVMType pointerTypeToType: [module typeForName: @"HammerRuleLengthOfMatchFunction"]], [module typeForName: @"HammerParser"], [module typeForName: @"NSString"], nil]],
- *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeForName: @"HammerParser"], nil]],
- *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeForName: @"HammerParser"], context.int1Type, [module typeForName: @"HammerRule"], [module typeForName: @"NSString"], [module typeForName: @"NSRange"], nil]];
+ *lengthOfMatchFunctionForReference = [module declareExternalFunctionWithName: @"HammerCompiledRuleLengthOfMatchFunctionForReference" type: [LLVMType functionType: [LLVMType pointerTypeToType: [module typeNamed: @"HammerRuleLengthOfMatchFunction"]], [module typeNamed: @"HammerParser"], [module typeNamed: @"NSString"], nil]],
+ *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
+ *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndNestMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, [module typeNamed: @"HammerRule"], [module typeNamed: @"NSString"], [module typeNamed: @"NSRange"], nil]];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder call: pushMatchContext, [lengthOfMatch parameterAtIndex: 1], nil];
- LLVMFunction *subruleLengthOfMatch = (LLVMFunction *)[builder call: lengthOfMatchFunctionForReference, [lengthOfMatch parameterAtIndex: 1], [context constantUntypedPointer: rule.reference], nil];
+ LLVMFunction *subruleLengthOfMatch = (LLVMFunction *)[builder call: lengthOfMatchFunctionForReference, [lengthOfMatch parameterAtIndex: 1], [context constantUntypedPointer: HammerReferenceRuleGetReference(rule)], nil];
LLVMValue
- *length = [builder allocateLocal: @"length" type: [module typeForName: @"NSUInteger"]],
- *range = [builder allocateLocal: @"range" type: [module typeForName: @"NSRange"]];
+ *length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
+ *range = [builder allocateLocal: @"range" type: [module typeNamed: @"NSRange"]];
[builder set: length, [builder call: subruleLengthOfMatch, [lengthOfMatch parameterAtIndex: 0], [lengthOfMatch parameterAtIndex: 1], nil]];
[builder setElements: range, [lengthOfMatch parameterAtIndex: 0], [builder get: length], nil];
[builder call: popMatchContext,
[lengthOfMatch parameterAtIndex: 1],
[builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]],
[context constantUntypedPointer: rule],
- [context constantUntypedPointer: rule.reference],
+ [context constantUntypedPointer: HammerReferenceRuleGetReference(rule)],
[builder get: range],
nil];
[builder return: [builder get: length]];
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
--(void)leaveRepetitionRule:(HammerRepetitionRule *)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
+-(void)leaveRepetitionRule:(HammerRepetitionRuleRef)rule withVisitedSubrule:(HammerBuiltRuleFunctions *)subrule {
NSString *name = [self nameForRule: rule];
LLVMFunction
- *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeForName: @"HammerParser"], nil]],
- *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeForName: @"HammerParser"], context.int1Type, nil]];
+ *pushMatchContext = [module declareExternalFunctionWithName: @"HammerParserPushMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], nil]],
+ *popMatchContext = [module declareExternalFunctionWithName: @"HammerParserPopAndPassUpMatchContext" type: [LLVMType functionType: context.voidType, [module typeNamed: @"HammerParser"], context.int1Type, nil]];
LLVMFunction *lengthOfMatch = [module functionWithName: name];
if(!lengthOfMatch) {
lengthOfMatch = [module functionWithName: name typeName: @"HammerRuleLengthOfMatchFunction"];
[builder positionAtEndOfFunction: lengthOfMatch];
[builder call: pushMatchContext, [lengthOfMatch parameterAtIndex: 1], nil];
LLVMValue
- *length = [builder allocateLocal: @"length" type: [module typeForName: @"NSUInteger"]],
+ *length = [builder allocateLocal: @"length" type: [module typeNamed: @"NSUInteger"]],
*count = [builder allocateLocal: @"count" type: context.int64Type],
- *subrange = [builder allocateLocal: @"subrange" type: [module typeForName: @"NSRange"]];
+ *subrange = [builder allocateLocal: @"subrange" type: [module typeNamed: @"NSRange"]];
[builder set: length, [context constantUnsignedInteger: 0]];
[builder set: count, [context constantUnsignedInt64: 0]];
LLVMBlock
*loopBlock = [lengthOfMatch appendBlockWithName: @"loop"],
*subruleTestBlock = [lengthOfMatch appendBlockWithName: @"subrule test"],
*subruleMatchedBlock = [lengthOfMatch appendBlockWithName: @"subrule matched"],
*returnBlock = [lengthOfMatch appendBlockWithName: @"return"];
LLVMValue
*unbounded = [context constantUnsignedInt64: HammerRepetitionRuleUnboundedMaximum],
- *maximum = [context constantUnsignedInt64: rule.maximum],
- *minimum = [context constantUnsignedInt64: rule.minimum];
+ *maximum = [context constantUnsignedInt64: HammerRepetitionRuleGetMaximum(rule)],
+ *minimum = [context constantUnsignedInt64: HammerRepetitionRuleGetMinimum(rule)];
[builder jumpToBlock: loopBlock];
[builder positionAtEndOfBlock: loopBlock]; {
[builder if: [builder or: [builder equal: maximum, unbounded], [builder unsignedLessThan: [builder get: count], maximum]] then: subruleTestBlock else: returnBlock];
}
[builder positionAtEndOfBlock: subruleTestBlock]; {
[builder set: count, [builder add: [builder get: count], [context constantUnsignedInt64: 1]]];
[builder if: [builder call: subrule.rangeOfMatch, subrange, [builder add: [lengthOfMatch parameterAtIndex: 0], [builder get: length]], [lengthOfMatch parameterAtIndex: 1], nil] then: subruleMatchedBlock else: returnBlock];
}
[builder positionAtEndOfBlock: subruleMatchedBlock]; {
[builder set: length, [builder subtract: [builder add: [builder getElement: subrange atIndex: 0], [builder getElement: subrange atIndex: 1]], [lengthOfMatch parameterAtIndex: 0]]];
[builder jumpToBlock: loopBlock];
}
[builder positionAtEndOfBlock: returnBlock]; {
[builder set: length, [builder condition: (
- (rule.maximum == HammerRepetitionRuleUnboundedMaximum)
+ (HammerRepetitionRuleGetMaximum(rule) == HammerRepetitionRuleUnboundedMaximum)
? [builder unsignedLessThan: minimum, [builder get: count]]
: [builder and: [builder unsignedLessThan: minimum, [builder get: count]], [builder unsignedLessOrEqual: [builder get: count], maximum]]
)
then: [builder get: length]
else: [context constantUnsignedInteger: NSNotFound]
]];
[builder call: popMatchContext, [lengthOfMatch parameterAtIndex: 1], [builder notEqual: [builder get: length], [context constantUnsignedInteger: NSNotFound]], nil];
[builder return: [builder get: length]];
}
}
[self addBuiltFunctions: [self defaultFunctionsForRule: rule withLengthOfMatchFunction: lengthOfMatch]];
}
@end
diff --git a/External/Auspicion b/External/Auspicion
index f02e8b0..06810f3 160000
--- a/External/Auspicion
+++ b/External/Auspicion
@@ -1 +1 @@
-Subproject commit f02e8b0bdfe8aa5e0b6953d9f0903439e5be6f2b
+Subproject commit 06810f3339ba70e353acacc8f421156a1fdded20
diff --git a/External/Hammer b/External/Hammer
index eca5b6e..da1df2c 160000
--- a/External/Hammer
+++ b/External/Hammer
@@ -1 +1 @@
-Subproject commit eca5b6e54d4af9a2d20d1668d68bb7fe894caa84
+Subproject commit da1df2c07f53348aa88634cfb892df5a20f06322
diff --git a/External/Include/Hammer/HammerContainerRule.h b/External/Include/Hammer/HammerContainerRule.h
deleted file mode 100644
index c889113..0000000
--- a/External/Include/Hammer/HammerContainerRule.h
+++ /dev/null
@@ -1,20 +0,0 @@
-// HammerContainerRule.h
-// Created by Rob Rix on 2009-12-04
-// Copyright 2009 Monochrome Industries
-
-/*
-Exists to remove some duplication.
-*/
-
-#import <Hammer/HammerRule.h>
-
-@interface HammerContainerRule : HammerRule {
- HammerRule *subrule;
-}
-
-+(id)ruleWithSubrule:(HammerRule *)_subrule;
--(id)initWithSubrule:(HammerRule *)_subrule;
-
-@property (nonatomic, readonly) HammerRule *subrule;
-
-@end
\ No newline at end of file
diff --git a/External/Include/Hammer/HammerError.h b/External/Include/Hammer/HammerError.h
deleted file mode 100644
index 869eb0b..0000000
--- a/External/Include/Hammer/HammerError.h
+++ /dev/null
@@ -1,22 +0,0 @@
-// HammerError.h
-// Created by Rob Rix on 2009-09-27
-// Copyright 2009 Monochrome Industries
-
-#import <Foundation/Foundation.h>
-
-extern NSString * const HammerErrorDomain;
-
-enum {
- HammerParserParseFailedError = -1,
- HammerAlternationRuleNoAlternativeErrorCode = -2
-};
-typedef NSInteger HammerErrorCode;
-
-@class HammerAlternationRule, HammerParser;
-
-@interface HammerError : NSError
-
-+(id)parseFailedErrorInRange:(NSRange)range ofGrammar:(NSString *)grammar resultingParser:(HammerParser *)parser;
-+(id)noMatchingAlternativeErrorAtIndex:(NSUInteger)index withAlternationRule:(HammerAlternationRule *)rule;
-
-@end
\ No newline at end of file
diff --git a/External/Include/Hammer/HammerParser.h b/External/Include/Hammer/HammerParser.h
deleted file mode 100644
index 2bdfbeb..0000000
--- a/External/Include/Hammer/HammerParser.h
+++ /dev/null
@@ -1,113 +0,0 @@
-// HammerParser.h
-// Created by Rob Rix on 2007-12-14
-// Copyright 2007 Monochrome Industries
-
-#import <Foundation/Foundation.h>
-
-@class HammerAlternationRule, HammerMatch, HammerReferenceRule, HammerRule;
-@protocol HammerParserDelegate;
-
-@interface HammerParser : NSObject <NSCopying, NSCoding> {
- NSDictionary *rules;
- NSMutableArray *parentParsers;
- NSMutableArray *matchContextStack;
- NSError *tempError;
- NSUInteger errorDepth;
- NSMutableArray *_errors;
- NSString *string;
- id<HammerParserDelegate> delegate;
- NSUInteger cursor;
- BOOL isIgnoringMatches;
- BOOL isParsing;
- BOOL attemptsIgnorableRule;
-}
-
-+(HammerParser *)parserWithGrammar:(NSString *)grammar relativeToBaseURL:(NSURL *)baseURL error:(NSError **)error;
-+(HammerParser *)parserWithGrammar:(NSString *)grammar error:(NSError **)error;
-+(HammerParser *)parserWithContentsOfURL:(NSURL *)grammarURL error:(NSError **)error;
-
-@property (nonatomic, copy) NSDictionary *rules;
--(HammerRule *)ruleForReference:(NSString *)reference;
-
-// imports are done via differential inheritance
--(void)importRulesFromParser:(HammerParser *)parser;
--(BOOL)importRulesFromGrammarAtURL:(NSURL *)grammarURL error:(NSError **)error;
-
-@property (nonatomic, readonly) HammerRule *mainRule;
-@property (nonatomic, readonly) HammerRule *ignorableRule;
-
--(NSUInteger)ignorableCharactersFromCursor:(NSUInteger)initial;
-@property (nonatomic, readonly) BOOL isIgnoringMatches;
-@property (nonatomic) BOOL attemptsIgnorableRule;
-
-@property (nonatomic, readonly, copy) NSString *string;
-
-@property (nonatomic, assign) id<HammerParserDelegate> delegate;
-
-@property (nonatomic) NSUInteger cursor;
-@property (nonatomic, readonly) BOOL isAtEnd;
--(BOOL)cursorIsAtEnd:(NSUInteger)initial;
-
--(BOOL)parse:(NSString *)str;
-
-@property (nonatomic, readonly) BOOL isParsing;
-
--(NSString *)toGrammar;
-
-@end
-
-
-@interface HammerParser () // feedback from matches
-
-@property (nonatomic, readonly) NSMutableDictionary *currentMatchContext;
-
--(void)pushMatchContext;
--(void)popAndDiscardMatchContext;
--(void)popAndPassUpMatchContext;
--(void)popAndPassUpMatchContext:(BOOL)shouldPassUp;
--(void)popAndNestMatchContext:(BOOL)shouldPassUp inRule:(HammerRule *)rule forKey:(NSString *)key inRange:(NSRange)range;
-
-@end
-
-
-@interface HammerParser () // error handling
-
-@property (nonatomic, readonly) NSError *currentErrorContext;
-
--(void)addError:(NSError *)error;
-
--(void)pushErrorContext;
--(NSError *)popErrorContext;
-
-@property (nonatomic, copy, readonly) NSArray *errors;
-
-@end
-
-
-@protocol HammerParserDelegate <NSObject>
-
-@optional
-
-// fixme: return an error by reference
-// if, for a given rule name <name>, the document responds to the slightly different selector âparser:<name>Rule:didMatch:â, that message will be sent instead of this
--(id)parser:(HammerParser *)parser rule:(HammerReferenceRule *)rule didMatch:(HammerMatch *)match error:(NSError **)error; // so implement this when developing and you can watch what comes in that you werenât expecting yet.
-
--(void)parser:(HammerParser *)parser rule:(HammerAlternationRule *)rule parseErrorOccurred:(NSError *)error;
-
-@end
-
-
-// C API
-BOOL HammerParserCursorIsAtEnd(HammerParser *parser, NSUInteger cursor);
-
-NSUInteger HammerParserGetInputLength(HammerParser *parser);
-NSString *HammerParserGetInputString(HammerParser *parser);
-
-NSUInteger HammerParserIgnorableCharactersFromCursor(HammerParser *parser, NSUInteger cursor);
-
-BOOL HammerParserGetAttemptsIgnorableRule(HammerParser *parser);
-void HammerParserSetAttemptsIgnorableRule(HammerParser *parser, BOOL _attemptsIgnorableRule);
-
-void HammerParserPushMatchContext(HammerParser *parser);
-void HammerParserPopAndPassUpMatchContext(HammerParser *parser, BOOL shouldPassUp);
-void HammerParserPopAndNestMatchContext(HammerParser *parser, BOOL shouldPassUp, HammerRule *rule, NSString *key, NSRange range);
diff --git a/External/RXAssertions b/External/RXAssertions
deleted file mode 160000
index 11b00db..0000000
--- a/External/RXAssertions
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 11b00dbc07bea37324290dd9e9faa537720e3e55
diff --git a/Other Sources/bootstrap-hammerc.m b/Other Sources/bootstrap-hammerc.m
index 024e94a..1b37f9b 100644
--- a/Other Sources/bootstrap-hammerc.m
+++ b/Other Sources/bootstrap-hammerc.m
@@ -1,14 +1,27 @@
// bootstrap-hammerc.m
// Created by Rob Rix on 2010-03-03
// Copyright 2010 Monochrome Industries
#import <Foundation/Foundation.h>
-int main (int argc, const char * argv[]) {
+#import <Hammer/Hammer.h>
+
+#import "HammerRuleCompiler.h"
+
+int main(int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ HammerRuleGraphRef grammar = [HammerBuilder grammarRuleGraph];
+ HammerRuleCompiler *compiler = [[HammerRuleCompiler alloc] init];
+ for(NSString *ruleName in grammar) {
+ HammerRuleRef rule = HammerRuleGraphGetRuleForName(grammar, ruleName);
+ HammerRuleRef compiledRule = [compiler compileRule: rule];
+ }
+ // the rules shouldnât be JITed, they should just be outputâhow?
+ // then they should actually be assembled via llc?
+ // where does optimization come in?
[pool drain];
return 0;
}
diff --git a/Other Sources/hammerc.m b/Other Sources/hammerc.m
index 85f6572..e9ce70d 100644
--- a/Other Sources/hammerc.m
+++ b/Other Sources/hammerc.m
@@ -1,14 +1,14 @@
// hammerc.m
// Created by Rob Rix on 2010-03-03
// Copyright 2010 Monochrome Industries
#import <Foundation/Foundation.h>
-int main (int argc, const char * argv[]) {
+int main(int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool drain];
return 0;
}
diff --git a/Tasks.taskpaper b/Tasks.taskpaper
index 43e5a60..d40feed 100644
--- a/Tasks.taskpaper
+++ b/Tasks.taskpaper
@@ -1,3 +1,4 @@
-- include Hammer in Extermal @done(2010-03-04)
-- include Auspicion in External @done(2010-03-04)
-- make a static library of Auspicion @done(2010-03-04)
+- write a parser for `@encode()` directive strings.
+- provide JIT-compiled implementations of the match methods for rules, written in Auspicion. Use those in Hammer, and use them in hammerc as the components of the static compilation.
+ Is that even possible, i.e. resolving function calls and replacing them with static ones?
+- inline everything.
diff --git a/hammerc.xcodeproj/project.pbxproj b/hammerc.xcodeproj/project.pbxproj
index 3f23c26..0d21f30 100644
--- a/hammerc.xcodeproj/project.pbxproj
+++ b/hammerc.xcodeproj/project.pbxproj
@@ -1,927 +1,1065 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 45;
objects = {
/* Begin PBXBuildFile section */
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859EA3029092ED04C91782 /* hammerc.1 */; };
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */; };
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */; };
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */; };
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */; };
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */; };
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */; };
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */; };
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */; };
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */; };
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */; };
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */; };
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E51113F5FEF0086F21C /* hammerc.m */; };
D4551E82113F85830086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
D4551E9A113F85CA0086F21C /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E95113F85C20086F21C /* libAuspicion.a */; };
D4551E9B113F85CC0086F21C /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E95113F85C20086F21C /* libAuspicion.a */; };
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EBA113F88300086F21C /* bootstrap-hammerc.m */; };
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E49113F5FC80086F21C /* HammerCompiledRule.m */; };
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */; };
D4551EE3113F88700086F21C /* digit.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC3113F88700086F21C /* digit.grammar */; };
D4551EE4113F88700086F21C /* letter.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EC4113F88700086F21C /* letter.grammar */; };
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */; };
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC7113F88700086F21C /* HammerBuilderTests.m */; };
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */; };
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */; };
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */; };
D4551EEA113F88700086F21C /* HammerContainerRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */; };
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */; };
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */; };
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */; };
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */; };
D4551EEF113F88700086F21C /* HammerParserTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED7113F88700086F21C /* HammerParserTests.m */; };
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */; };
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */; };
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */; };
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EDE113F88700086F21C /* HammerRuleTests.m */; };
D4551EF4113F88700086F21C /* HammerTestParser.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EE0113F88700086F21C /* HammerTestParser.m */; };
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */; };
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */ = {isa = PBXBuildFile; fileRef = D4551EF7113F88A00086F21C /* Hammer.grammar */; };
D4551EFB113F88B80086F21C /* libAuspicion.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E95113F85C20086F21C /* libAuspicion.a */; };
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4551E7B113F85780086F21C /* libHammer.a */; };
- D4551F0B113F8E270086F21C /* RXAssertions.m in Sources */ = {isa = PBXBuildFile; fileRef = D4551F0A113F8E270086F21C /* RXAssertions.m */; };
+ D48B23EB11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */; };
+ D48B23EC11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */; };
+ D48B23ED11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */; };
+ D48B23EE11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */; };
+ D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */ = {isa = PBXBuildFile; fileRef = D48B24BC11B25720007CBBB4 /* RXAssertions.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D4551DFE113E48B20086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
proxyType = 1;
- remoteGlobalIDString = D4551DF9113E48A90086F21C /* bootstrap-hammerc */;
+ remoteGlobalIDString = D4551DF9113E48A90086F21C;
remoteInfo = "bootstrap-hammerc";
};
D4551E7A113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D4041AB1113BB80D005F156E /* libHammer.a */;
+ remoteGlobalIDString = D4041AB1113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
- D4551E7C113F85780086F21C /* PBXContainerItemProxy */ = {
- isa = PBXContainerItemProxy;
- containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
- proxyType = 2;
- remoteGlobalIDString = 8DC2EF5B0486A6940098B216 /* Hammer.framework */;
- remoteInfo = Hammer;
- };
D4551E7E113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D4DB11D60D138C7400C730A3 /* Tests.octest */;
+ remoteGlobalIDString = D4DB11D60D138C7400C730A3;
remoteInfo = Tests;
};
D4551E80113F85780086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D404EB4610F5791C007612E9 /* Measure Performance */;
+ remoteGlobalIDString = D404EB4610F5791C007612E9;
remoteInfo = "Measure Performance";
};
D4551E94113F85C20086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D2AAC07E0554694100DB518D /* libAuspicion.a */;
+ remoteGlobalIDString = D2AAC07E0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4551E96113F85C20086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D407954F10EB27140061CF6C /* Auspicion.framework */;
+ remoteGlobalIDString = D407954F10EB27140061CF6C;
remoteInfo = "Auspicion (Framework)";
};
D4551E98113F85C20086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
proxyType = 2;
- remoteGlobalIDString = D4D9DE5510EB5F4F003EEE90 /* libAuspicionLLVM.a */;
+ remoteGlobalIDString = D4D9DE5510EB5F4F003EEE90;
remoteInfo = AuspicionLLVM;
};
D4551E9C113F85D70086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
- remoteGlobalIDString = D4041AB0113BB80D005F156E /* Hammer (Static Library) */;
+ remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
D4551E9E113F85DA0086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
proxyType = 1;
- remoteGlobalIDString = D2AAC07D0554694100DB518D /* Auspicion (Static Library) */;
+ remoteGlobalIDString = D2AAC07D0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4551EFD113F88CA0086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
proxyType = 1;
- remoteGlobalIDString = D2AAC07D0554694100DB518D /* Auspicion (Static Library) */;
+ remoteGlobalIDString = D2AAC07D0554694100DB518D;
remoteInfo = "Auspicion (Static Library)";
};
D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
proxyType = 1;
- remoteGlobalIDString = D4041AB0113BB80D005F156E /* Hammer (Static Library) */;
+ remoteGlobalIDString = D4041AB0113BB80D005F156E;
remoteInfo = "Hammer (Static Library)";
};
+ D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
+ proxyType = 2;
+ remoteGlobalIDString = D2AAC046055464E500DB518D /* libPolymorph.a */;
+ remoteInfo = Polymorph;
+ };
+ D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
+ proxyType = 2;
+ remoteGlobalIDString = D4AB04351180335A0048BBA1 /* Tests.octest */;
+ remoteInfo = Tests;
+ };
+ D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
+ proxyType = 2;
+ remoteGlobalIDString = D2AAC07E0554694100DB518D /* libRXAssertions.a */;
+ remoteInfo = RXAssertions;
+ };
+ D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
+ proxyType = 2;
+ remoteGlobalIDString = D442A488106FD94900944F07 /* Tests.octest */;
+ remoteInfo = Tests;
+ };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
8DD76F9E0486AA7600D96B5E /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 8;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
8DD76F9F0486AA7600D96B5E /* hammerc.1 in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
8DD76FA10486AA7600D96B5E /* hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = hammerc; sourceTree = BUILT_PRODUCTS_DIR; };
C6859EA3029092ED04C91782 /* hammerc.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = hammerc.1; sourceTree = "<group>"; };
D4551DFA113E48A90086F21C /* bootstrap-hammerc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "bootstrap-hammerc"; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E28113F5F6D0086F21C /* Tests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Tests.octest; sourceTree = BUILT_PRODUCTS_DIR; };
D4551E29113F5F6D0086F21C /* Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Tests-Info.plist"; sourceTree = "<group>"; };
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledAlternationRuleTests.m; sourceTree = "<group>"; };
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterRuleTests.m; sourceTree = "<group>"; };
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLiteralRuleTests.m; sourceTree = "<group>"; };
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledNamedRuleTests.m; sourceTree = "<group>"; };
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledReferenceRuleTests.m; sourceTree = "<group>"; };
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompilerTests.m; sourceTree = "<group>"; };
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCompiledRule.h; sourceTree = "<group>"; };
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCompiledRule.m; sourceTree = "<group>"; };
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleCompiler.h; sourceTree = "<group>"; };
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleCompiler.m; sourceTree = "<group>"; };
D4551E51113F5FEF0086F21C /* hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = hammerc.m; sourceTree = "<group>"; };
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hammerc_Prefix.pch; sourceTree = "<group>"; };
D4551E6E113F85780086F21C /* Hammer.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Hammer.xcodeproj; sourceTree = "<group>"; };
D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Auspicion.xcodeproj; sourceTree = "<group>"; };
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "bootstrap-hammerc.m"; sourceTree = "<group>"; };
D4551EC3113F88700086F21C /* digit.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = digit.grammar; sourceTree = "<group>"; };
D4551EC4113F88700086F21C /* letter.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = letter.grammar; sourceTree = "<group>"; };
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerAlternationRuleTests.h; sourceTree = "<group>"; };
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerAlternationRuleTests.m; sourceTree = "<group>"; };
D4551EC7113F88700086F21C /* HammerBuilderTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerBuilderTests.m; sourceTree = "<group>"; };
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterRuleTests.h; sourceTree = "<group>"; };
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterRuleTests.m; sourceTree = "<group>"; };
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerCharacterSetRuleTests.h; sourceTree = "<group>"; };
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerCharacterSetRuleTests.m; sourceTree = "<group>"; };
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerContainerRuleTests.m; sourceTree = "<group>"; };
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralConcatenationRuleTests.h; sourceTree = "<group>"; };
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralConcatenationRuleTests.m; sourceTree = "<group>"; };
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLiteralRuleTests.h; sourceTree = "<group>"; };
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLiteralRuleTests.m; sourceTree = "<group>"; };
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerLookaheadRuleTests.h; sourceTree = "<group>"; };
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerLookaheadRuleTests.m; sourceTree = "<group>"; };
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerNamedRuleTests.h; sourceTree = "<group>"; };
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerNamedRuleTests.m; sourceTree = "<group>"; };
D4551ED7113F88700086F21C /* HammerParserTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerParserTests.m; sourceTree = "<group>"; };
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerReferenceRuleTests.h; sourceTree = "<group>"; };
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerReferenceRuleTests.m; sourceTree = "<group>"; };
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRepetitionRuleTests.h; sourceTree = "<group>"; };
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRepetitionRuleTests.m; sourceTree = "<group>"; };
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRulePrinterTests.m; sourceTree = "<group>"; };
D4551EDD113F88700086F21C /* HammerRuleTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerRuleTests.h; sourceTree = "<group>"; };
D4551EDE113F88700086F21C /* HammerRuleTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerRuleTests.m; sourceTree = "<group>"; };
D4551EDF113F88700086F21C /* HammerTestParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestParser.h; sourceTree = "<group>"; };
D4551EE0113F88700086F21C /* HammerTestParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestParser.m; sourceTree = "<group>"; };
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HammerTestRuleVisitor.h; sourceTree = "<group>"; };
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HammerTestRuleVisitor.m; sourceTree = "<group>"; };
D4551EF7113F88A00086F21C /* Hammer.grammar */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Hammer.grammar; sourceTree = "<group>"; };
- D4551F09113F8E270086F21C /* RXAssertions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAssertions.h; sourceTree = "<group>"; };
- D4551F0A113F8E270086F21C /* RXAssertions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RXAssertions.m; sourceTree = "<group>"; };
+ D48B23E711B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "LLVMModule+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
+ D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "LLVMModule+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
+ D48B23E911B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "LLVMType+RuntimeTypeEncodings.h"; sourceTree = "<group>"; };
+ D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "LLVMType+RuntimeTypeEncodings.m"; sourceTree = "<group>"; };
+ D48B247911B25720007CBBB4 /* RXAllocation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAllocation.h; sourceTree = "<group>"; };
+ D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXCoreFoundationIntegration.h; sourceTree = "<group>"; };
+ D48B247D11B25720007CBBB4 /* RXObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObject.h; sourceTree = "<group>"; };
+ D48B248011B25720007CBBB4 /* RXObjectType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXObjectType.h; sourceTree = "<group>"; };
+ D48B248111B25720007CBBB4 /* RXShadowObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXShadowObject.h; sourceTree = "<group>"; };
+ D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = Polymorph.xcodeproj; sourceTree = "<group>"; };
+ D48B24BB11B25720007CBBB4 /* RXAssertions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RXAssertions.h; sourceTree = "<group>"; };
+ D48B24BC11B25720007CBBB4 /* RXAssertions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RXAssertions.m; sourceTree = "<group>"; };
+ D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = RXAssertions.xcodeproj; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
8DD76F9B0486AA7600D96B5E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E9A113F85CA0086F21C /* libAuspicion.a in Frameworks */,
D4551E82113F85830086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF8113E48A90086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E9B113F85CC0086F21C /* libAuspicion.a in Frameworks */,
D4551E85113F858B0086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E25113F5F6D0086F21C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D4551EFB113F88B80086F21C /* libAuspicion.a in Frameworks */,
D4551EFC113F88B80086F21C /* libHammer.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
08FB7794FE84155DC02AAC07 /* hammerc */ = {
isa = PBXGroup;
children = (
+ D48B23E611B24D5E007CBBB4 /* Categories */,
08FB7795FE84155DC02AAC07 /* Classes */,
D4551E50113F5FEF0086F21C /* Other Sources */,
D4551E30113F5FB10086F21C /* Tests */,
C6859EA2029092E104C91782 /* Documentation */,
D4551E6B113F85410086F21C /* External */,
D4551E2F113F5F7D0086F21C /* Resources */,
1AB674ADFE9D54B511CA2CBB /* Products */,
);
name = hammerc;
sourceTree = "<group>";
};
08FB7795FE84155DC02AAC07 /* Classes */ = {
isa = PBXGroup;
children = (
D4551E48113F5FC80086F21C /* HammerCompiledRule.h */,
D4551E49113F5FC80086F21C /* HammerCompiledRule.m */,
D4551E4A113F5FC80086F21C /* HammerRuleCompiler.h */,
D4551E4B113F5FC80086F21C /* HammerRuleCompiler.m */,
);
path = Classes;
sourceTree = "<group>";
};
1AB674ADFE9D54B511CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
8DD76FA10486AA7600D96B5E /* hammerc */,
D4551DFA113E48A90086F21C /* bootstrap-hammerc */,
D4551E28113F5F6D0086F21C /* Tests.octest */,
);
name = Products;
sourceTree = "<group>";
};
C6859EA2029092E104C91782 /* Documentation */ = {
isa = PBXGroup;
children = (
C6859EA3029092ED04C91782 /* hammerc.1 */,
);
path = Documentation;
sourceTree = "<group>";
};
D4551E2F113F5F7D0086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551E29113F5F6D0086F21C /* Tests-Info.plist */,
);
path = Resources;
sourceTree = "<group>";
};
D4551E30113F5FB10086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551E31113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m */,
D4551E32113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m */,
D4551E33113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m */,
D4551E34113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m */,
D4551E35113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m */,
D4551E36113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m */,
D4551E37113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m */,
D4551E38113F5FB10086F21C /* HammerCompiledNamedRuleTests.m */,
D4551E39113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m */,
D4551E3A113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m */,
D4551E3B113F5FB10086F21C /* HammerRuleCompilerTests.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551E50113F5FEF0086F21C /* Other Sources */ = {
isa = PBXGroup;
children = (
D4551EBA113F88300086F21C /* bootstrap-hammerc.m */,
D4551E51113F5FEF0086F21C /* hammerc.m */,
D4551E52113F5FEF0086F21C /* hammerc_Prefix.pch */,
);
path = "Other Sources";
sourceTree = "<group>";
};
D4551E6B113F85410086F21C /* External */ = {
isa = PBXGroup;
children = (
D4551E6D113F855E0086F21C /* Auspicion */,
D4551E6C113F85530086F21C /* Hammer */,
- D4551F08113F8E0A0086F21C /* RXAssertions */,
);
path = External;
sourceTree = "<group>";
};
D4551E6C113F85530086F21C /* Hammer */ = {
isa = PBXGroup;
children = (
D4551E6E113F85780086F21C /* Hammer.xcodeproj */,
+ D48B244C11B25720007CBBB4 /* External */,
D4551EF6113F88930086F21C /* Resources */,
D4551EC1113F88700086F21C /* Tests */,
);
path = Hammer;
sourceTree = "<group>";
};
D4551E6D113F855E0086F21C /* Auspicion */ = {
isa = PBXGroup;
children = (
D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */,
);
path = Auspicion;
sourceTree = "<group>";
};
D4551E6F113F85780086F21C /* Products */ = {
isa = PBXGroup;
children = (
D4551E7B113F85780086F21C /* libHammer.a */,
- D4551E7D113F85780086F21C /* Hammer.framework */,
D4551E7F113F85780086F21C /* Tests.octest */,
D4551E81113F85780086F21C /* Measure Performance */,
);
name = Products;
sourceTree = "<group>";
};
D4551E8C113F85C20086F21C /* Products */ = {
isa = PBXGroup;
children = (
D4551E95113F85C20086F21C /* libAuspicion.a */,
D4551E97113F85C20086F21C /* Auspicion.framework */,
D4551E99113F85C20086F21C /* libAuspicionLLVM.a */,
);
name = Products;
sourceTree = "<group>";
};
D4551EC1113F88700086F21C /* Tests */ = {
isa = PBXGroup;
children = (
D4551EC2113F88700086F21C /* Fixtures */,
D4551EC5113F88700086F21C /* HammerAlternationRuleTests.h */,
D4551EC6113F88700086F21C /* HammerAlternationRuleTests.m */,
D4551EC7113F88700086F21C /* HammerBuilderTests.m */,
D4551EC8113F88700086F21C /* HammerCharacterRuleTests.h */,
D4551EC9113F88700086F21C /* HammerCharacterRuleTests.m */,
D4551ECA113F88700086F21C /* HammerCharacterSetRuleTests.h */,
D4551ECB113F88700086F21C /* HammerCharacterSetRuleTests.m */,
D4551ECC113F88700086F21C /* HammerConcatenationRuleTests.h */,
D4551ECD113F88700086F21C /* HammerConcatenationRuleTests.m */,
D4551ECE113F88700086F21C /* HammerContainerRuleTests.m */,
D4551ECF113F88700086F21C /* HammerLiteralConcatenationRuleTests.h */,
D4551ED0113F88700086F21C /* HammerLiteralConcatenationRuleTests.m */,
D4551ED1113F88700086F21C /* HammerLiteralRuleTests.h */,
D4551ED2113F88700086F21C /* HammerLiteralRuleTests.m */,
D4551ED3113F88700086F21C /* HammerLookaheadRuleTests.h */,
D4551ED4113F88700086F21C /* HammerLookaheadRuleTests.m */,
D4551ED5113F88700086F21C /* HammerNamedRuleTests.h */,
D4551ED6113F88700086F21C /* HammerNamedRuleTests.m */,
D4551ED7113F88700086F21C /* HammerParserTests.m */,
D4551ED8113F88700086F21C /* HammerReferenceRuleTests.h */,
D4551ED9113F88700086F21C /* HammerReferenceRuleTests.m */,
D4551EDA113F88700086F21C /* HammerRepetitionRuleTests.h */,
D4551EDB113F88700086F21C /* HammerRepetitionRuleTests.m */,
D4551EDC113F88700086F21C /* HammerRulePrinterTests.m */,
D4551EDD113F88700086F21C /* HammerRuleTests.h */,
D4551EDE113F88700086F21C /* HammerRuleTests.m */,
D4551EDF113F88700086F21C /* HammerTestParser.h */,
D4551EE0113F88700086F21C /* HammerTestParser.m */,
D4551EE1113F88700086F21C /* HammerTestRuleVisitor.h */,
D4551EE2113F88700086F21C /* HammerTestRuleVisitor.m */,
);
path = Tests;
sourceTree = "<group>";
};
D4551EC2113F88700086F21C /* Fixtures */ = {
isa = PBXGroup;
children = (
D4551EC3113F88700086F21C /* digit.grammar */,
D4551EC4113F88700086F21C /* letter.grammar */,
);
path = Fixtures;
sourceTree = "<group>";
};
D4551EF6113F88930086F21C /* Resources */ = {
isa = PBXGroup;
children = (
D4551EF7113F88A00086F21C /* Hammer.grammar */,
);
path = Resources;
sourceTree = "<group>";
};
- D4551F08113F8E0A0086F21C /* RXAssertions */ = {
+ D48B23E611B24D5E007CBBB4 /* Categories */ = {
isa = PBXGroup;
children = (
- D4551F09113F8E270086F21C /* RXAssertions.h */,
- D4551F0A113F8E270086F21C /* RXAssertions.m */,
+ D48B23E711B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.h */,
+ D48B23E811B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m */,
+ D48B23E911B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.h */,
+ D48B23EA11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m */,
+ );
+ path = Categories;
+ sourceTree = "<group>";
+ };
+ D48B244C11B25720007CBBB4 /* External */ = {
+ isa = PBXGroup;
+ children = (
+ D48B244D11B25720007CBBB4 /* Polymorph */,
+ D48B249111B25720007CBBB4 /* RXAssertions */,
+ );
+ path = External;
+ sourceTree = "<group>";
+ };
+ D48B244D11B25720007CBBB4 /* Polymorph */ = {
+ isa = PBXGroup;
+ children = (
+ D48B247811B25720007CBBB4 /* Classes */,
+ D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */,
+ );
+ path = Polymorph;
+ sourceTree = "<group>";
+ };
+ D48B247811B25720007CBBB4 /* Classes */ = {
+ isa = PBXGroup;
+ children = (
+ D48B247911B25720007CBBB4 /* RXAllocation.h */,
+ D48B247B11B25720007CBBB4 /* RXCoreFoundationIntegration.h */,
+ D48B247D11B25720007CBBB4 /* RXObject.h */,
+ D48B248011B25720007CBBB4 /* RXObjectType.h */,
+ D48B248111B25720007CBBB4 /* RXShadowObject.h */,
+ );
+ path = Classes;
+ sourceTree = "<group>";
+ };
+ D48B248B11B25720007CBBB4 /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ D48B24E211B25721007CBBB4 /* libPolymorph.a */,
+ D48B24E411B25721007CBBB4 /* Tests.octest */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
+ D48B249111B25720007CBBB4 /* RXAssertions */ = {
+ isa = PBXGroup;
+ children = (
+ D48B24BB11B25720007CBBB4 /* RXAssertions.h */,
+ D48B24BC11B25720007CBBB4 /* RXAssertions.m */,
+ D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */,
);
path = RXAssertions;
sourceTree = "<group>";
};
+ D48B24BF11B25720007CBBB4 /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ D48B24EB11B25721007CBBB4 /* libRXAssertions.a */,
+ D48B24ED11B25721007CBBB4 /* Tests.octest */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
8DD76F960486AA7600D96B5E /* hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */;
buildPhases = (
8DD76F990486AA7600D96B5E /* Sources */,
8DD76F9B0486AA7600D96B5E /* Frameworks */,
8DD76F9E0486AA7600D96B5E /* CopyFiles */,
);
buildRules = (
);
dependencies = (
D4551DFF113E48B20086F21C /* PBXTargetDependency */,
);
name = hammerc;
productInstallPath = "$(HOME)/bin";
productName = hammerc;
productReference = 8DD76FA10486AA7600D96B5E /* hammerc */;
productType = "com.apple.product-type.tool";
};
D4551DF9113E48A90086F21C /* bootstrap-hammerc */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */;
buildPhases = (
D4551DF7113E48A90086F21C /* Sources */,
D4551DF8113E48A90086F21C /* Frameworks */,
);
buildRules = (
);
dependencies = (
D4551E9D113F85D70086F21C /* PBXTargetDependency */,
D4551E9F113F85DA0086F21C /* PBXTargetDependency */,
);
name = "bootstrap-hammerc";
productName = "bootstrap-hammerc";
productReference = D4551DFA113E48A90086F21C /* bootstrap-hammerc */;
productType = "com.apple.product-type.tool";
};
D4551E27113F5F6D0086F21C /* Tests */ = {
isa = PBXNativeTarget;
buildConfigurationList = D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */;
buildPhases = (
D4551E24113F5F6D0086F21C /* Sources */,
D4551E23113F5F6D0086F21C /* Resources */,
D4551E25113F5F6D0086F21C /* Frameworks */,
D4551E26113F5F6D0086F21C /* ShellScript */,
);
buildRules = (
);
dependencies = (
D4551EFE113F88CA0086F21C /* PBXTargetDependency */,
D4551F00113F88CA0086F21C /* PBXTargetDependency */,
);
name = Tests;
productName = Tests;
productReference = D4551E28113F5F6D0086F21C /* Tests.octest */;
productType = "com.apple.product-type.bundle";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
08FB7793FE84155DC02AAC07 /* Project object */ = {
isa = PBXProject;
buildConfigurationList = 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */;
compatibilityVersion = "Xcode 3.1";
hasScannedForEncodings = 1;
mainGroup = 08FB7794FE84155DC02AAC07 /* hammerc */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = D4551E8C113F85C20086F21C /* Products */;
ProjectRef = D4551E8B113F85C20086F21C /* Auspicion.xcodeproj */;
},
{
ProductGroup = D4551E6F113F85780086F21C /* Products */;
ProjectRef = D4551E6E113F85780086F21C /* Hammer.xcodeproj */;
},
+ {
+ ProductGroup = D48B248B11B25720007CBBB4 /* Products */;
+ ProjectRef = D48B248A11B25720007CBBB4 /* Polymorph.xcodeproj */;
+ },
+ {
+ ProductGroup = D48B24BF11B25720007CBBB4 /* Products */;
+ ProjectRef = D48B24BE11B25720007CBBB4 /* RXAssertions.xcodeproj */;
+ },
);
projectRoot = "";
targets = (
8DD76F960486AA7600D96B5E /* hammerc */,
D4551DF9113E48A90086F21C /* bootstrap-hammerc */,
D4551E27113F5F6D0086F21C /* Tests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
D4551E7B113F85780086F21C /* libHammer.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libHammer.a;
remoteRef = D4551E7A113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
- D4551E7D113F85780086F21C /* Hammer.framework */ = {
- isa = PBXReferenceProxy;
- fileType = wrapper.framework;
- path = Hammer.framework;
- remoteRef = D4551E7C113F85780086F21C /* PBXContainerItemProxy */;
- sourceTree = BUILT_PRODUCTS_DIR;
- };
D4551E7F113F85780086F21C /* Tests.octest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = Tests.octest;
remoteRef = D4551E7E113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E81113F85780086F21C /* Measure Performance */ = {
isa = PBXReferenceProxy;
fileType = "compiled.mach-o.executable";
path = "Measure Performance";
remoteRef = D4551E80113F85780086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E95113F85C20086F21C /* libAuspicion.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libAuspicion.a;
remoteRef = D4551E94113F85C20086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E97113F85C20086F21C /* Auspicion.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = Auspicion.framework;
remoteRef = D4551E96113F85C20086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
D4551E99113F85C20086F21C /* libAuspicionLLVM.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libAuspicionLLVM.a;
remoteRef = D4551E98113F85C20086F21C /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
+ D48B24E211B25721007CBBB4 /* libPolymorph.a */ = {
+ isa = PBXReferenceProxy;
+ fileType = archive.ar;
+ path = libPolymorph.a;
+ remoteRef = D48B24E111B25721007CBBB4 /* PBXContainerItemProxy */;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ D48B24E411B25721007CBBB4 /* Tests.octest */ = {
+ isa = PBXReferenceProxy;
+ fileType = wrapper.cfbundle;
+ path = Tests.octest;
+ remoteRef = D48B24E311B25721007CBBB4 /* PBXContainerItemProxy */;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ D48B24EB11B25721007CBBB4 /* libRXAssertions.a */ = {
+ isa = PBXReferenceProxy;
+ fileType = archive.ar;
+ path = libRXAssertions.a;
+ remoteRef = D48B24EA11B25721007CBBB4 /* PBXContainerItemProxy */;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
+ D48B24ED11B25721007CBBB4 /* Tests.octest */ = {
+ isa = PBXReferenceProxy;
+ fileType = wrapper.cfbundle;
+ path = Tests.octest;
+ remoteRef = D48B24EC11B25721007CBBB4 /* PBXContainerItemProxy */;
+ sourceTree = BUILT_PRODUCTS_DIR;
+ };
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
D4551E23113F5F6D0086F21C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551EE3113F88700086F21C /* digit.grammar in Resources */,
D4551EE4113F88700086F21C /* letter.grammar in Resources */,
D4551EF8113F88A00086F21C /* Hammer.grammar in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
D4551E26113F5F6D0086F21C /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
8DD76F990486AA7600D96B5E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4E113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4F113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551E54113F5FEF0086F21C /* hammerc.m in Sources */,
+ D48B23ED11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */,
+ D48B23EE11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551DF7113E48A90086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E4C113F5FC80086F21C /* HammerCompiledRule.m in Sources */,
D4551E4D113F5FC80086F21C /* HammerRuleCompiler.m in Sources */,
D4551EBB113F88300086F21C /* bootstrap-hammerc.m in Sources */,
+ D48B23EB11B24D5E007CBBB4 /* LLVMModule+RuntimeTypeEncodings.m in Sources */,
+ D48B23EC11B24D5E007CBBB4 /* LLVMType+RuntimeTypeEncodings.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D4551E24113F5F6D0086F21C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D4551E3C113F5FB10086F21C /* HammerCompiledAlternationRuleTests.m in Sources */,
D4551E3D113F5FB10086F21C /* HammerCompiledCharacterRuleTests.m in Sources */,
D4551E3E113F5FB10086F21C /* HammerCompiledCharacterSetRuleTests.m in Sources */,
D4551E3F113F5FB10086F21C /* HammerCompiledConcatenationRuleTests.m in Sources */,
D4551E40113F5FB10086F21C /* HammerCompiledLiteralConcatenationRuleTests.m in Sources */,
D4551E41113F5FB10086F21C /* HammerCompiledLiteralRuleTests.m in Sources */,
D4551E42113F5FB10086F21C /* HammerCompiledLookaheadRuleTests.m in Sources */,
D4551E43113F5FB10086F21C /* HammerCompiledNamedRuleTests.m in Sources */,
D4551E44113F5FB10086F21C /* HammerCompiledReferenceRuleTests.m in Sources */,
D4551E45113F5FB10086F21C /* HammerCompiledRepetitionRuleTests.m in Sources */,
D4551E46113F5FB10086F21C /* HammerRuleCompilerTests.m in Sources */,
D4551EBE113F88450086F21C /* HammerCompiledRule.m in Sources */,
D4551EBF113F88450086F21C /* HammerRuleCompiler.m in Sources */,
D4551EE5113F88700086F21C /* HammerAlternationRuleTests.m in Sources */,
D4551EE6113F88700086F21C /* HammerBuilderTests.m in Sources */,
D4551EE7113F88700086F21C /* HammerCharacterRuleTests.m in Sources */,
D4551EE8113F88700086F21C /* HammerCharacterSetRuleTests.m in Sources */,
D4551EE9113F88700086F21C /* HammerConcatenationRuleTests.m in Sources */,
D4551EEA113F88700086F21C /* HammerContainerRuleTests.m in Sources */,
D4551EEB113F88700086F21C /* HammerLiteralConcatenationRuleTests.m in Sources */,
D4551EEC113F88700086F21C /* HammerLiteralRuleTests.m in Sources */,
D4551EED113F88700086F21C /* HammerLookaheadRuleTests.m in Sources */,
D4551EEE113F88700086F21C /* HammerNamedRuleTests.m in Sources */,
D4551EEF113F88700086F21C /* HammerParserTests.m in Sources */,
D4551EF0113F88700086F21C /* HammerReferenceRuleTests.m in Sources */,
D4551EF1113F88700086F21C /* HammerRepetitionRuleTests.m in Sources */,
D4551EF2113F88700086F21C /* HammerRulePrinterTests.m in Sources */,
D4551EF3113F88700086F21C /* HammerRuleTests.m in Sources */,
D4551EF4113F88700086F21C /* HammerTestParser.m in Sources */,
D4551EF5113F88700086F21C /* HammerTestRuleVisitor.m in Sources */,
- D4551F0B113F8E270086F21C /* RXAssertions.m in Sources */,
+ D48B251D11B25AE5007CBBB4 /* RXAssertions.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D4551DFF113E48B20086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D4551DF9113E48A90086F21C /* bootstrap-hammerc */;
targetProxy = D4551DFE113E48B20086F21C /* PBXContainerItemProxy */;
};
D4551E9D113F85D70086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551E9C113F85D70086F21C /* PBXContainerItemProxy */;
};
D4551E9F113F85DA0086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
targetProxy = D4551E9E113F85DA0086F21C /* PBXContainerItemProxy */;
};
D4551EFE113F88CA0086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Auspicion (Static Library)";
targetProxy = D4551EFD113F88CA0086F21C /* PBXContainerItemProxy */;
};
D4551F00113F88CA0086F21C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "Hammer (Static Library)";
targetProxy = D4551EFF113F88CA0086F21C /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
1DEB927508733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_FIX_AND_CONTINUE = YES;
- GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
- GCC_MODEL_TUNING = G5;
GCC_OPTIMIZATION_LEVEL = 0;
- GCC_PRECOMPILE_PREFIX_HEADER = YES;
- GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
- HEADER_SEARCH_PATHS = External/Include/;
INSTALL_PATH = /usr/local/bin;
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
+ );
OTHER_LDFLAGS = (
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Debug;
};
1DEB927608733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_MODEL_TUNING = G5;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
HEADER_SEARCH_PATHS = External/Include/;
INSTALL_PATH = /usr/local/bin;
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
+ );
OTHER_LDFLAGS = (
"-framework",
Foundation,
"-lstdc++",
);
PRODUCT_NAME = hammerc;
};
name = Release;
};
1DEB927908733DD40010E9CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
- GCC_ENABLE_OBJC_GC = supported;
+ GCC_ENABLE_OBJC_GC = required;
+ GCC_INCREASE_PRECOMPILED_HEADER_SHARING = YES;
GCC_OPTIMIZATION_LEVEL = 0;
- GCC_VERSION = com.apple.compilers.llvmgcc42;
+ GCC_PRECOMPILE_PREFIX_HEADER = YES;
+ GCC_PREFIX_HEADER = "Other Sources/hammerc_Prefix.pch";
+ GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
+ HEADER_SEARCH_PATHS = External/Include/;
ONLY_ACTIVE_ARCH = YES;
PREBINDING = NO;
- SDKROOT = macosx10.5;
+ SDKROOT = macosx10.6;
};
name = Debug;
};
1DEB927A08733DD40010E9CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_GC = supported;
GCC_VERSION = com.apple.compilers.llvmgcc42;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
PREBINDING = NO;
SDKROOT = macosx10.5;
};
name = Release;
};
D4551DFC113E48A90086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
- GCC_ENABLE_FIX_AND_CONTINUE = YES;
- GCC_MODEL_TUNING = G5;
GCC_OPTIMIZATION_LEVEL = 0;
- GCC_PRECOMPILE_PREFIX_HEADER = YES;
- GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h";
- HEADER_SEARCH_PATHS = External/Include/;
INSTALL_PATH = /usr/local/bin;
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
+ );
OTHER_LDFLAGS = (
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
};
name = Debug;
};
D4551DFD113E48A90086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_MODEL_TUNING = G5;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h";
HEADER_SEARCH_PATHS = External/Include/;
INSTALL_PATH = /usr/local/bin;
+ LIBRARY_SEARCH_PATHS = (
+ "$(inherited)",
+ "\"$(SRCROOT)/External/Hammer/External/Polymorph/build/Debug\"",
+ );
OTHER_LDFLAGS = (
"-framework",
Foundation,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = "bootstrap-hammerc";
ZERO_LINK = NO;
};
name = Release;
};
D4551E2A113F5F6D0086F21C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = NO;
FRAMEWORK_SEARCH_PATHS = "$(DEVELOPER_LIBRARY_DIR)/Frameworks";
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_MODEL_TUNING = G5;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h";
HEADER_SEARCH_PATHS = External/Include/;
INFOPLIST_FILE = "Resources/Tests-Info.plist";
INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles";
OTHER_LDFLAGS = (
"-framework",
Foundation,
"-framework",
SenTestingKit,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = Tests;
USER_HEADER_SEARCH_PATHS = External/Include/Hammer/;
WRAPPER_EXTENSION = octest;
};
name = Debug;
};
D4551E2B113F5F6D0086F21C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = "$(DEVELOPER_LIBRARY_DIR)/Frameworks";
GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_MODEL_TUNING = G5;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h";
HEADER_SEARCH_PATHS = External/Include/;
INFOPLIST_FILE = "Resources/Tests-Info.plist";
INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles";
OTHER_LDFLAGS = (
"-framework",
Foundation,
"-framework",
SenTestingKit,
"-lstdc++",
);
PREBINDING = NO;
PRODUCT_NAME = Tests;
USER_HEADER_SEARCH_PATHS = External/Include/Hammer/;
WRAPPER_EXTENSION = octest;
ZERO_LINK = NO;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB927508733DD40010E9CD /* Debug */,
1DEB927608733DD40010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1DEB927908733DD40010E9CD /* Debug */,
1DEB927A08733DD40010E9CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D4551E02113E621B0086F21C /* Build configuration list for PBXNativeTarget "bootstrap-hammerc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D4551DFC113E48A90086F21C /* Debug */,
D4551DFD113E48A90086F21C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D4551E2C113F5F6D0086F21C /* Build configuration list for PBXNativeTarget "Tests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D4551E2A113F5F6D0086F21C /* Debug */,
D4551E2B113F5F6D0086F21C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
}
|
kenfodder/frog
|
cb97dc520e874937652ba14cf133f15a1afb7b11
|
bug fix for frog init - thanks ferry
|
diff --git a/lib/schema.rb b/lib/schema.rb
index b60b9fe..8680241 100644
--- a/lib/schema.rb
+++ b/lib/schema.rb
@@ -1,23 +1,25 @@
+require 'active_record'
+
class Schema < ActiveRecord::Migration
def self.up
create_table :blogs do |t|
t.string :title
t.timestamps
end unless ActiveRecord::Base.connection.tables.include?('blogs')
create_table :entries do |t|
t.integer :blog_id
t.string :title
t.string :url
t.text :text
t.timestamps
end unless ActiveRecord::Base.connection.tables.include?('entries')
end
def self.down
drop_table :blogs if ActiveRecord::Base.connection.tables.include?('blogs')
drop_table :entries if ActiveRecord::Base.connection.tables.include?('entries')
end
-end
\ No newline at end of file
+end
|
kenfodder/frog
|
24e472ee787427304e31c41918e28423ea909970
|
tidied up the login page
|
diff --git a/public/style.css b/public/style.css
index 9a7106a..68b753f 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1,45 +1,46 @@
body {font-family: verdana;}
code {font-family:"Bitstream Vera Sans Mono","Monaco","Courier",monospace;}
textarea {width:100%; height:300px; border:1px solid #888888; padding:5px;}
input {border:1px solid #888888; padding:5px;}
+label {font-weight:bold; margin-right:10px;}
.text_input {width:100%;}
#nav {margin-bottom:15px; position:absolute; top: 0pt; right: 0pt; margin-right:10px;}
#footer {font-size:0.7em; margin-top:20px;}
/* Syntax highlighting */
#content .normal {}
#content .comment { color: #CCC; font-style: italic; border: none; margin: 0; }
#content .keyword { color: #C60; font-weight: bold; }
#content .method { color: #9FF; }
#content .class { color: #074; }
#content .module { color: #050; }
#content .punct { color: #0D0; font-weight: bold; }
#content .symbol { color: #099; }
#content .string { color: #C03; }
#content .char { color: #F07; }
#content .ident { color: #0D0; }
#content .constant { color: #07F; }
#content .regex { color: #B66; }
#content .number { color: #FF0; }
#content .attribute { color: #7BB; }
#content .global { color: #7FB; }
#content .expr { color: #909; }
#content .escape { color: #277; }
#content .syntax {
width:650px;
background-color: #333;
padding: 2px;
margin: 5px;
margin-left: 1em;
font-size:9pt;
letter-spacing:0;
line-height:1.3em;
}
#content .syntax .line_number {
text-align: right;
padding-left: 1em;
padding-right: 1em;
color: #999;
}
\ No newline at end of file
diff --git a/views/login.erb b/views/login.erb
index 1d8355a..d638242 100644
--- a/views/login.erb
+++ b/views/login.erb
@@ -1,5 +1,7 @@
+<h2>Login</h2>
+
<form action="/login" method="post">
- <p><input type="text" name="username"/></p>
- <p><input type="text" name="password"/></p>
+ <p><label>Username</label><input type="text" name="username"/></p>
+ <p><label>Password</label><input type="password" name="password"/></p>
<p><input type="submit" value="login"/></p>
</form>
\ No newline at end of file
|
kenfodder/frog
|
6dec8c36b9f79cfaa63918d222ec751c509e61da
|
better looking input fields
|
diff --git a/public/style.css b/public/style.css
index 284c88b..9a7106a 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1,44 +1,45 @@
body {font-family: verdana;}
code {font-family:"Bitstream Vera Sans Mono","Monaco","Courier",monospace;}
textarea {width:100%; height:300px; border:1px solid #888888; padding:5px;}
+input {border:1px solid #888888; padding:5px;}
.text_input {width:100%;}
#nav {margin-bottom:15px; position:absolute; top: 0pt; right: 0pt; margin-right:10px;}
#footer {font-size:0.7em; margin-top:20px;}
/* Syntax highlighting */
#content .normal {}
#content .comment { color: #CCC; font-style: italic; border: none; margin: 0; }
#content .keyword { color: #C60; font-weight: bold; }
#content .method { color: #9FF; }
#content .class { color: #074; }
#content .module { color: #050; }
#content .punct { color: #0D0; font-weight: bold; }
#content .symbol { color: #099; }
#content .string { color: #C03; }
#content .char { color: #F07; }
#content .ident { color: #0D0; }
#content .constant { color: #07F; }
#content .regex { color: #B66; }
#content .number { color: #FF0; }
#content .attribute { color: #7BB; }
#content .global { color: #7FB; }
#content .expr { color: #909; }
#content .escape { color: #277; }
#content .syntax {
width:650px;
background-color: #333;
padding: 2px;
margin: 5px;
margin-left: 1em;
font-size:9pt;
letter-spacing:0;
line-height:1.3em;
}
#content .syntax .line_number {
text-align: right;
padding-left: 1em;
padding-right: 1em;
color: #999;
}
\ No newline at end of file
|
kenfodder/frog
|
2cefef6187eed50ccfe51d786f8d577ecb618423
|
Tidied up the entry form, removed jquery for now
|
diff --git a/public/jquery-1.2.6.min.js b/public/jquery-1.2.6.min.js
deleted file mode 100644
index 82b98e1..0000000
--- a/public/jquery-1.2.6.min.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * jQuery 1.2.6 - New Wave Javascript
- *
- * Copyright (c) 2008 John Resig (jquery.com)
- * Dual licensed under the MIT (MIT-LICENSE.txt)
- * and GPL (GPL-LICENSE.txt) licenses.
- *
- * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
- * $Rev: 5685 $
- */
-(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else
-return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
-return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
-selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
-return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
-this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
-return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
-jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&©&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
-script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
-for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
-for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
-jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
-ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&¬xml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&¬xml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&¬xml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
-while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
-while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
-for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
-jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
-xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
-jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
-for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
-s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
-e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();
\ No newline at end of file
diff --git a/public/style.css b/public/style.css
index e04f4e2..284c88b 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1,44 +1,44 @@
body {font-family: verdana;}
code {font-family:"Bitstream Vera Sans Mono","Monaco","Courier",monospace;}
-textarea {width:600px; height:300px;}
-input {width:600px;}
+textarea {width:100%; height:300px; border:1px solid #888888; padding:5px;}
+.text_input {width:100%;}
#nav {margin-bottom:15px; position:absolute; top: 0pt; right: 0pt; margin-right:10px;}
#footer {font-size:0.7em; margin-top:20px;}
/* Syntax highlighting */
#content .normal {}
#content .comment { color: #CCC; font-style: italic; border: none; margin: 0; }
#content .keyword { color: #C60; font-weight: bold; }
#content .method { color: #9FF; }
#content .class { color: #074; }
#content .module { color: #050; }
#content .punct { color: #0D0; font-weight: bold; }
#content .symbol { color: #099; }
#content .string { color: #C03; }
#content .char { color: #F07; }
#content .ident { color: #0D0; }
#content .constant { color: #07F; }
#content .regex { color: #B66; }
#content .number { color: #FF0; }
#content .attribute { color: #7BB; }
#content .global { color: #7FB; }
#content .expr { color: #909; }
#content .escape { color: #277; }
#content .syntax {
width:650px;
background-color: #333;
padding: 2px;
margin: 5px;
margin-left: 1em;
font-size:9pt;
letter-spacing:0;
line-height:1.3em;
}
#content .syntax .line_number {
text-align: right;
padding-left: 1em;
padding-right: 1em;
color: #999;
}
\ No newline at end of file
diff --git a/views/_entry_form.erb b/views/_entry_form.erb
index f7ddb93..b762709 100644
--- a/views/_entry_form.erb
+++ b/views/_entry_form.erb
@@ -1,3 +1,8 @@
-<p><b>Title</b> <input type="text" name="title" value="<%= @entry.title %>" /></p>
-<p><b>URL?</b> <input type="text" name="url" value="<%= @entry.url %>" /></p>
-<p><b>Text</b> <textarea name="text"><%= @entry.text %></textarea></p>
\ No newline at end of file
+<p><b>Title</b> <input type="text" name="title" value="<%= @entry.title %>" class="text_input" /></p>
+<p><b>URL?</b> <input type="text" name="url" value="<%= @entry.url %>" class="text_input" /></p>
+<p>
+ <b>Body</b>
+ <a href="http://hobix.com/textile/quick.html" target="_new">Textile Enabled</a>
+ for syntax use: [code]...[/code]
+ <textarea name="text"><%= @entry.text %></textarea>
+</p>
\ No newline at end of file
diff --git a/views/new.erb b/views/new.erb
index b0413fe..a209cd0 100644
--- a/views/new.erb
+++ b/views/new.erb
@@ -1,4 +1,6 @@
+<h2>New Entry</h2>
+
<form action="/admin/create" method="post">
<%= partial :entry_form %>
- <p><input type="submit" value="create"/></p>
+ <p><input type="submit" value="create"/> <input type="button" value="cancel" onclick="location.href='/'"/></p>
</form>
\ No newline at end of file
diff --git a/views/update.erb b/views/update.erb
index 4fdaa3b..9896131 100644
--- a/views/update.erb
+++ b/views/update.erb
@@ -1,4 +1,6 @@
+<h2>Edit Entry</h2>
+
<form action="/admin/update/<%= @entry.id %>" method="post">
<%= partial :entry_form %>
- <p><input type="submit" value="update"/></p>
+ <p><input type="submit" value="update"/> <input type="button" value="cancel" onclick="location.href='/admin'"/></p>
</form>
\ No newline at end of file
|
kenfodder/frog
|
824752cde3688de541f03952b1565ec7d966039a
|
Wired up update and destroy actions on admin
|
diff --git a/frog.rb b/frog.rb
index f1ce8c0..2116366 100755
--- a/frog.rb
+++ b/frog.rb
@@ -1,85 +1,102 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
Dir["lib/*.rb"].each { |x| load x }
configure do
set_option :sessions, true
end
before do
if request.path_info =~ /admin/ and !logged_in?
session['forward'] = request.path_info + (request.query_string.blank? ? '' : '?' + request.query_string)
redirect '/login'
end
@blog = Blog.find(:first)
end
helpers do
include Helpers
end
# Main Blog action
get '/' do
@entries = @blog.entries
erb :blog
end
# Permalink Entry action
get '/perm/:id' do
@entry = @blog.entries.find(params[:id])
erb :entry
end
get '/login' do
erb :login
end
post '/login' do
# TODO: store the hashed password on the blog model
if params[:username] == 'admin' and params['password'] == 'admin'
session[:user] = true
redirect session['forward'] || '/'
else
redirect '/login'
end
end
get '/logout' do
session[:user] = nil
redirect '/'
end
# -- Admin actions (require login)
get '/admin' do
@entries = @blog.entries
erb :admin
end
get '/admin/new' do
+ @entry = Entry.new
erb :new
end
+get '/admin/update/:id' do
+ @entry = @blog.entries.find(params[:id])
+ erb :update
+end
+
+post '/admin/update/:id' do
+ entry = @blog.entries.find(params[:id])
+ entry.update_attributes(:title => params[:title], :url => params[:url], :text => params[:text])
+ redirect "/perm/#{entry.id}"
+end
+
+get '/admin/destroy/:id' do
+ @blog.entries.find(params[:id]).destroy
+ redirect '/admin'
+end
+
post '/admin/create' do
entry = @blog.entries.create(
:title => params[:title],
:url => params[:url],
:text => params[:text]
)
redirect "/perm/#{entry.id}"
end
# For use by the bookmarklet
# http://blog/admin/bookmark?url=http://somewhere.com/
get '/admin/bookmark' do
url = params[:url]
title = scrape_page_title(url)
@blog.entries.create(
:title => title,
:url => url
)
redirect url
end
diff --git a/lib/helpers.rb b/lib/helpers.rb
index bff69db..b3e22b6 100644
--- a/lib/helpers.rb
+++ b/lib/helpers.rb
@@ -1,67 +1,68 @@
module Helpers
def logged_in?
session[:user]
end
def partial(name, options={})
erb("_#{name.to_s}".to_sym, options.merge(:layout => false))
end
def image_tag(file, options={})
tag = "<img src='/images/#{file}'"
tag += " alt='#{options[:alt]}' title='#{options[:alt]}' " if options[:alt]
tag += "/>"
end
def link_to(text, link='#', options = {})
tag = "<a href='#{link}'"
tag += " class=\"#{options[:class]}\"" if options[:class]
tag += " target=\"#{options[:target]}\"" if options[:target]
+ tag += " onclick=\"#{options[:onclick]}\"" if options[:onclick]
tag += ">#{text}</a>"
end
def scrape_page_title(url)
page_title = /<title>\s*(.*)\s*<\/title>/i
begin
page_content = Timeout.timeout(5) {
fetch(url).body.to_s
}
matches = page_content.match(page_title)
matches[1] if matches || nil
rescue Exception => e
url
end
end
def fetch(uri_str, limit = 3)
return false if limit == 0
response = Net::HTTP.get_response(URI.parse(uri_str))
case response
when Net::HTTPSuccess then response
when Net::HTTPRedirection then fetch(response['location'], limit - 1)
else
return false
end
end
def time_ago_or_time_stamp(from_time, to_time = Time.now, include_seconds = true, detail = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1 then time = (distance_in_seconds < 60) ? "#{distance_in_seconds} seconds ago" : '1 minute ago'
when 2..59 then time = "#{distance_in_minutes} minutes ago"
when 60..90 then time = "1 hour ago"
when 90..1440 then time = "#{(distance_in_minutes.to_f / 60.0).round} hours ago"
when 1440..2160 then time = '1 day ago' # 1-1.5 days
when 2160..2880 then time = "#{(distance_in_minutes.to_f / 1440.0).round} days ago" # 1.5-2 days
else time = from_time.strftime("%a, %d %b %Y")
end
return time_stamp(from_time) if (detail && distance_in_minutes > 2880)
return time
end
end
\ No newline at end of file
diff --git a/views/_entry_form.erb b/views/_entry_form.erb
new file mode 100644
index 0000000..f7ddb93
--- /dev/null
+++ b/views/_entry_form.erb
@@ -0,0 +1,3 @@
+<p><b>Title</b> <input type="text" name="title" value="<%= @entry.title %>" /></p>
+<p><b>URL?</b> <input type="text" name="url" value="<%= @entry.url %>" /></p>
+<p><b>Text</b> <textarea name="text"><%= @entry.text %></textarea></p>
\ No newline at end of file
diff --git a/views/admin.erb b/views/admin.erb
index 8f7d3e8..5862aeb 100644
--- a/views/admin.erb
+++ b/views/admin.erb
@@ -1,17 +1,21 @@
<h2>Admin</h2>
<p><b>Blog Title</b> <%= @blog.title %></p>
<p><%= link_to('New Entry', '/admin/new') %></p>
<% @entries.each do |entry| %>
- <p><a href="/perm/<%= entry.id %>"><%= entry.title %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small></p>
+ <p>
+ <a href="/perm/<%= entry.id %>"><%= entry.title %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small>
+ <%= link_to 'Edit', "/admin/update/#{entry.id}" %> |
+ <%= link_to 'Delete', "/admin/destroy/#{entry.id}", :onclick => "return confirm('Are you sure?');" %>
+ </p>
<% end %>
<h2>TODO</h2>
<p>Google analytics code</p>
<p>Keywords & Description</p>
<p>Any rhc widgets</p>
<p>Logo?</p>
\ No newline at end of file
diff --git a/views/new.erb b/views/new.erb
index c010653..b0413fe 100644
--- a/views/new.erb
+++ b/views/new.erb
@@ -1,6 +1,4 @@
<form action="/admin/create" method="post">
- <p><b>Title</b> <input type="text" name="title"/></p>
- <p><b>URL?</b> <input type="text" name="url"/></p>
- <p><b>Text</b> <textarea name="text"></textarea></p>
+ <%= partial :entry_form %>
<p><input type="submit" value="create"/></p>
</form>
\ No newline at end of file
diff --git a/views/update.erb b/views/update.erb
new file mode 100644
index 0000000..4fdaa3b
--- /dev/null
+++ b/views/update.erb
@@ -0,0 +1,4 @@
+<form action="/admin/update/<%= @entry.id %>" method="post">
+ <%= partial :entry_form %>
+ <p><input type="submit" value="update"/></p>
+</form>
\ No newline at end of file
|
kenfodder/frog
|
81cf9340f15cc89da1baf3bb68c17d23681a554e
|
Bit of tidy up and commenting
|
diff --git a/frog.rb b/frog.rb
index ae310c2..f1ce8c0 100755
--- a/frog.rb
+++ b/frog.rb
@@ -1,78 +1,85 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
Dir["lib/*.rb"].each { |x| load x }
configure do
set_option :sessions, true
end
before do
if request.path_info =~ /admin/ and !logged_in?
session['forward'] = request.path_info + (request.query_string.blank? ? '' : '?' + request.query_string)
redirect '/login'
end
@blog = Blog.find(:first)
end
+helpers do
+ include Helpers
+end
+
+# Main Blog action
get '/' do
@entries = @blog.entries
erb :blog
end
+# Permalink Entry action
get '/perm/:id' do
@entry = @blog.entries.find(params[:id])
erb :entry
end
get '/login' do
erb :login
end
post '/login' do
+ # TODO: store the hashed password on the blog model
if params[:username] == 'admin' and params['password'] == 'admin'
session[:user] = true
redirect session['forward'] || '/'
else
redirect '/login'
end
end
get '/logout' do
session[:user] = nil
redirect '/'
end
+# -- Admin actions (require login)
+
get '/admin' do
@entries = @blog.entries
erb :admin
end
get '/admin/new' do
erb :new
end
post '/admin/create' do
entry = @blog.entries.create(
:title => params[:title],
:url => params[:url],
:text => params[:text]
)
redirect "/perm/#{entry.id}"
end
+# For use by the bookmarklet
+# http://blog/admin/bookmark?url=http://somewhere.com/
get '/admin/bookmark' do
url = params[:url]
title = scrape_page_title(url)
@blog.entries.create(
:title => title,
:url => url
)
redirect url
end
-
-helpers do
- include Helpers
-end
\ No newline at end of file
diff --git a/lib/helpers.rb b/lib/helpers.rb
index 7fe43f7..bff69db 100644
--- a/lib/helpers.rb
+++ b/lib/helpers.rb
@@ -1,70 +1,67 @@
module Helpers
def logged_in?
session[:user]
end
def partial(name, options={})
erb("_#{name.to_s}".to_sym, options.merge(:layout => false))
end
def image_tag(file, options={})
tag = "<img src='/images/#{file}'"
- if options[:alt]
- tag += " alt='#{options[:alt]}' title='#{options[:alt]}' "
- end
+ tag += " alt='#{options[:alt]}' title='#{options[:alt]}' " if options[:alt]
tag += "/>"
end
def link_to(text, link='#', options = {})
- o = ''
- if options[:class]
- o = "class = \"#{options[:class]}\""
- end
- "<a href='#{link}'#{o}>#{text}</a>"
+ tag = "<a href='#{link}'"
+ tag += " class=\"#{options[:class]}\"" if options[:class]
+ tag += " target=\"#{options[:target]}\"" if options[:target]
+ tag += ">#{text}</a>"
end
def scrape_page_title(url)
page_title = /<title>\s*(.*)\s*<\/title>/i
begin
page_content = Timeout.timeout(5) {
fetch(url).body.to_s
}
matches = page_content.match(page_title)
matches[1] if matches || nil
rescue Exception => e
url
end
end
def fetch(uri_str, limit = 3)
return false if limit == 0
response = Net::HTTP.get_response(URI.parse(uri_str))
case response
when Net::HTTPSuccess then response
when Net::HTTPRedirection then fetch(response['location'], limit - 1)
else
return false
end
end
def time_ago_or_time_stamp(from_time, to_time = Time.now, include_seconds = true, detail = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1 then time = (distance_in_seconds < 60) ? "#{distance_in_seconds} seconds ago" : '1 minute ago'
when 2..59 then time = "#{distance_in_minutes} minutes ago"
when 60..90 then time = "1 hour ago"
when 90..1440 then time = "#{(distance_in_minutes.to_f / 60.0).round} hours ago"
when 1440..2160 then time = '1 day ago' # 1-1.5 days
when 2160..2880 then time = "#{(distance_in_minutes.to_f / 1440.0).round} days ago" # 1.5-2 days
else time = from_time.strftime("%a, %d %b %Y")
end
return time_stamp(from_time) if (detail && distance_in_minutes > 2880)
return time
end
end
\ No newline at end of file
diff --git a/views/_entry.erb b/views/_entry.erb
index c7148e3..0cfb1f7 100644
--- a/views/_entry.erb
+++ b/views/_entry.erb
@@ -1,29 +1,27 @@
<% prev_date ||= '' %>
<div class="post">
-
<div class="date">
<% if prev_date != entry.created_at.strftime("%a%d%Y") %>
<div class="date_brick">
<%= entry.created_at.strftime("%b") %><br/>
<%= entry.created_at.strftime("%d") %>
</div>
<%= entry.created_at.strftime("%a") %>
<% end %>
<div style="font-size:0.4em"><%= link_to(entry.created_at.strftime("%H:%M"), "/perm/#{entry.id}") %></div>
</div>
-
<% unless entry.url.blank? %>
<div class="link">
<%= link_to entry.title, entry.url, :class => 'link' %>
</div>
<p style="margin-top:-2px;"><small><%= entry.short_uri %></small></p>
<% else %>
<h2><%= entry.title %></h2>
<% end %>
<%= entry.html %>
</div>
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
index f11d7b1..69dd9c6 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,34 +1,36 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><%= @title ? "#{@title} | " : '' %> <%= @blog.title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
<link href="/tumblr.css" media="screen" rel="Stylesheet" type="text/css"></link>
<script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
<h1><%= link_to @blog.title, '/' %></h1>
-<div id="nav">
- <% if logged_in? %><a href="/admin">Admin</a> | <%= link_to('New Entry', '/admin/new') %> | <a href="/logout">Logout</a><% end %>
-</div>
+<% if logged_in? %>
+ <div id="nav">
+ <a href="/admin">Admin</a> | <%= link_to('New Entry', '/admin/new') %> | <a href="/logout">Logout</a>
+ </div>
+<% end %>
<div id="content">
<%= yield %>
</div>
<div id="footer">
powered by <a href="http://github.com/moomerman/frog/tree/master">frog</a> and
<a href="http://github.com/bmizerany/sinatra/tree/master">sinatra</a>
| <a href="http://hobix.com/textile/">formatting</a>
</div>
</body>
</html>
\ No newline at end of file
|
kenfodder/frog
|
41cb9dcddfb198726924c50ffe281efd7554c72e
|
fixed the date layout
|
diff --git a/Rakefile b/Rakefile
index a95d018..51b2574 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,30 +1,38 @@
Dir["lib/*.rb"].each { |x| load x }
task :default do
puts 'rake frog:init to get started'
puts 'rake frog:reset to reload the db schema (loses all data!)'
end
namespace :frog do
task :db_up do
Schema.up
end
task :db_down do
Schema.down
end
task :init => :db_up do
if Blog.count == 0
blog = Blog.create!(:title => 'My Frog Blog')
blog.entries.create(
:title => 'Welcome to Frog!',
:text => '!http://www1.istockphoto.com/file_thumbview_approve/1073907/2/istockphoto_1073907-frog-cartoon.jpg!'
)
+ blog.entries.create(
+ :title => 'Code Sample',
+ :text => "[code]def frog\n puts 'Welcome to Frog'\nend[/code]"
+ )
+ blog.entries.create(
+ :title => 'moomerman\'s frog at master - GitHub',
+ :url => "http://github.com/moomerman/frog/tree/master"
+ )
end
end
task :reset => [:db_down, :init]
end
\ No newline at end of file
diff --git a/lib/helpers.rb b/lib/helpers.rb
index 8971933..7fe43f7 100644
--- a/lib/helpers.rb
+++ b/lib/helpers.rb
@@ -1,66 +1,70 @@
module Helpers
def logged_in?
session[:user]
end
def partial(name, options={})
erb("_#{name.to_s}".to_sym, options.merge(:layout => false))
end
def image_tag(file, options={})
tag = "<img src='/images/#{file}'"
if options[:alt]
tag += " alt='#{options[:alt]}' title='#{options[:alt]}' "
end
tag += "/>"
end
- def link_to(text, link='#')
- "<a href='#{link}'>#{text}</a>"
+ def link_to(text, link='#', options = {})
+ o = ''
+ if options[:class]
+ o = "class = \"#{options[:class]}\""
+ end
+ "<a href='#{link}'#{o}>#{text}</a>"
end
def scrape_page_title(url)
page_title = /<title>\s*(.*)\s*<\/title>/i
begin
page_content = Timeout.timeout(5) {
fetch(url).body.to_s
}
matches = page_content.match(page_title)
matches[1] if matches || nil
rescue Exception => e
url
end
end
def fetch(uri_str, limit = 3)
return false if limit == 0
response = Net::HTTP.get_response(URI.parse(uri_str))
case response
when Net::HTTPSuccess then response
when Net::HTTPRedirection then fetch(response['location'], limit - 1)
else
return false
end
end
def time_ago_or_time_stamp(from_time, to_time = Time.now, include_seconds = true, detail = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1 then time = (distance_in_seconds < 60) ? "#{distance_in_seconds} seconds ago" : '1 minute ago'
when 2..59 then time = "#{distance_in_minutes} minutes ago"
when 60..90 then time = "1 hour ago"
when 90..1440 then time = "#{(distance_in_minutes.to_f / 60.0).round} hours ago"
when 1440..2160 then time = '1 day ago' # 1-1.5 days
when 2160..2880 then time = "#{(distance_in_minutes.to_f / 1440.0).round} days ago" # 1.5-2 days
else time = from_time.strftime("%a, %d %b %Y")
end
return time_stamp(from_time) if (detail && distance_in_minutes > 2880)
return time
end
end
\ No newline at end of file
diff --git a/views/_entry.erb b/views/_entry.erb
index 5d6e09d..c7148e3 100644
--- a/views/_entry.erb
+++ b/views/_entry.erb
@@ -1,26 +1,29 @@
+<% prev_date ||= '' %>
+
<div class="post">
-
+
+
<div class="date">
- <div class="date_brick">
- Sep<br/>
- 26
- </div>
- Fri
+ <% if prev_date != entry.created_at.strftime("%a%d%Y") %>
+ <div class="date_brick">
+ <%= entry.created_at.strftime("%b") %><br/>
+ <%= entry.created_at.strftime("%d") %>
+ </div>
+ <%= entry.created_at.strftime("%a") %>
+ <% end %>
+ <div style="font-size:0.4em"><%= link_to(entry.created_at.strftime("%H:%M"), "/perm/#{entry.id}") %></div>
</div>
+
- <h2>
- <% unless entry.url.blank? %>
- <%= link_to entry.title, entry.url %>
- <% else %>
- <%= entry.title %>
- <% end %>
- </h2>
<% unless entry.url.blank? %>
- <p style="margin-top:-20px"><small><%= entry.short_uri %></small></p>
+ <div class="link">
+ <%= link_to entry.title, entry.url, :class => 'link' %>
+ </div>
+ <p style="margin-top:-2px;"><small><%= entry.short_uri %></small></p>
+ <% else %>
+ <h2><%= entry.title %></h2>
<% end %>
<%= entry.html %>
- <small><%= link_to(entry.created_at, "/perm/#{entry.id}") %></small>
-
</div>
\ No newline at end of file
diff --git a/views/blog.erb b/views/blog.erb
index 43253c1..c44fcd3 100644
--- a/views/blog.erb
+++ b/views/blog.erb
@@ -1,3 +1,5 @@
+<% prev_date = '' %>
<% @entries.each do |entry| %>
- <%= partial(:entry, :locals => {:entry => entry}) %>
+ <%= partial(:entry, :locals => {:entry => entry, :prev_date => prev_date}) %>
+ <% prev_date = entry.created_at.strftime("%a%d%Y") %>
<% end %>
|
kenfodder/frog
|
c745806593e8bf4174973319785e68010458881f
|
added style
|
diff --git a/frog.rb b/frog.rb
index 6098c1d..ae310c2 100755
--- a/frog.rb
+++ b/frog.rb
@@ -1,77 +1,78 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
Dir["lib/*.rb"].each { |x| load x }
configure do
set_option :sessions, true
end
before do
if request.path_info =~ /admin/ and !logged_in?
session['forward'] = request.path_info + (request.query_string.blank? ? '' : '?' + request.query_string)
redirect '/login'
end
@blog = Blog.find(:first)
end
get '/' do
@entries = @blog.entries
erb :blog
end
get '/perm/:id' do
@entry = @blog.entries.find(params[:id])
erb :entry
end
get '/login' do
erb :login
end
post '/login' do
if params[:username] == 'admin' and params['password'] == 'admin'
session[:user] = true
redirect session['forward'] || '/'
else
redirect '/login'
end
end
get '/logout' do
session[:user] = nil
redirect '/'
end
get '/admin' do
+ @entries = @blog.entries
erb :admin
end
get '/admin/new' do
erb :new
end
post '/admin/create' do
entry = @blog.entries.create(
:title => params[:title],
:url => params[:url],
:text => params[:text]
)
redirect "/perm/#{entry.id}"
end
get '/admin/bookmark' do
url = params[:url]
title = scrape_page_title(url)
@blog.entries.create(
:title => title,
:url => url
)
redirect url
end
helpers do
include Helpers
end
\ No newline at end of file
diff --git a/public/style.css b/public/style.css
index be7220d..e04f4e2 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1,44 +1,44 @@
body {font-family: verdana;}
code {font-family:"Bitstream Vera Sans Mono","Monaco","Courier",monospace;}
textarea {width:600px; height:300px;}
input {width:600px;}
-#nav {margin-bottom:15px;}
+#nav {margin-bottom:15px; position:absolute; top: 0pt; right: 0pt; margin-right:10px;}
#footer {font-size:0.7em; margin-top:20px;}
/* Syntax highlighting */
#content .normal {}
#content .comment { color: #CCC; font-style: italic; border: none; margin: 0; }
#content .keyword { color: #C60; font-weight: bold; }
#content .method { color: #9FF; }
#content .class { color: #074; }
#content .module { color: #050; }
#content .punct { color: #0D0; font-weight: bold; }
#content .symbol { color: #099; }
#content .string { color: #C03; }
#content .char { color: #F07; }
#content .ident { color: #0D0; }
#content .constant { color: #07F; }
#content .regex { color: #B66; }
#content .number { color: #FF0; }
#content .attribute { color: #7BB; }
#content .global { color: #7FB; }
#content .expr { color: #909; }
#content .escape { color: #277; }
#content .syntax {
width:650px;
background-color: #333;
padding: 2px;
margin: 5px;
margin-left: 1em;
font-size:9pt;
letter-spacing:0;
line-height:1.3em;
}
#content .syntax .line_number {
text-align: right;
padding-left: 1em;
padding-right: 1em;
color: #999;
}
\ No newline at end of file
diff --git a/public/tumblr.css b/public/tumblr.css
new file mode 100644
index 0000000..13fbc1d
--- /dev/null
+++ b/public/tumblr.css
@@ -0,0 +1,279 @@
+ body {
+ margin: 0px;
+ background-color: #fff;
+ font-family: 'Lucida Grande', Helvetica, sans-serif;
+ }
+
+ a {
+ color: #6498cc;
+ }
+
+ h1 {
+ width: 800px;
+ padding: 0px 100px 20px 100px;
+ margin: 50px auto 40px auto;
+ border-bottom: solid 1px #ccc;
+ text-align: center;
+ font: Bold 55px 'Trebuchet MS', Helvetica, sans-serif;
+ letter-spacing: -2px;
+ line-height: 50px;
+ position: relative;
+ }
+
+ h1 a {
+ color: #444;
+ text-decoration: none;
+ }
+
+ h1 img {
+ border-width: 0px;
+ position: absolute;
+ right: 0px;
+ bottom: 10px;
+ width: 16px;
+ height: 16px;
+ }
+
+ div#content {
+ width: 620px;
+ margin: auto;
+ position: relative;
+ }
+
+ div#content div#description {
+ position: absolute;
+ right: -170px;
+ width: 160px;
+ text-align: right;
+ }
+
+ div#description {
+ font: Normal 17px Helvetica,sans-serif;
+ line-height: 20px;
+ color: #777;
+ }
+
+ div#description a {
+ color: #777;
+ }
+
+ div.post {
+ position: relative;
+ margin-bottom: 40px;
+ padding-right: 20px;
+ }
+
+ div.post div.date {
+ position: absolute;
+ left: -260px;
+ text-align: right;
+ width: 230px;
+ white-space: nowrap;
+ font: Normal 34px Helvetica, sans-serif;
+ letter-spacing: -2px;
+ color: #ccc;
+ text-transform: uppercase;
+ line-height: 35px;
+ }
+
+ div.post div.date div.date_brick {
+ float: right;
+ height: 30px;
+ width: 45px;
+ background-color: #6498cc;
+ color: #bbd5f1;
+ font: Bold 12px Verdana, Sans-Serif;
+ text-align: center;
+ line-height: 12px;
+ margin-left: 10px;
+ padding-top: 5px;
+ letter-spacing: 0px;
+ overflow: hidden;
+ }
+
+ div.post img.permalink {
+ width: 14px;
+ height: 13px;
+ border-width: 0px;
+ background-color: #000;
+ display: none;
+ position: absolute;
+ right: 0px;
+ top: 0px;
+ z-index: 10;
+ }
+
+ div.post:hover img.permalink {
+ display: inline;
+ }
+
+ div.post h2 {
+ font-size: 18px;
+ font-weight: Bold;
+ color: #6498cc;
+ letter-spacing: -1px;
+ margin: 0px 0px 5px 0px;
+ }
+
+ div.post h2 a {
+ color: #6498cc;
+ text-decoration: none;
+ }
+
+ div.post div.caption {
+ font-size: 14px;
+ font-weight: bold;
+ color: #444;
+ margin-top: 10px;
+ padding: 0px 20px 0px 20px;
+ }
+
+ div.post div.caption a {
+ color: #444;
+ }
+
+/* Regular Post */
+
+ div.post div.regular {
+ font-size: 12px;
+ color: #444;
+ line-height: 17px;
+ }
+
+ div.post div.regular img { padding:5px }
+
+ div.post div.regular blockquote {
+ font-style: italic;
+ border-left: solid 2px #444;
+ padding-left: 10px;
+ }
+
+ /* Quote Post */
+
+ div.post div.quote div.quote_text {
+ font-family: Helvetica, sans-serif;
+ font-weight: bold;
+ color: #888;
+ border-left: solid 5px #6498cc;
+ padding-left: 10px;
+ }
+
+ div.post div.quote div.quote_text span.short {
+ font-size: 36px;
+ line-height: 40px;
+ letter-spacing: -1px;
+ }
+
+ div.post div.quote div.quote_text span.medium {
+ font-size: 25px;
+ line-height: 27px;
+ letter-spacing: -1px;
+ }
+
+ div.post div.quote div.quote_text span.long {
+ font-size: 16px;
+ line-height: 20px;
+ }
+
+ div.post div.quote div.quote_text a {
+ color: #888;
+ }
+
+ div.post div.quote div.source {
+ font-size: 16px;
+ font-weight: Bold;
+ color: #555;
+ margin-top: 5px;
+ }
+
+ div.post div.quote div.source a {
+ color: #555;
+ }
+
+ /* Link Post */
+
+ div.post div.link a.link {
+ font: Bold 20px Helvetica, sans-serif;
+ letter-spacing: -1px;
+ color: #c00;
+ }
+ div.post div.link img { padding:5px }
+ div.post div.link span.description {
+ font-size: 13px;
+ font-weight: normal;
+ letter-spacing: -1px;
+ color: #444;
+ }
+
+ /* Conversation Post */
+
+ div.post div.conversation ul {
+ list-style-type: none;
+ margin: 0px;
+ padding: 0px 0px 0px 1px;
+ border-left: solid 5px #bbb;
+ }
+
+ div.post div.conversation ul li {
+ font-size: 12px;
+ padding: 4px 10px 4px 8px;
+ color: #444;
+ margin-bottom: 1px;
+ }
+
+ div.post div.conversation ul li span.label {
+ font-weight: bold;
+ }
+
+ div.post div.conversation ul li span.user_1 {
+ color: #c00;
+ }
+
+ div.post div.conversation ul li span.user_2 {
+ color: #00c;
+ }
+
+ div.post div.conversation ul li span.user_3 {
+ color: #0a0;
+ }
+
+ div.post div.conversation ul li.odd {
+ background-color: #f4f4f4;
+ }
+
+ div.post div.conversation ul li.even {
+ background-color: #e8e8e8;
+ }
+
+ /* Video Post */
+
+ div.post div.video {
+ width: 400px;
+ margin: auto;
+ }
+
+ /* Footer */
+
+ div#footer {
+ margin: 40px 0px 30px 0px;
+ text-align: center;
+ font-size: 15px;
+ font-weight: bold;
+ color: #444;
+ }
+
+ div#footer a {
+ text-decoration: none;
+ color: #444;
+ }
+
+ div#footer a:hover {
+ text-decoration: underline;
+ }
+
+ div#footer div#credit {
+ font: Normal 13px Georgia, serif;
+ font-size: 13px;
+ margin-top: 15px;
+ }
+
diff --git a/views/_entry.erb b/views/_entry.erb
new file mode 100644
index 0000000..5d6e09d
--- /dev/null
+++ b/views/_entry.erb
@@ -0,0 +1,26 @@
+<div class="post">
+
+ <div class="date">
+ <div class="date_brick">
+ Sep<br/>
+ 26
+ </div>
+ Fri
+ </div>
+
+ <h2>
+ <% unless entry.url.blank? %>
+ <%= link_to entry.title, entry.url %>
+ <% else %>
+ <%= entry.title %>
+ <% end %>
+ </h2>
+ <% unless entry.url.blank? %>
+ <p style="margin-top:-20px"><small><%= entry.short_uri %></small></p>
+ <% end %>
+
+ <%= entry.html %>
+
+ <small><%= link_to(entry.created_at, "/perm/#{entry.id}") %></small>
+
+</div>
\ No newline at end of file
diff --git a/views/admin.erb b/views/admin.erb
index 189001e..8f7d3e8 100644
--- a/views/admin.erb
+++ b/views/admin.erb
@@ -1,8 +1,17 @@
<h2>Admin</h2>
<p><b>Blog Title</b> <%= @blog.title %></p>
+<p><%= link_to('New Entry', '/admin/new') %></p>
+
+<% @entries.each do |entry| %>
+ <p><a href="/perm/<%= entry.id %>"><%= entry.title %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small></p>
+<% end %>
+
+
+<h2>TODO</h2>
+
<p>Google analytics code</p>
<p>Keywords & Description</p>
<p>Any rhc widgets</p>
<p>Logo?</p>
\ No newline at end of file
diff --git a/views/blog.erb b/views/blog.erb
index c8cca39..43253c1 100644
--- a/views/blog.erb
+++ b/views/blog.erb
@@ -1,3 +1,3 @@
<% @entries.each do |entry| %>
- <a href="/perm/<%= entry.id %>"><%= entry.title %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small><br/>
+ <%= partial(:entry, :locals => {:entry => entry}) %>
<% end %>
diff --git a/views/entry.erb b/views/entry.erb
index b394d3f..951b8aa 100644
--- a/views/entry.erb
+++ b/views/entry.erb
@@ -1,16 +1,3 @@
<% @title = @entry.title %>
-<h2>
- <% unless @entry.url.blank? %>
- <%= link_to @entry.title, @entry.url %>
- <% else %>
- <%= @entry.title %>
- <% end %>
-</h2>
-<% unless @entry.url.blank? %>
- <p style="margin-top:-20px"><small><%= @entry.short_uri %></small></p>
-<% end %>
-
-<%= @entry.html %>
-
-<small><%= @entry.created_at %></small>
\ No newline at end of file
+<%= partial(:entry, :locals => {:entry => @entry}) %>
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
index 1a250b0..f11d7b1 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,33 +1,34 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><%= @title ? "#{@title} | " : '' %> <%= @blog.title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
+ <link href="/tumblr.css" media="screen" rel="Stylesheet" type="text/css"></link>
<script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
<h1><%= link_to @blog.title, '/' %></h1>
<div id="nav">
- <% if logged_in? %>| <a href="/admin/new">Create</a> | <a href="/logout">Logout</a><% end %>
+ <% if logged_in? %><a href="/admin">Admin</a> | <%= link_to('New Entry', '/admin/new') %> | <a href="/logout">Logout</a><% end %>
</div>
<div id="content">
<%= yield %>
</div>
<div id="footer">
powered by <a href="http://github.com/moomerman/frog/tree/master">frog</a> and
<a href="http://github.com/bmizerany/sinatra/tree/master">sinatra</a>
| <a href="http://hobix.com/textile/">formatting</a>
</div>
</body>
</html>
\ No newline at end of file
|
kenfodder/frog
|
caabad86fa5aadcd2461ea6b9a1691dc6cc42f74
|
added page title for entry
|
diff --git a/Rakefile b/Rakefile
index d6764b2..a95d018 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,30 +1,30 @@
Dir["lib/*.rb"].each { |x| load x }
task :default do
puts 'rake frog:init to get started'
- puts 'rake frog:reset to reload the db schema'
+ puts 'rake frog:reset to reload the db schema (loses all data!)'
end
namespace :frog do
task :db_up do
Schema.up
end
task :db_down do
Schema.down
end
task :init => :db_up do
if Blog.count == 0
- blog = Blog.create!(:title => 'My Blog')
+ blog = Blog.create!(:title => 'My Frog Blog')
blog.entries.create(
:title => 'Welcome to Frog!',
:text => '!http://www1.istockphoto.com/file_thumbview_approve/1073907/2/istockphoto_1073907-frog-cartoon.jpg!'
)
end
end
task :reset => [:db_down, :init]
end
\ No newline at end of file
diff --git a/views/entry.erb b/views/entry.erb
index 80798ea..b394d3f 100644
--- a/views/entry.erb
+++ b/views/entry.erb
@@ -1,14 +1,16 @@
+<% @title = @entry.title %>
+
<h2>
<% unless @entry.url.blank? %>
<%= link_to @entry.title, @entry.url %>
<% else %>
<%= @entry.title %>
<% end %>
</h2>
<% unless @entry.url.blank? %>
<p style="margin-top:-20px"><small><%= @entry.short_uri %></small></p>
<% end %>
<%= @entry.html %>
<small><%= @entry.created_at %></small>
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
index d402408..1a250b0 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,33 +1,33 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
- <title><%= @blog.title %></title>
+ <title><%= @title ? "#{@title} | " : '' %> <%= @blog.title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
<script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
<h1><%= link_to @blog.title, '/' %></h1>
<div id="nav">
<% if logged_in? %>| <a href="/admin/new">Create</a> | <a href="/logout">Logout</a><% end %>
</div>
<div id="content">
<%= yield %>
</div>
<div id="footer">
powered by <a href="http://github.com/moomerman/frog/tree/master">frog</a> and
<a href="http://github.com/bmizerany/sinatra/tree/master">sinatra</a>
| <a href="http://hobix.com/textile/">formatting</a>
</div>
</body>
</html>
\ No newline at end of file
|
kenfodder/frog
|
8a84fe32b6f2edc8ae63ef21effc70a3fb31dfe0
|
added footer, more syntax styling, added first entry
|
diff --git a/Rakefile b/Rakefile
index a3481ad..d6764b2 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,24 +1,30 @@
Dir["lib/*.rb"].each { |x| load x }
task :default do
puts 'rake frog:init to get started'
puts 'rake frog:reset to reload the db schema'
end
namespace :frog do
task :db_up do
Schema.up
end
task :db_down do
Schema.down
end
task :init => :db_up do
- Blog.create!(:title => 'My Blog') if Blog.count == 0
+ if Blog.count == 0
+ blog = Blog.create!(:title => 'My Blog')
+ blog.entries.create(
+ :title => 'Welcome to Frog!',
+ :text => '!http://www1.istockphoto.com/file_thumbview_approve/1073907/2/istockphoto_1073907-frog-cartoon.jpg!'
+ )
+ end
end
task :reset => [:db_down, :init]
end
\ No newline at end of file
diff --git a/public/style.css b/public/style.css
index 41b34b8..be7220d 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1,41 +1,44 @@
body {font-family: verdana;}
code {font-family:"Bitstream Vera Sans Mono","Monaco","Courier",monospace;}
textarea {width:600px; height:300px;}
input {width:600px;}
#nav {margin-bottom:15px;}
-
+#footer {font-size:0.7em; margin-top:20px;}
/* Syntax highlighting */
#content .normal {}
-#content .comment { color: #CCC; font-style: italic; border: none; margin: none; }
+#content .comment { color: #CCC; font-style: italic; border: none; margin: 0; }
#content .keyword { color: #C60; font-weight: bold; }
#content .method { color: #9FF; }
#content .class { color: #074; }
#content .module { color: #050; }
#content .punct { color: #0D0; font-weight: bold; }
#content .symbol { color: #099; }
#content .string { color: #C03; }
#content .char { color: #F07; }
#content .ident { color: #0D0; }
#content .constant { color: #07F; }
#content .regex { color: #B66; }
#content .number { color: #FF0; }
#content .attribute { color: #7BB; }
#content .global { color: #7FB; }
#content .expr { color: #909; }
#content .escape { color: #277; }
#content .syntax {
+ width:650px;
+ background-color: #333;
+ padding: 2px;
+ margin: 5px;
+ margin-left: 1em;
font-size:9pt;
letter-spacing:0;
line-height:1.3em;
- margin-bottom:0;
- position:relative;
- white-space:pre;
}
#content .syntax .line_number {
text-align: right;
+ padding-left: 1em;
padding-right: 1em;
color: #999;
}
\ No newline at end of file
diff --git a/views/entry.erb b/views/entry.erb
index b386619..80798ea 100644
--- a/views/entry.erb
+++ b/views/entry.erb
@@ -1,12 +1,14 @@
<h2>
<% unless @entry.url.blank? %>
<%= link_to @entry.title, @entry.url %>
<% else %>
<%= @entry.title %>
<% end %>
</h2>
<% unless @entry.url.blank? %>
<p style="margin-top:-20px"><small><%= @entry.short_uri %></small></p>
<% end %>
-<%= @entry.html %>
\ No newline at end of file
+<%= @entry.html %>
+
+<small><%= @entry.created_at %></small>
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
index 2d3d1e3..d402408 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,30 +1,33 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><%= @blog.title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
<script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
<h1><%= link_to @blog.title, '/' %></h1>
<div id="nav">
<% if logged_in? %>| <a href="/admin/new">Create</a> | <a href="/logout">Logout</a><% end %>
</div>
<div id="content">
<%= yield %>
</div>
<div id="footer">
+ powered by <a href="http://github.com/moomerman/frog/tree/master">frog</a> and
+ <a href="http://github.com/bmizerany/sinatra/tree/master">sinatra</a>
+ | <a href="http://hobix.com/textile/">formatting</a>
</div>
</body>
</html>
\ No newline at end of file
|
kenfodder/frog
|
c70d156a1982220fbb02b803fd57838780f74beb
|
bug fixes
|
diff --git a/frog.rb b/frog.rb
index 11580c0..6098c1d 100755
--- a/frog.rb
+++ b/frog.rb
@@ -1,77 +1,77 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
Dir["lib/*.rb"].each { |x| load x }
configure do
set_option :sessions, true
end
before do
if request.path_info =~ /admin/ and !logged_in?
session['forward'] = request.path_info + (request.query_string.blank? ? '' : '?' + request.query_string)
redirect '/login'
end
@blog = Blog.find(:first)
end
get '/' do
@entries = @blog.entries
erb :blog
end
get '/perm/:id' do
@entry = @blog.entries.find(params[:id])
erb :entry
end
get '/login' do
erb :login
end
post '/login' do
if params[:username] == 'admin' and params['password'] == 'admin'
session[:user] = true
redirect session['forward'] || '/'
else
redirect '/login'
end
end
get '/logout' do
session[:user] = nil
redirect '/'
end
get '/admin' do
erb :admin
end
get '/admin/new' do
erb :new
end
post '/admin/create' do
entry = @blog.entries.create(
:title => params[:title],
:url => params[:url],
:text => params[:text]
)
- redirect "/#{entry.id}"
+ redirect "/perm/#{entry.id}"
end
get '/admin/bookmark' do
url = params[:url]
title = scrape_page_title(url)
@blog.entries.create(
:title => title,
:url => url
)
redirect url
end
helpers do
include Helpers
end
\ No newline at end of file
diff --git a/views/new.erb b/views/new.erb
index a7dd9d3..c010653 100644
--- a/views/new.erb
+++ b/views/new.erb
@@ -1,6 +1,6 @@
-<form action="/create" method="post">
- <p><input type="text" name="title"/></p>
- <p><input type="text" name="url"/></p>
- <p><textarea name="text"></textarea></p>
+<form action="/admin/create" method="post">
+ <p><b>Title</b> <input type="text" name="title"/></p>
+ <p><b>URL?</b> <input type="text" name="url"/></p>
+ <p><b>Text</b> <textarea name="text"></textarea></p>
<p><input type="submit" value="create"/></p>
</form>
\ No newline at end of file
|
kenfodder/frog
|
ebc08b2f3d2f8c861ebc64b966ee4c8773a83584
|
more info in the readme
|
diff --git a/README.textile b/README.textile
index 2f9d524..92dda2e 100644
--- a/README.textile
+++ b/README.textile
@@ -1,3 +1,21 @@
h1. Frog
Frog will be a full-featured blog application written using the sinatra web framework. It's still in early development.
+
+h2. Installing and Running
+
+* gem install sinatra # the tiny web framework
+* gem install active_record # my orm of choice
+* gem install sqlite3-ruby # the default data store
+* gem install RedCloth # textile markup processor
+* gem install syntaxi # code syntax formatting
+
+* git clone git://github.com/moomerman/frog.git
+* cd frog
+* rake frog:init
+* ./frog.rb
+# go to http://localhost:4567/
+
+By default frog uses sqlite3 as the data store, but you can use anything that ActiveRecord supports, configure this in lib/models.rb.
+
+To create a new blog entry you need to go to /admin and login with admin:admin.
\ No newline at end of file
|
kenfodder/frog
|
a5222a8290377c6669505b979c17aee684ee7487
|
added a readme
|
diff --git a/README.textile b/README.textile
new file mode 100644
index 0000000..2f9d524
--- /dev/null
+++ b/README.textile
@@ -0,0 +1,3 @@
+h1. Frog
+
+Frog will be a full-featured blog application written using the sinatra web framework. It's still in early development.
|
kenfodder/frog
|
ae120e583797bcd85ae9871f4db7c16f33e7d8d2
|
fixed the bookmark tool and added some notes to the admin page
|
diff --git a/frog.rb b/frog.rb
index 50d1b9f..11580c0 100755
--- a/frog.rb
+++ b/frog.rb
@@ -1,77 +1,77 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
Dir["lib/*.rb"].each { |x| load x }
configure do
set_option :sessions, true
end
before do
if request.path_info =~ /admin/ and !logged_in?
- session['forward'] = request.path_info
+ session['forward'] = request.path_info + (request.query_string.blank? ? '' : '?' + request.query_string)
redirect '/login'
end
@blog = Blog.find(:first)
end
get '/' do
@entries = @blog.entries
erb :blog
end
get '/perm/:id' do
@entry = @blog.entries.find(params[:id])
erb :entry
end
get '/login' do
erb :login
end
post '/login' do
if params[:username] == 'admin' and params['password'] == 'admin'
session[:user] = true
redirect session['forward'] || '/'
else
redirect '/login'
end
end
get '/logout' do
session[:user] = nil
redirect '/'
end
get '/admin' do
erb :admin
end
get '/admin/new' do
erb :new
end
post '/admin/create' do
entry = @blog.entries.create(
:title => params[:title],
:url => params[:url],
:text => params[:text]
)
redirect "/#{entry.id}"
end
get '/admin/bookmark' do
url = params[:url]
title = scrape_page_title(url)
@blog.entries.create(
:title => title,
:url => url
)
redirect url
end
helpers do
include Helpers
end
\ No newline at end of file
diff --git a/views/admin.erb b/views/admin.erb
index 71b6c65..189001e 100644
--- a/views/admin.erb
+++ b/views/admin.erb
@@ -1 +1,8 @@
-<h2>TODO</h2>
\ No newline at end of file
+<h2>Admin</h2>
+
+<p><b>Blog Title</b> <%= @blog.title %></p>
+
+<p>Google analytics code</p>
+<p>Keywords & Description</p>
+<p>Any rhc widgets</p>
+<p>Logo?</p>
\ No newline at end of file
diff --git a/views/entry.erb b/views/entry.erb
index 53d34dc..b386619 100644
--- a/views/entry.erb
+++ b/views/entry.erb
@@ -1,12 +1,12 @@
<h2>
- <% if @entry.url %>
+ <% unless @entry.url.blank? %>
<%= link_to @entry.title, @entry.url %>
<% else %>
<%= @entry.title %>
<% end %>
</h2>
-<% if @entry.url %>
+<% unless @entry.url.blank? %>
<p style="margin-top:-20px"><small><%= @entry.short_uri %></small></p>
<% end %>
<%= @entry.html %>
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
index bea7391..2d3d1e3 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,30 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><%= @blog.title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
<script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
-<h1><%= @blog.title %></h1>
+<h1><%= link_to @blog.title, '/' %></h1>
<div id="nav">
- <a href="/">Home</a> | <a href="/admin">Admin</a> <% if logged_in? %>| <a href="/admin/new">Create</a> | <a href="/logout">Logout</a><% end %>
+ <% if logged_in? %>| <a href="/admin/new">Create</a> | <a href="/logout">Logout</a><% end %>
</div>
<div id="content">
<%= yield %>
</div>
<div id="footer">
</div>
</body>
</html>
\ No newline at end of file
|
kenfodder/frog
|
d7f5a922ad8f291bc7643885766607224f0bdd39
|
Fixed the syntax highlighting Created an admin area
|
diff --git a/frog.rb b/frog.rb
index a926009..50d1b9f 100755
--- a/frog.rb
+++ b/frog.rb
@@ -1,33 +1,77 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
Dir["lib/*.rb"].each { |x| load x }
+configure do
+ set_option :sessions, true
+end
+
before do
+ if request.path_info =~ /admin/ and !logged_in?
+ session['forward'] = request.path_info
+ redirect '/login'
+ end
@blog = Blog.find(:first)
end
get '/' do
@entries = @blog.entries
erb :blog
end
-get '/new' do
+get '/perm/:id' do
+ @entry = @blog.entries.find(params[:id])
+ erb :entry
+end
+
+get '/login' do
+ erb :login
+end
+
+post '/login' do
+ if params[:username] == 'admin' and params['password'] == 'admin'
+ session[:user] = true
+ redirect session['forward'] || '/'
+ else
+ redirect '/login'
+ end
+end
+
+get '/logout' do
+ session[:user] = nil
+ redirect '/'
+end
+
+get '/admin' do
+ erb :admin
+end
+
+get '/admin/new' do
erb :new
end
-post '/create' do
- entry = @blog.entries.create(:title => params[:title], :text => params[:text])
+post '/admin/create' do
+ entry = @blog.entries.create(
+ :title => params[:title],
+ :url => params[:url],
+ :text => params[:text]
+ )
redirect "/#{entry.id}"
end
-get '/:id' do
- @entry = @blog.entries.find(params[:id])
- erb :entry
+get '/admin/bookmark' do
+ url = params[:url]
+ title = scrape_page_title(url)
+ @blog.entries.create(
+ :title => title,
+ :url => url
+ )
+ redirect url
end
helpers do
include Helpers
end
\ No newline at end of file
diff --git a/lib/helpers.rb b/lib/helpers.rb
index b022f36..8971933 100644
--- a/lib/helpers.rb
+++ b/lib/helpers.rb
@@ -1,21 +1,66 @@
module Helpers
+
+ def logged_in?
+ session[:user]
+ end
+
+ def partial(name, options={})
+ erb("_#{name.to_s}".to_sym, options.merge(:layout => false))
+ end
+
+ def image_tag(file, options={})
+ tag = "<img src='/images/#{file}'"
+ if options[:alt]
+ tag += " alt='#{options[:alt]}' title='#{options[:alt]}' "
+ end
+ tag += "/>"
+ end
+
+ def link_to(text, link='#')
+ "<a href='#{link}'>#{text}</a>"
+ end
+
+ def scrape_page_title(url)
+ page_title = /<title>\s*(.*)\s*<\/title>/i
+ begin
+ page_content = Timeout.timeout(5) {
+ fetch(url).body.to_s
+ }
+ matches = page_content.match(page_title)
+ matches[1] if matches || nil
+ rescue Exception => e
+ url
+ end
+ end
+ def fetch(uri_str, limit = 3)
+ return false if limit == 0
+
+ response = Net::HTTP.get_response(URI.parse(uri_str))
+ case response
+ when Net::HTTPSuccess then response
+ when Net::HTTPRedirection then fetch(response['location'], limit - 1)
+ else
+ return false
+ end
+ end
+
def time_ago_or_time_stamp(from_time, to_time = Time.now, include_seconds = true, detail = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1 then time = (distance_in_seconds < 60) ? "#{distance_in_seconds} seconds ago" : '1 minute ago'
when 2..59 then time = "#{distance_in_minutes} minutes ago"
when 60..90 then time = "1 hour ago"
when 90..1440 then time = "#{(distance_in_minutes.to_f / 60.0).round} hours ago"
when 1440..2160 then time = '1 day ago' # 1-1.5 days
when 2160..2880 then time = "#{(distance_in_minutes.to_f / 1440.0).round} days ago" # 1.5-2 days
else time = from_time.strftime("%a, %d %b %Y")
end
return time_stamp(from_time) if (detail && distance_in_minutes > 2880)
return time
end
end
\ No newline at end of file
diff --git a/lib/models.rb b/lib/models.rb
index c03155b..f4b0599 100644
--- a/lib/models.rb
+++ b/lib/models.rb
@@ -1,25 +1,45 @@
require 'active_record'
require 'redcloth'
require 'syntaxi'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "lib/frog.db"
)
class Blog < ActiveRecord::Base
has_many :entries, :order => 'created_at DESC'
end
class Entry < ActiveRecord::Base
belongs_to :blog
Syntaxi.line_number_method = 'floating'
Syntaxi.wrap_at_column = 80
def html
- html = RedCloth.new(self.text).to_html
- html = Syntaxi.new(html).process
+ return if self.text.blank?
+
+ s = StringScanner.new(self.text)
+ html = ''
+ while markup = s.scan_until(/\[code/) do
+ html += RedCloth.new(markup[0..-6]).to_html
+ s.pos= s.pos-5
+ code = s.scan_until(/\[\/code\]/)
+ if code
+ code.gsub!(/\[code\]/, '[code lang="ruby"]')
+ html += '<div class="syntax">' + Syntaxi.new(code).process + '</div>'
+ else
+ break
+ end
+ end
+ html += RedCloth.new(s.rest).to_html
+
+ html
+ end
+
+ def short_uri
+ URI.parse(self.url).host.gsub(/www./, '') rescue self.url
end
end
\ No newline at end of file
diff --git a/lib/schema.rb b/lib/schema.rb
index 054d99c..b60b9fe 100644
--- a/lib/schema.rb
+++ b/lib/schema.rb
@@ -1,22 +1,23 @@
class Schema < ActiveRecord::Migration
def self.up
create_table :blogs do |t|
t.string :title
t.timestamps
end unless ActiveRecord::Base.connection.tables.include?('blogs')
create_table :entries do |t|
t.integer :blog_id
t.string :title
+ t.string :url
t.text :text
t.timestamps
end unless ActiveRecord::Base.connection.tables.include?('entries')
end
def self.down
drop_table :blogs if ActiveRecord::Base.connection.tables.include?('blogs')
drop_table :entries if ActiveRecord::Base.connection.tables.include?('entries')
end
end
\ No newline at end of file
diff --git a/public/style.css b/public/style.css
index 12a6e8b..41b34b8 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1,40 +1,41 @@
-* {font-family:verdana;}
+body {font-family: verdana;}
+code {font-family:"Bitstream Vera Sans Mono","Monaco","Courier",monospace;}
textarea {width:600px; height:300px;}
input {width:600px;}
#nav {margin-bottom:15px;}
/* Syntax highlighting */
#content .normal {}
#content .comment { color: #CCC; font-style: italic; border: none; margin: none; }
#content .keyword { color: #C60; font-weight: bold; }
#content .method { color: #9FF; }
#content .class { color: #074; }
#content .module { color: #050; }
#content .punct { color: #0D0; font-weight: bold; }
#content .symbol { color: #099; }
#content .string { color: #C03; }
#content .char { color: #F07; }
#content .ident { color: #0D0; }
#content .constant { color: #07F; }
#content .regex { color: #B66; }
#content .number { color: #FF0; }
#content .attribute { color: #7BB; }
#content .global { color: #7FB; }
#content .expr { color: #909; }
#content .escape { color: #277; }
#content .syntax {
- background-color: #333;
- padding: 2px;
- margin: 5px;
- margin-left: 1em;
- margin-bottom: 1em;
+ font-size:9pt;
+ letter-spacing:0;
+ line-height:1.3em;
+ margin-bottom:0;
+ position:relative;
+ white-space:pre;
}
#content .syntax .line_number {
text-align: right;
- font-family: monospace;
padding-right: 1em;
color: #999;
}
\ No newline at end of file
diff --git a/views/admin.erb b/views/admin.erb
new file mode 100644
index 0000000..71b6c65
--- /dev/null
+++ b/views/admin.erb
@@ -0,0 +1 @@
+<h2>TODO</h2>
\ No newline at end of file
diff --git a/views/blog.erb b/views/blog.erb
index 3f8de35..c8cca39 100644
--- a/views/blog.erb
+++ b/views/blog.erb
@@ -1,3 +1,3 @@
<% @entries.each do |entry| %>
- <a href="/<%= entry.id %>"><%= entry.title %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small><br/>
+ <a href="/perm/<%= entry.id %>"><%= entry.title %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small><br/>
<% end %>
diff --git a/views/entry.erb b/views/entry.erb
index 8b79b72..53d34dc 100644
--- a/views/entry.erb
+++ b/views/entry.erb
@@ -1,3 +1,12 @@
-<h2><%= @entry.title %></h2>
+<h2>
+ <% if @entry.url %>
+ <%= link_to @entry.title, @entry.url %>
+ <% else %>
+ <%= @entry.title %>
+ <% end %>
+</h2>
+<% if @entry.url %>
+ <p style="margin-top:-20px"><small><%= @entry.short_uri %></small></p>
+<% end %>
<%= @entry.html %>
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
index d3626df..bea7391 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,30 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><%= @blog.title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
<script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
<h1><%= @blog.title %></h1>
<div id="nav">
- <a href="/">Home</a> | <a href="/new">Create</a>
+ <a href="/">Home</a> | <a href="/admin">Admin</a> <% if logged_in? %>| <a href="/admin/new">Create</a> | <a href="/logout">Logout</a><% end %>
</div>
<div id="content">
<%= yield %>
</div>
<div id="footer">
</div>
</body>
</html>
\ No newline at end of file
diff --git a/views/login.erb b/views/login.erb
new file mode 100644
index 0000000..1d8355a
--- /dev/null
+++ b/views/login.erb
@@ -0,0 +1,5 @@
+<form action="/login" method="post">
+ <p><input type="text" name="username"/></p>
+ <p><input type="text" name="password"/></p>
+ <p><input type="submit" value="login"/></p>
+</form>
\ No newline at end of file
diff --git a/views/new.erb b/views/new.erb
index c3d56e5..a7dd9d3 100644
--- a/views/new.erb
+++ b/views/new.erb
@@ -1,5 +1,6 @@
<form action="/create" method="post">
<p><input type="text" name="title"/></p>
+ <p><input type="text" name="url"/></p>
<p><textarea name="text"></textarea></p>
<p><input type="submit" value="create"/></p>
</form>
\ No newline at end of file
|
kenfodder/frog
|
9dd9fea343c7c8ab847ec0bc4d67ce550462f56e
|
added syntax highlighting
|
diff --git a/frog.rb b/frog.rb
index 724a880..a926009 100755
--- a/frog.rb
+++ b/frog.rb
@@ -1,33 +1,33 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
Dir["lib/*.rb"].each { |x| load x }
before do
@blog = Blog.find(:first)
end
get '/' do
@entries = @blog.entries
erb :blog
end
get '/new' do
erb :new
end
post '/create' do
- @blog.entries.create(:text => params[:text])
- redirect '/'
+ entry = @blog.entries.create(:title => params[:title], :text => params[:text])
+ redirect "/#{entry.id}"
end
get '/:id' do
@entry = @blog.entries.find(params[:id])
erb :entry
end
helpers do
include Helpers
end
\ No newline at end of file
diff --git a/lib/models.rb b/lib/models.rb
index 667f596..c03155b 100644
--- a/lib/models.rb
+++ b/lib/models.rb
@@ -1,14 +1,25 @@
require 'active_record'
+require 'redcloth'
+require 'syntaxi'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "lib/frog.db"
)
class Blog < ActiveRecord::Base
has_many :entries, :order => 'created_at DESC'
end
class Entry < ActiveRecord::Base
belongs_to :blog
+
+ Syntaxi.line_number_method = 'floating'
+ Syntaxi.wrap_at_column = 80
+
+ def html
+ html = RedCloth.new(self.text).to_html
+ html = Syntaxi.new(html).process
+ end
+
end
\ No newline at end of file
diff --git a/lib/schema.rb b/lib/schema.rb
index 744cbc8..054d99c 100644
--- a/lib/schema.rb
+++ b/lib/schema.rb
@@ -1,21 +1,22 @@
class Schema < ActiveRecord::Migration
def self.up
create_table :blogs do |t|
t.string :title
t.timestamps
end unless ActiveRecord::Base.connection.tables.include?('blogs')
create_table :entries do |t|
t.integer :blog_id
+ t.string :title
t.text :text
t.timestamps
end unless ActiveRecord::Base.connection.tables.include?('entries')
end
def self.down
drop_table :blogs if ActiveRecord::Base.connection.tables.include?('blogs')
drop_table :entries if ActiveRecord::Base.connection.tables.include?('entries')
end
end
\ No newline at end of file
diff --git a/public/style.css b/public/style.css
index 56e0f4b..12a6e8b 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1,3 +1,40 @@
* {font-family:verdana;}
-#nav {margin-bottom:15px;}
\ No newline at end of file
+textarea {width:600px; height:300px;}
+input {width:600px;}
+
+#nav {margin-bottom:15px;}
+
+
+/* Syntax highlighting */
+#content .normal {}
+#content .comment { color: #CCC; font-style: italic; border: none; margin: none; }
+#content .keyword { color: #C60; font-weight: bold; }
+#content .method { color: #9FF; }
+#content .class { color: #074; }
+#content .module { color: #050; }
+#content .punct { color: #0D0; font-weight: bold; }
+#content .symbol { color: #099; }
+#content .string { color: #C03; }
+#content .char { color: #F07; }
+#content .ident { color: #0D0; }
+#content .constant { color: #07F; }
+#content .regex { color: #B66; }
+#content .number { color: #FF0; }
+#content .attribute { color: #7BB; }
+#content .global { color: #7FB; }
+#content .expr { color: #909; }
+#content .escape { color: #277; }
+#content .syntax {
+ background-color: #333;
+ padding: 2px;
+ margin: 5px;
+ margin-left: 1em;
+ margin-bottom: 1em;
+}
+#content .syntax .line_number {
+ text-align: right;
+ font-family: monospace;
+ padding-right: 1em;
+ color: #999;
+}
\ No newline at end of file
diff --git a/views/blog.erb b/views/blog.erb
index 5aff014..3f8de35 100644
--- a/views/blog.erb
+++ b/views/blog.erb
@@ -1,3 +1,3 @@
<% @entries.each do |entry| %>
- <a href="/<%= entry.id %>"><%= entry.text %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small><br/>
+ <a href="/<%= entry.id %>"><%= entry.title %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small><br/>
<% end %>
diff --git a/views/entry.erb b/views/entry.erb
index 3aaa4f0..8b79b72 100644
--- a/views/entry.erb
+++ b/views/entry.erb
@@ -1 +1,3 @@
-<h2><%= @entry.text %></h2>
\ No newline at end of file
+<h2><%= @entry.title %></h2>
+
+<%= @entry.html %>
\ No newline at end of file
diff --git a/views/new.erb b/views/new.erb
index 45c0057..c3d56e5 100644
--- a/views/new.erb
+++ b/views/new.erb
@@ -1,4 +1,5 @@
<form action="/create" method="post">
- <textarea name="text"></textarea>
- <input type="submit" value="create"/>
+ <p><input type="text" name="title"/></p>
+ <p><textarea name="text"></textarea></p>
+ <p><input type="submit" value="create"/></p>
</form>
\ No newline at end of file
|
kenfodder/frog
|
0e08200d8998ca3fb90d4a5a3aa5008d0f2fdbed
|
added some style info
|
diff --git a/public/style.css b/public/style.css
index ca683e1..56e0f4b 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1 +1,3 @@
-* {font-family:verdana;}
\ No newline at end of file
+* {font-family:verdana;}
+
+#nav {margin-bottom:15px;}
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
index 054392e..d3626df 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,22 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><%= @blog.title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
<script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
+
+<h1><%= @blog.title %></h1>
-<a href="/">Home</a> | <a href="/new">Create</a>
-<br/><br/>
+<div id="nav">
+ <a href="/">Home</a> | <a href="/new">Create</a>
+</div>
+
+<div id="content">
+ <%= yield %>
+</div>
-<%= yield %>
+<div id="footer">
+</div>
</body>
</html>
\ No newline at end of file
|
kenfodder/frog
|
210457a77d320c88a51a02c3a3c1d232dbaf9d3e
|
now valid xhtml transitional
|
diff --git a/views/layout.erb b/views/layout.erb
index 3fb7e4d..054392e 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,17 +1,22 @@
-<html>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+
<head>
<title><%= @blog.title %></title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
<script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
</head>
<body>
<a href="/">Home</a> | <a href="/new">Create</a>
<br/><br/>
<%= yield %>
</body>
</html>
\ No newline at end of file
|
kenfodder/frog
|
9783d9932ec44b720065204f6d193f68ebe09820
|
added jquery and a html layout
|
diff --git a/frog.rb b/frog.rb
index cfb4228..724a880 100755
--- a/frog.rb
+++ b/frog.rb
@@ -1,33 +1,33 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
Dir["lib/*.rb"].each { |x| load x }
before do
@blog = Blog.find(:first)
end
get '/' do
@entries = @blog.entries
erb :blog
end
get '/new' do
erb :new
end
post '/create' do
@blog.entries.create(:text => params[:text])
redirect '/'
end
get '/:id' do
- @entry = Entry.find(params[:id])
+ @entry = @blog.entries.find(params[:id])
erb :entry
end
helpers do
include Helpers
end
\ No newline at end of file
diff --git a/public/jquery-1.2.6.min.js b/public/jquery-1.2.6.min.js
new file mode 100644
index 0000000..82b98e1
--- /dev/null
+++ b/public/jquery-1.2.6.min.js
@@ -0,0 +1,32 @@
+/*
+ * jQuery 1.2.6 - New Wave Javascript
+ *
+ * Copyright (c) 2008 John Resig (jquery.com)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
+ * $Rev: 5685 $
+ */
+(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else
+return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
+return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
+selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
+return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
+this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
+return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
+jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&©&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
+script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
+for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
+for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
+jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
+ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&¬xml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&¬xml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&¬xml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
+while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
+while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
+for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
+jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
+xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
+jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
+for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
+s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
+e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();
\ No newline at end of file
diff --git a/public/style.css b/public/style.css
index e69de29..ca683e1 100644
--- a/public/style.css
+++ b/public/style.css
@@ -0,0 +1 @@
+* {font-family:verdana;}
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
index d0228d3..3fb7e4d 100644
--- a/views/layout.erb
+++ b/views/layout.erb
@@ -1,3 +1,17 @@
+<html>
+<head>
+ <title><%= @blog.title %></title>
+ <link href="/style.css" media="screen" rel="Stylesheet" type="text/css"></link>
+ <script src="/jquery-1.2.6.min.js" type="text/javascript"></script>
+</head>
+
+<body>
+
<a href="/">Home</a> | <a href="/new">Create</a>
-<br/>
-<%= yield %>
\ No newline at end of file
+<br/><br/>
+
+<%= yield %>
+
+</body>
+
+</html>
\ No newline at end of file
|
kenfodder/frog
|
c0073bb5c816aa40efe6381001f1ae67316d7354
|
Initial blog stucture and simple models
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..3bb567f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+lib/frog.db
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..a3481ad
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,24 @@
+Dir["lib/*.rb"].each { |x| load x }
+
+task :default do
+ puts 'rake frog:init to get started'
+ puts 'rake frog:reset to reload the db schema'
+end
+
+namespace :frog do
+
+ task :db_up do
+ Schema.up
+ end
+
+ task :db_down do
+ Schema.down
+ end
+
+ task :init => :db_up do
+ Blog.create!(:title => 'My Blog') if Blog.count == 0
+ end
+
+ task :reset => [:db_down, :init]
+
+end
\ No newline at end of file
diff --git a/frog.rb b/frog.rb
new file mode 100755
index 0000000..cfb4228
--- /dev/null
+++ b/frog.rb
@@ -0,0 +1,33 @@
+#!/usr/bin/env ruby
+
+require 'rubygems'
+require 'sinatra'
+
+Dir["lib/*.rb"].each { |x| load x }
+
+before do
+ @blog = Blog.find(:first)
+end
+
+get '/' do
+ @entries = @blog.entries
+ erb :blog
+end
+
+get '/new' do
+ erb :new
+end
+
+post '/create' do
+ @blog.entries.create(:text => params[:text])
+ redirect '/'
+end
+
+get '/:id' do
+ @entry = Entry.find(params[:id])
+ erb :entry
+end
+
+helpers do
+ include Helpers
+end
\ No newline at end of file
diff --git a/lib/helpers.rb b/lib/helpers.rb
new file mode 100644
index 0000000..b022f36
--- /dev/null
+++ b/lib/helpers.rb
@@ -0,0 +1,21 @@
+module Helpers
+
+ def time_ago_or_time_stamp(from_time, to_time = Time.now, include_seconds = true, detail = false)
+ from_time = from_time.to_time if from_time.respond_to?(:to_time)
+ to_time = to_time.to_time if to_time.respond_to?(:to_time)
+ distance_in_minutes = (((to_time - from_time).abs)/60).round
+ distance_in_seconds = ((to_time - from_time).abs).round
+ case distance_in_minutes
+ when 0..1 then time = (distance_in_seconds < 60) ? "#{distance_in_seconds} seconds ago" : '1 minute ago'
+ when 2..59 then time = "#{distance_in_minutes} minutes ago"
+ when 60..90 then time = "1 hour ago"
+ when 90..1440 then time = "#{(distance_in_minutes.to_f / 60.0).round} hours ago"
+ when 1440..2160 then time = '1 day ago' # 1-1.5 days
+ when 2160..2880 then time = "#{(distance_in_minutes.to_f / 1440.0).round} days ago" # 1.5-2 days
+ else time = from_time.strftime("%a, %d %b %Y")
+ end
+ return time_stamp(from_time) if (detail && distance_in_minutes > 2880)
+ return time
+ end
+
+end
\ No newline at end of file
diff --git a/lib/models.rb b/lib/models.rb
new file mode 100644
index 0000000..667f596
--- /dev/null
+++ b/lib/models.rb
@@ -0,0 +1,14 @@
+require 'active_record'
+
+ActiveRecord::Base.establish_connection(
+ :adapter => "sqlite3",
+ :database => "lib/frog.db"
+)
+
+class Blog < ActiveRecord::Base
+ has_many :entries, :order => 'created_at DESC'
+end
+
+class Entry < ActiveRecord::Base
+ belongs_to :blog
+end
\ No newline at end of file
diff --git a/lib/schema.rb b/lib/schema.rb
new file mode 100644
index 0000000..744cbc8
--- /dev/null
+++ b/lib/schema.rb
@@ -0,0 +1,21 @@
+class Schema < ActiveRecord::Migration
+
+ def self.up
+ create_table :blogs do |t|
+ t.string :title
+ t.timestamps
+ end unless ActiveRecord::Base.connection.tables.include?('blogs')
+
+ create_table :entries do |t|
+ t.integer :blog_id
+ t.text :text
+ t.timestamps
+ end unless ActiveRecord::Base.connection.tables.include?('entries')
+ end
+
+ def self.down
+ drop_table :blogs if ActiveRecord::Base.connection.tables.include?('blogs')
+ drop_table :entries if ActiveRecord::Base.connection.tables.include?('entries')
+ end
+
+end
\ No newline at end of file
diff --git a/public/style.css b/public/style.css
new file mode 100644
index 0000000..e69de29
diff --git a/views/blog.erb b/views/blog.erb
new file mode 100644
index 0000000..5aff014
--- /dev/null
+++ b/views/blog.erb
@@ -0,0 +1,3 @@
+<% @entries.each do |entry| %>
+ <a href="/<%= entry.id %>"><%= entry.text %></a> <small>(<%= time_ago_or_time_stamp(entry.created_at) %>)</small><br/>
+<% end %>
diff --git a/views/entry.erb b/views/entry.erb
new file mode 100644
index 0000000..3aaa4f0
--- /dev/null
+++ b/views/entry.erb
@@ -0,0 +1 @@
+<h2><%= @entry.text %></h2>
\ No newline at end of file
diff --git a/views/layout.erb b/views/layout.erb
new file mode 100644
index 0000000..d0228d3
--- /dev/null
+++ b/views/layout.erb
@@ -0,0 +1,3 @@
+<a href="/">Home</a> | <a href="/new">Create</a>
+<br/>
+<%= yield %>
\ No newline at end of file
diff --git a/views/new.erb b/views/new.erb
new file mode 100644
index 0000000..45c0057
--- /dev/null
+++ b/views/new.erb
@@ -0,0 +1,4 @@
+<form action="/create" method="post">
+ <textarea name="text"></textarea>
+ <input type="submit" value="create"/>
+</form>
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
a32a60742bcdf58f2ab2e237e3b199f33718b10a
|
add github-pages supported plugins
|
diff --git a/Gemfile b/Gemfile
index 202d61a..3f6314a 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,4 +1,6 @@
source "https://rubygems.org"
gem 'github-pages'
-gem 'jekyll-assets'
+gem 'jekyll-sitemap'
+gem 'jekyll-mentions'
+gem 'jemoji'
diff --git a/Gemfile.lock b/Gemfile.lock
index eeaebd4..43adedb 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,138 +1,92 @@
GEM
remote: https://rubygems.org/
specs:
RedCloth (4.2.9)
activesupport (4.1.6)
i18n (~> 0.6, >= 0.6.9)
json (~> 1.7, >= 1.7.7)
minitest (~> 5.1)
thread_safe (~> 0.1)
tzinfo (~> 1.1)
blankslate (2.1.2.4)
- celluloid (0.16.0)
- timers (~> 4.0.0)
- classifier-reborn (2.0.1)
- fast-stemmer (~> 1.0)
- coffee-script (2.3.0)
- coffee-script-source
- execjs
- coffee-script-source (1.8.0)
+ classifier (1.3.4)
+ fast-stemmer (>= 1.0.0)
colorator (0.1)
- execjs (2.2.1)
+ commander (4.1.6)
+ highline (~> 1.6.11)
fast-stemmer (1.0.2)
ffi (1.9.5)
- gemoji (2.1.0)
- github-pages (28)
+ gemoji (1.5.0)
+ github-pages (15)
RedCloth (= 4.2.9)
- jekyll (= 2.4.0)
- jekyll-coffeescript (= 1.0.0)
- jekyll-mentions (= 0.1.3)
- jekyll-redirect-from (= 0.6.2)
- jekyll-sass-converter (= 1.2.0)
- jekyll-sitemap (= 0.6.0)
- jemoji (= 0.3.0)
+ jekyll (= 1.4.3)
kramdown (= 1.3.1)
- liquid (= 2.6.1)
+ liquid (= 2.5.5)
maruku (= 0.7.0)
- pygments.rb (= 0.6.0)
rdiscount (= 2.1.7)
- redcarpet (= 3.1.2)
- hike (1.2.3)
- hitimes (1.2.2)
- html-pipeline (1.9.0)
+ redcarpet (= 2.3.0)
+ highline (1.6.21)
+ html-pipeline (1.5.0)
activesupport (>= 2)
nokogiri (~> 1.4)
i18n (0.6.11)
- jekyll (2.4.0)
- classifier-reborn (~> 2.0)
+ jekyll (1.4.3)
+ classifier (~> 1.3)
colorator (~> 0.1)
- jekyll-coffeescript (~> 1.0)
- jekyll-gist (~> 1.0)
- jekyll-paginate (~> 1.0)
- jekyll-sass-converter (~> 1.0)
- jekyll-watch (~> 1.1)
- kramdown (~> 1.3)
- liquid (~> 2.6.1)
- mercenary (~> 0.3.3)
- pygments.rb (~> 0.6.0)
- redcarpet (~> 3.1)
- safe_yaml (~> 1.0)
+ commander (~> 4.1.3)
+ liquid (~> 2.5.5)
+ listen (~> 1.3)
+ maruku (~> 0.7.0)
+ pygments.rb (~> 0.5.0)
+ redcarpet (~> 2.3.0)
+ safe_yaml (~> 0.9.7)
toml (~> 0.1.0)
- jekyll-assets (0.10.0)
- jekyll (~> 2.0)
- sass (~> 3.2)
- sprockets (~> 2.10)
- sprockets-helpers
- sprockets-sass
- jekyll-coffeescript (1.0.0)
- coffee-script (~> 2.2)
- jekyll-gist (1.1.0)
- jekyll-mentions (0.1.3)
- html-pipeline (~> 1.9.0)
- jekyll (~> 2.0)
- jekyll-paginate (1.0.0)
- jekyll-redirect-from (0.6.2)
- jekyll (~> 2.0)
- jekyll-sass-converter (1.2.0)
- sass (~> 3.2)
+ jekyll-mentions (0.0.9)
+ html-pipeline (~> 1.5.0)
+ jekyll (~> 1.4)
jekyll-sitemap (0.6.0)
- jekyll-watch (1.1.1)
- listen (~> 2.7)
- jemoji (0.3.0)
- gemoji (~> 2.0)
- html-pipeline (~> 1.9)
- jekyll (~> 2.0)
+ jemoji (0.1.0)
+ gemoji (~> 1.5.0)
+ html-pipeline (~> 1.5.0)
+ jekyll (~> 1.4)
json (1.8.1)
kramdown (1.3.1)
- liquid (2.6.1)
- listen (2.7.11)
- celluloid (>= 0.15.2)
+ liquid (2.5.5)
+ listen (1.3.1)
rb-fsevent (>= 0.9.3)
rb-inotify (>= 0.9)
+ rb-kqueue (>= 0.2)
maruku (0.7.0)
- mercenary (0.3.4)
mini_portile (0.6.0)
minitest (5.4.2)
- multi_json (1.10.1)
nokogiri (1.6.3.1)
mini_portile (= 0.6.0)
parslet (1.5.0)
blankslate (~> 2.0)
posix-spawn (0.3.9)
- pygments.rb (0.6.0)
+ pygments.rb (0.5.4)
posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.1.0)
- rack (1.5.2)
rb-fsevent (0.9.4)
rb-inotify (0.9.5)
ffi (>= 0.5.0)
+ rb-kqueue (0.2.3)
+ ffi (>= 0.5.0)
rdiscount (2.1.7)
- redcarpet (3.1.2)
- safe_yaml (1.0.4)
- sass (3.4.5)
- sprockets (2.12.2)
- hike (~> 1.2)
- multi_json (~> 1.0)
- rack (~> 1.0)
- tilt (~> 1.1, != 1.3.0)
- sprockets-helpers (1.1.0)
- sprockets (~> 2.0)
- sprockets-sass (1.2.0)
- sprockets (~> 2.0)
- tilt (~> 1.1)
+ redcarpet (2.3.0)
+ safe_yaml (0.9.7)
thread_safe (0.3.4)
- tilt (1.4.1)
- timers (4.0.1)
- hitimes
toml (0.1.1)
parslet (~> 1.5.0)
tzinfo (1.2.2)
thread_safe (~> 0.1)
yajl-ruby (1.1.0)
PLATFORMS
ruby
DEPENDENCIES
github-pages
- jekyll-assets
+ jekyll-mentions
+ jekyll-sitemap
+ jemoji
diff --git a/_config.yml b/_config.yml
index a8a576b..09898a6 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,42 +1,42 @@
permalink: /:year/:month/:title.html
exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md, README_POSTS.md ]
future: false
lsi: true # Produces an index for related posts.
paginate: 10
plugins: ./_plugins
-
-# assets:
-# js_compressor: uglifier
-# css_compressor: sass
+gems:
+ - jekyll-sitemap
+ - jekyll-mentions
+ - jemoji
defaults:
-
scope:
path: _posts
type: posts
values:
layout: post
author: Marcos Hack
brand: mhack
author:
name: Marcos Hack
email: [email protected]
twitter: marcoshack
github: marcoshack
linkedin: marcoshack
google_plus: 101876381204467415756
title_sufix: '- Marcos Hack'
disqus:
shortname: mhack
google_analytics:
id: UA-6981296-7
github:
ribbon: false
copyright: '© 2013 Marcos Hack. All rights reserved.'
diff --git a/_plugins/ext.rb b/_plugins/ext.rb
deleted file mode 100644
index b9c6c96..0000000
--- a/_plugins/ext.rb
+++ /dev/null
@@ -1 +0,0 @@
-require "jekyll-assets"
diff --git a/_plugins/generate_sitemap.rb b/_plugins/generate_sitemap.rb
deleted file mode 100644
index bb683b8..0000000
--- a/_plugins/generate_sitemap.rb
+++ /dev/null
@@ -1,154 +0,0 @@
-# Jekyll sitemap page generator.
-# http://recursive-design.com/projects/jekyll-plugins/
-#
-# Version: 0.2.4 (201210160037)
-#
-# Copyright (c) 2010 Dave Perrett, http://recursive-design.com/
-# Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
-#
-# A generator that creates a sitemap.xml page for jekyll sites, suitable for submission to
-# google etc.
-#
-# To use it, simply drop this script into the _plugins directory of your Jekyll site.
-#
-# When you compile your jekyll site, this plugin will loop through the list of pages in your
-# site, and generate an entry in sitemap.xml for each one.
-
-require 'pathname'
-
-module Jekyll
-
-
- # Monkey-patch an accessor for a page's containing folder, since
- # we need it to generate the sitemap.
- class Page
- def subfolder
- @dir
- end
- end
-
-
- # Sub-class Jekyll::StaticFile to allow recovery from unimportant exception
- # when writing the sitemap file.
- class StaticSitemapFile < StaticFile
- def write(dest)
- super(dest) rescue ArgumentError
- true
- end
- end
-
-
- # Generates a sitemap.xml file containing URLs of all pages and posts.
- class SitemapGenerator < Generator
- safe true
- priority :low
-
- # Generates the sitemap.xml file.
- #
- # +site+ is the global Site object.
- def generate(site)
- # Create the destination folder if necessary.
- site_folder = site.config['destination']
- unless File.directory?(site_folder)
- p = Pathname.new(site_folder)
- p.mkdir
- end
-
- # Write the contents of sitemap.xml.
- File.open(File.join(site_folder, 'sitemap.xml'), 'w') do |f|
- f.write(generate_header())
- f.write(generate_content(site))
- f.write(generate_footer())
- f.close
- end
-
- # Add a static file entry for the zip file, otherwise Site::cleanup will remove it.
- site.static_files << Jekyll::StaticSitemapFile.new(site, site.dest, '/', 'sitemap.xml')
- end
-
- private
-
- # Returns the XML header.
- def generate_header
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"
- end
-
- # Returns a string containing the the XML entries.
- #
- # +site+ is the global Site object.
- def generate_content(site)
- result = ''
-
- # First, try to find any stand-alone pages.
- site.pages.each { |page|
- path = page.subfolder + '/' + page.name
-
- # Skip files that don't exist yet (e.g. paginator pages)
- next unless FileTest.exist?(path)
-
- mod_date = File.mtime(site.source + path)
-
- # Use the user-specified permalink if one is given.
- if page.permalink
- path = page.permalink
- else
- # Be smart about the output filename.
- path.gsub!(/.md$/, '.html')
- end
-
- # Ignore SASS, SCSS, and CSS files
- next if path =~ /.(sass|scss|css)$/
-
- # Remove the trailing 'index.html' if there is one, and just output the folder name.
- path = path[0..-11] if path =~ /\/index.html$/
-
- result += entry(path, mod_date, get_attrs(page), site) unless path =~ /error/
- }
-
- # Next, find all the posts.
- posts = site.site_payload['site']['posts']
- for post in posts do
- url = post.url
- url = '/' + url unless url =~ /^\//
- url = url[0..-11] if url=~/\/index.html$/
- result += entry(url, post.date, get_attrs(post), site)
- end
-
- result
- end
-
- def get_attrs( page )
- attrs = Hash.new
- attrs[:changefreq] = page.data['changefreq'] if page.data.has_key?('changefreq')
- attrs[:priority] = page.data['priority'] if page.data.has_key?('priority')
- attrs
- end
-
- # Returns the XML footer.
- def generate_footer
- "\n</urlset>"
- end
-
- # Creates an XML entry from the given path and date.
- #
- # +path+ is the URL path to the page.
- # +date+ is the date the file was modified (in the case of regular pages), or published (for blog posts).
- # +changefreq+ is the frequency with which the page is expected to change (this information is used by
- # e.g. the Googlebot). This may be specified in the page's YAML front matter. If it is not set, nothing
- # is output for this property.
- def entry(path, date, attrs, site)
- # Remove the trailing slash from the baseurl if it is present, for consistency.
- baseurl = site.config['baseurl']
- baseurl = baseurl[0..-2] if baseurl=~/\/$/
-
- "
- <url>
- <loc>#{baseurl}#{path}</loc>
- <lastmod>#{date.strftime("%Y-%m-%d")}</lastmod>
-" + attrs.map { |k,v| " <#{k}>#{v}</#{k}>" }.join("\n") + "
- </url>"
- end
-
- end
-
-end
|
marcoshack/marcoshack.github.io
|
18beda7f6f2ef4239dbc9ab22e6d7c6c9ff9b115
|
rename *.md files to *.markdown
|
diff --git a/_config.yml b/_config.yml
index c9bd8d8..a8a576b 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,33 +1,42 @@
permalink: /:year/:month/:title.html
exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md, README_POSTS.md ]
future: false
lsi: true # Produces an index for related posts.
paginate: 10
plugins: ./_plugins
# assets:
# js_compressor: uglifier
# css_compressor: sass
+defaults:
+ -
+ scope:
+ path: _posts
+ type: posts
+ values:
+ layout: post
+ author: Marcos Hack
+
brand: mhack
author:
name: Marcos Hack
email: [email protected]
twitter: marcoshack
github: marcoshack
linkedin: marcoshack
google_plus: 101876381204467415756
title_sufix: '- Marcos Hack'
disqus:
shortname: mhack
google_analytics:
id: UA-6981296-7
github:
ribbon: false
copyright: '© 2013 Marcos Hack. All rights reserved.'
diff --git a/contato.md b/contato.markdown
similarity index 96%
rename from contato.md
rename to contato.markdown
index 0aed9ee..a9f5577 100644
--- a/contato.md
+++ b/contato.markdown
@@ -1,15 +1,15 @@
----
+---
layout: default
title: Contato
date: 2009-12-10 15:00:29 -0300
updated: 2013-07-25 22:53:00 -0300
---
# Contato
**E-mail, GTalk:** [email protected]
**Twitter:** [@marcoshack](http://twitter.com/marcoshack)
**Github:** [github.com/marcoshack](http://github.com/marcoshack)
**LinkedIn:** [br.linkedin.com/in/marcoshack](http://br.linkedin.com/in/marcoshack/)
|
marcoshack/marcoshack.github.io
|
b10d6c7045064f2c82e8b5ac5f5a4c9094f27ca9
|
remove jekyll-assets plugin because github gh-pages doesn't support it
|
diff --git a/_config.yml b/_config.yml
index 1260f75..c9bd8d8 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,34 +1,33 @@
permalink: /:year/:month/:title.html
exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md, README_POSTS.md ]
future: false
lsi: true # Produces an index for related posts.
paginate: 10
plugins: ./_plugins
-gems: [jekyll-assets]
-assets:
- js_compressor: uglifier
- css_compressor: sass
+# assets:
+# js_compressor: uglifier
+# css_compressor: sass
brand: mhack
author:
name: Marcos Hack
email: [email protected]
twitter: marcoshack
github: marcoshack
linkedin: marcoshack
google_plus: 101876381204467415756
title_sufix: '- Marcos Hack'
disqus:
shortname: mhack
google_analytics:
id: UA-6981296-7
github:
ribbon: false
copyright: '© 2013 Marcos Hack. All rights reserved.'
diff --git a/_layouts/default.html b/_layouts/default.html
index 3e18138..5b60b4c 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,30 +1,36 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ page.title }} {{ site.title_sufix }}</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- {% stylesheet application %}
+ <link rel="stylesheet" href="/assets/stylesheets/vendor/bootstrap.css">
+ <link rel="stylesheet" href="/assets/stylesheets/vendor/bootstrap-docs.css">
+ <link rel="stylesheet" href="/assets/stylesheets/vendor/prettify.css">
+ <link rel="stylesheet" href="/assets/stylesheets/application.css">
- <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
+ <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
+
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
-
+
<div class="container">
{{ content }}
</div>
{% include footer.html %}
- {% javascript application %}
+
+ <script src="/assets/javascripts/vendor/jquery.js"></script>
+ <script src="/assets/javascripts/vendor/bootstrap.js"></script>
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/_assets/images/glyphicons-halflings-white.png b/assets/images/glyphicons-halflings-white.png
similarity index 100%
rename from _assets/images/glyphicons-halflings-white.png
rename to assets/images/glyphicons-halflings-white.png
diff --git a/_assets/images/glyphicons-halflings.png b/assets/images/glyphicons-halflings.png
similarity index 100%
rename from _assets/images/glyphicons-halflings.png
rename to assets/images/glyphicons-halflings.png
diff --git a/_assets/javascripts/application.js b/assets/javascripts/application.js
similarity index 100%
rename from _assets/javascripts/application.js
rename to assets/javascripts/application.js
diff --git a/_assets/javascripts/vendor/bootstrap.js b/assets/javascripts/vendor/bootstrap.js
similarity index 100%
rename from _assets/javascripts/vendor/bootstrap.js
rename to assets/javascripts/vendor/bootstrap.js
diff --git a/_assets/javascripts/vendor/jquery.js b/assets/javascripts/vendor/jquery.js
similarity index 100%
rename from _assets/javascripts/vendor/jquery.js
rename to assets/javascripts/vendor/jquery.js
diff --git a/_assets/stylesheets/application.css b/assets/stylesheets/application.css
similarity index 100%
rename from _assets/stylesheets/application.css
rename to assets/stylesheets/application.css
diff --git a/_assets/stylesheets/vendor/bootstrap-docs.css b/assets/stylesheets/vendor/bootstrap-docs.css
similarity index 100%
rename from _assets/stylesheets/vendor/bootstrap-docs.css
rename to assets/stylesheets/vendor/bootstrap-docs.css
diff --git a/_assets/stylesheets/vendor/bootstrap.css b/assets/stylesheets/vendor/bootstrap.css
similarity index 100%
rename from _assets/stylesheets/vendor/bootstrap.css
rename to assets/stylesheets/vendor/bootstrap.css
diff --git a/_assets/stylesheets/vendor/prettify.css b/assets/stylesheets/vendor/prettify.css
similarity index 100%
rename from _assets/stylesheets/vendor/prettify.css
rename to assets/stylesheets/vendor/prettify.css
|
marcoshack/marcoshack.github.io
|
a97c14890bf67eb356dd7341a78ff58b5b5e51d4
|
Add jekyll-assets to gems in _config.yml
|
diff --git a/_config.yml b/_config.yml
index 83231c9..1260f75 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,33 +1,34 @@
permalink: /:year/:month/:title.html
exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md, README_POSTS.md ]
future: false
lsi: true # Produces an index for related posts.
paginate: 10
plugins: ./_plugins
+gems: [jekyll-assets]
assets:
js_compressor: uglifier
css_compressor: sass
brand: mhack
author:
name: Marcos Hack
email: [email protected]
twitter: marcoshack
github: marcoshack
linkedin: marcoshack
google_plus: 101876381204467415756
title_sufix: '- Marcos Hack'
disqus:
shortname: mhack
google_analytics:
id: UA-6981296-7
github:
ribbon: false
copyright: '© 2013 Marcos Hack. All rights reserved.'
|
marcoshack/marcoshack.github.io
|
85634e48fd12483859c968082d2c72d1de9007de
|
Replace old gems by github-pages
|
diff --git a/.ruby-version b/.ruby-version
deleted file mode 100644
index 8e17352..0000000
--- a/.ruby-version
+++ /dev/null
@@ -1 +0,0 @@
-ruby-1.9.3-p448
diff --git a/Gemfile b/Gemfile
index 5587817..202d61a 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,15 +1,4 @@
source "https://rubygems.org"
-gem "jekyll"
-gem "rake"
-gem "nokogiri"
-gem "jekyll-assets"
-gem "uglifier"
-gem "sass"
-
-# gsl needs native libraries:
-#
-# $ brew tap homebrew/versions
-# $ brew install gsl114
-#
-gem "gsl"
+gem 'github-pages'
+gem 'jekyll-assets'
diff --git a/Gemfile.lock b/Gemfile.lock
index a7083a6..eeaebd4 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,71 +1,138 @@
GEM
remote: https://rubygems.org/
specs:
- classifier (1.3.3)
- fast-stemmer (>= 1.0.0)
+ RedCloth (4.2.9)
+ activesupport (4.1.6)
+ i18n (~> 0.6, >= 0.6.9)
+ json (~> 1.7, >= 1.7.7)
+ minitest (~> 5.1)
+ thread_safe (~> 0.1)
+ tzinfo (~> 1.1)
+ blankslate (2.1.2.4)
+ celluloid (0.16.0)
+ timers (~> 4.0.0)
+ classifier-reborn (2.0.1)
+ fast-stemmer (~> 1.0)
+ coffee-script (2.3.0)
+ coffee-script-source
+ execjs
+ coffee-script-source (1.8.0)
colorator (0.1)
- commander (4.1.4)
- highline (~> 1.6.11)
- directory_watcher (1.4.1)
- execjs (1.4.0)
- multi_json (~> 1.0)
+ execjs (2.2.1)
fast-stemmer (1.0.2)
- gsl (1.15.3)
- narray (>= 0.5.9)
- highline (1.6.19)
+ ffi (1.9.5)
+ gemoji (2.1.0)
+ github-pages (28)
+ RedCloth (= 4.2.9)
+ jekyll (= 2.4.0)
+ jekyll-coffeescript (= 1.0.0)
+ jekyll-mentions (= 0.1.3)
+ jekyll-redirect-from (= 0.6.2)
+ jekyll-sass-converter (= 1.2.0)
+ jekyll-sitemap (= 0.6.0)
+ jemoji (= 0.3.0)
+ kramdown (= 1.3.1)
+ liquid (= 2.6.1)
+ maruku (= 0.7.0)
+ pygments.rb (= 0.6.0)
+ rdiscount (= 2.1.7)
+ redcarpet (= 3.1.2)
hike (1.2.3)
- jekyll (1.1.2)
- classifier (~> 1.3)
+ hitimes (1.2.2)
+ html-pipeline (1.9.0)
+ activesupport (>= 2)
+ nokogiri (~> 1.4)
+ i18n (0.6.11)
+ jekyll (2.4.0)
+ classifier-reborn (~> 2.0)
colorator (~> 0.1)
- commander (~> 4.1.3)
- directory_watcher (~> 1.4.1)
- kramdown (~> 1.0.2)
- liquid (~> 2.5.1)
- maruku (~> 0.5)
- pygments.rb (~> 0.5.0)
- redcarpet (~> 2.2.2)
- safe_yaml (~> 0.7.0)
- jekyll-assets (0.6.1)
- jekyll (~> 1.0)
+ jekyll-coffeescript (~> 1.0)
+ jekyll-gist (~> 1.0)
+ jekyll-paginate (~> 1.0)
+ jekyll-sass-converter (~> 1.0)
+ jekyll-watch (~> 1.1)
+ kramdown (~> 1.3)
+ liquid (~> 2.6.1)
+ mercenary (~> 0.3.3)
+ pygments.rb (~> 0.6.0)
+ redcarpet (~> 3.1)
+ safe_yaml (~> 1.0)
+ toml (~> 0.1.0)
+ jekyll-assets (0.10.0)
+ jekyll (~> 2.0)
+ sass (~> 3.2)
sprockets (~> 2.10)
- kramdown (1.0.2)
- liquid (2.5.1)
- maruku (0.6.1)
- syntax (>= 1.0.0)
- mini_portile (0.5.1)
- multi_json (1.7.7)
- narray (0.6.0.8)
- nokogiri (1.6.0)
- mini_portile (~> 0.5.0)
- posix-spawn (0.3.6)
- pygments.rb (0.5.2)
+ sprockets-helpers
+ sprockets-sass
+ jekyll-coffeescript (1.0.0)
+ coffee-script (~> 2.2)
+ jekyll-gist (1.1.0)
+ jekyll-mentions (0.1.3)
+ html-pipeline (~> 1.9.0)
+ jekyll (~> 2.0)
+ jekyll-paginate (1.0.0)
+ jekyll-redirect-from (0.6.2)
+ jekyll (~> 2.0)
+ jekyll-sass-converter (1.2.0)
+ sass (~> 3.2)
+ jekyll-sitemap (0.6.0)
+ jekyll-watch (1.1.1)
+ listen (~> 2.7)
+ jemoji (0.3.0)
+ gemoji (~> 2.0)
+ html-pipeline (~> 1.9)
+ jekyll (~> 2.0)
+ json (1.8.1)
+ kramdown (1.3.1)
+ liquid (2.6.1)
+ listen (2.7.11)
+ celluloid (>= 0.15.2)
+ rb-fsevent (>= 0.9.3)
+ rb-inotify (>= 0.9)
+ maruku (0.7.0)
+ mercenary (0.3.4)
+ mini_portile (0.6.0)
+ minitest (5.4.2)
+ multi_json (1.10.1)
+ nokogiri (1.6.3.1)
+ mini_portile (= 0.6.0)
+ parslet (1.5.0)
+ blankslate (~> 2.0)
+ posix-spawn (0.3.9)
+ pygments.rb (0.6.0)
posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.1.0)
rack (1.5.2)
- rake (10.1.0)
- redcarpet (2.2.2)
- safe_yaml (0.7.1)
- sass (3.2.10)
- sprockets (2.10.0)
+ rb-fsevent (0.9.4)
+ rb-inotify (0.9.5)
+ ffi (>= 0.5.0)
+ rdiscount (2.1.7)
+ redcarpet (3.1.2)
+ safe_yaml (1.0.4)
+ sass (3.4.5)
+ sprockets (2.12.2)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
- syntax (1.0.0)
+ sprockets-helpers (1.1.0)
+ sprockets (~> 2.0)
+ sprockets-sass (1.2.0)
+ sprockets (~> 2.0)
+ tilt (~> 1.1)
+ thread_safe (0.3.4)
tilt (1.4.1)
- uglifier (2.1.2)
- execjs (>= 0.3.0)
- multi_json (~> 1.0, >= 1.0.2)
+ timers (4.0.1)
+ hitimes
+ toml (0.1.1)
+ parslet (~> 1.5.0)
+ tzinfo (1.2.2)
+ thread_safe (~> 0.1)
yajl-ruby (1.1.0)
PLATFORMS
ruby
DEPENDENCIES
- gsl
- jekyll
+ github-pages
jekyll-assets
- nokogiri
- rake
- sass
- uglifier
|
marcoshack/marcoshack.github.io
|
ff5492435e6a41f975475490184618c328ff40eb
|
substituicao do widget do twitter pelo rebelmouse
|
diff --git a/_includes/rebelmouse.html b/_includes/rebelmouse.html
new file mode 100644
index 0000000..6a4b9b9
--- /dev/null
+++ b/_includes/rebelmouse.html
@@ -0,0 +1 @@
+<script type="text/javascript" class="rebelmouse-embed-script" src="https://www.rebelmouse.com/static/js-build/embed/embed.js?site=mhack&height=1700&flexible=0&scrollbar_theme=dark&show_rebelnav=1"></script>
\ No newline at end of file
diff --git a/index.html b/index.html
index 6a7dd0f..5739f27 100644
--- a/index.html
+++ b/index.html
@@ -1,32 +1,33 @@
---
layout: default
title: Home
change_frequency: always
---
<div class="row">
<div class="span8">
{% for post in paginator.posts %}
<div class="row">
<div class="span2 hidden-phone">
{% if post.image != nil %}
<img src="/images/{{ post.image }}" />
{% endif %}
</div>
<div class="span6">
<h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
<div class="post_excerpt">
<blockquote>
<p>{{ post.content | strip_html | truncatewords: 30 }}</p>
<!-- <p>{{ post.excerpt }}</p> -->
<small class="muted">{% include post_date.html %}</small>
</blockquote>
</div>
</div>
</div>
{% endfor %}
{% include pagination.html %}
</div>
<div class="span4 hidden-phone">
- {% include twitter_widget.html %}
+ <!-- {% include twitter_widget.html %} -->
+ {% include rebelmouse.html %}
</div>
</div>
|
marcoshack/marcoshack.github.io
|
205595a61455c9d7376f723d7cf90d905b30b710
|
atualizar vhost durante rake deploy
|
diff --git a/_deploy/apache-vhost.conf b/_deploy/apache-vhost.conf
index bc16b4c..83871f7 100644
--- a/_deploy/apache-vhost.conf
+++ b/_deploy/apache-vhost.conf
@@ -1,18 +1,18 @@
<VirtualHost *:80>
ServerName mhack.com
ServerAlias mhack.com.br
ServerAlias marcoshack.com
ServerAlias marcoshack.com.br
ServerAlias www.mhack.com
ServerAlias www.mhack.com.br
ServerAlias www.marcoshack.com
ServerAlias www.marcoshack.com.br
DocumentRoot /home/mhack/www/mhack
<Directory /home/mhack/www/mhack>
Options All
AllowOverride All
Require all granted
</Directory>
-</VirtualHost>
\ No newline at end of file
+</VirtualHost>
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index 7b0ef03..b20257c 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,39 +1,44 @@
#!/usr/bin/env bash
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
TIMEZONE=America/Sao_Paulo
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
+VHOST_CONF=$HOME/etc/httpd/mhack.conf
function log_step {
echo -e "\e[1;33m--> ${1}\e[00m"
}
log_step "Setting up local workspace"
if [[ -d $TMP_GIT_CLONE ]]; then rm -Rf $TMP_GIT_CLONE; fi
git clone $GIT_REPO $TMP_GIT_CLONE
log_step "Updating dependencies"
cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
log_step "Updating site"
TZ=$TIMEZONE $JEKYLL_CMD build -s $TMP_GIT_CLONE -d $PUBLIC_WWW
+log_step "Updating vhost config"
+cp $TMP_GIT_CLONE/_deploy/apache-vhost.conf $VHOST_CONF
+sudo service httpd reload
+
log_step "Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
marcoshack/marcoshack.github.io
|
c794b97ee9079d0afc233ed5c0dcf9065b6d0141
|
setup do jekyll-assets
|
diff --git a/Gemfile b/Gemfile
index 25dc308..5587817 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,12 +1,15 @@
source "https://rubygems.org"
-gem 'jekyll'
-gem 'rake'
-gem 'nokogiri'
+gem "jekyll"
+gem "rake"
+gem "nokogiri"
+gem "jekyll-assets"
+gem "uglifier"
+gem "sass"
# gsl needs native libraries:
#
# $ brew tap homebrew/versions
# $ brew install gsl114
#
-gem 'gsl'
+gem "gsl"
diff --git a/Gemfile.lock b/Gemfile.lock
index f3e46ef..a7083a6 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,50 +1,71 @@
GEM
remote: https://rubygems.org/
specs:
classifier (1.3.3)
fast-stemmer (>= 1.0.0)
colorator (0.1)
commander (4.1.4)
highline (~> 1.6.11)
directory_watcher (1.4.1)
+ execjs (1.4.0)
+ multi_json (~> 1.0)
fast-stemmer (1.0.2)
gsl (1.15.3)
narray (>= 0.5.9)
highline (1.6.19)
+ hike (1.2.3)
jekyll (1.1.2)
classifier (~> 1.3)
colorator (~> 0.1)
commander (~> 4.1.3)
directory_watcher (~> 1.4.1)
kramdown (~> 1.0.2)
liquid (~> 2.5.1)
maruku (~> 0.5)
pygments.rb (~> 0.5.0)
redcarpet (~> 2.2.2)
safe_yaml (~> 0.7.0)
+ jekyll-assets (0.6.1)
+ jekyll (~> 1.0)
+ sprockets (~> 2.10)
kramdown (1.0.2)
liquid (2.5.1)
maruku (0.6.1)
syntax (>= 1.0.0)
mini_portile (0.5.1)
+ multi_json (1.7.7)
narray (0.6.0.8)
nokogiri (1.6.0)
mini_portile (~> 0.5.0)
posix-spawn (0.3.6)
pygments.rb (0.5.2)
posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.1.0)
+ rack (1.5.2)
rake (10.1.0)
redcarpet (2.2.2)
safe_yaml (0.7.1)
+ sass (3.2.10)
+ sprockets (2.10.0)
+ hike (~> 1.2)
+ multi_json (~> 1.0)
+ rack (~> 1.0)
+ tilt (~> 1.1, != 1.3.0)
syntax (1.0.0)
+ tilt (1.4.1)
+ uglifier (2.1.2)
+ execjs (>= 0.3.0)
+ multi_json (~> 1.0, >= 1.0.2)
yajl-ruby (1.1.0)
PLATFORMS
ruby
DEPENDENCIES
gsl
jekyll
+ jekyll-assets
nokogiri
rake
+ sass
+ uglifier
diff --git a/assets/img/glyphicons-halflings-white.png b/_assets/images/glyphicons-halflings-white.png
similarity index 100%
rename from assets/img/glyphicons-halflings-white.png
rename to _assets/images/glyphicons-halflings-white.png
diff --git a/assets/img/glyphicons-halflings.png b/_assets/images/glyphicons-halflings.png
similarity index 100%
rename from assets/img/glyphicons-halflings.png
rename to _assets/images/glyphicons-halflings.png
diff --git a/_assets/javascripts/application.js b/_assets/javascripts/application.js
new file mode 100644
index 0000000..afb024a
--- /dev/null
+++ b/_assets/javascripts/application.js
@@ -0,0 +1,2 @@
+//= require vendor/jquery.js
+//= require vendor/bootstrap.js
diff --git a/assets/js/bootstrap-2.2.2.js b/_assets/javascripts/vendor/bootstrap.js
similarity index 100%
rename from assets/js/bootstrap-2.2.2.js
rename to _assets/javascripts/vendor/bootstrap.js
diff --git a/assets/js/jquery-1.9.0.js b/_assets/javascripts/vendor/jquery.js
similarity index 100%
rename from assets/js/jquery-1.9.0.js
rename to _assets/javascripts/vendor/jquery.js
diff --git a/assets/css/style.css b/_assets/stylesheets/application.css
similarity index 93%
rename from assets/css/style.css
rename to _assets/stylesheets/application.css
index 2d4d421..4d3049d 100644
--- a/assets/css/style.css
+++ b/_assets/stylesheets/application.css
@@ -1,36 +1,38 @@
+/*= require vendor/bootstrap.css */
+
body { padding-top: 50px; }
@media screen and (max-width: 768px) {
body { padding-top: 0px; }
}
.footer {
text-align: center;
padding: 30px 0;
margin-top: 70px;
border-top: 1px solid #e5e5e5;
background-color: #f5f5f5;
}
.footer p {
margin-bottom: 0;
color: #777;
}
.footer-links {
margin: 10px 0;
}
.footer-links li {
display: inline;
padding: 0 2px;
}
.footer-links li:first-child {
padding-left: 0;
}
.post-info {
margin: 10px 0;
}
.post-info li {
font-size: 85%;
color: #999999;
display: inline;
padding: 0 2px;
}
\ No newline at end of file
diff --git a/assets/css/docs.css b/_assets/stylesheets/vendor/bootstrap-docs.css
similarity index 100%
rename from assets/css/docs.css
rename to _assets/stylesheets/vendor/bootstrap-docs.css
diff --git a/assets/css/bootstrap-2.2.2.css b/_assets/stylesheets/vendor/bootstrap.css
similarity index 100%
rename from assets/css/bootstrap-2.2.2.css
rename to _assets/stylesheets/vendor/bootstrap.css
diff --git a/assets/css/prettify.css b/_assets/stylesheets/vendor/prettify.css
similarity index 100%
rename from assets/css/prettify.css
rename to _assets/stylesheets/vendor/prettify.css
diff --git a/_config.yml b/_config.yml
index 2c9cda3..83231c9 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,29 +1,33 @@
permalink: /:year/:month/:title.html
exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md, README_POSTS.md ]
future: false
lsi: true # Produces an index for related posts.
paginate: 10
plugins: ./_plugins
+assets:
+ js_compressor: uglifier
+ css_compressor: sass
+
brand: mhack
author:
name: Marcos Hack
email: [email protected]
twitter: marcoshack
github: marcoshack
linkedin: marcoshack
google_plus: 101876381204467415756
title_sufix: '- Marcos Hack'
disqus:
shortname: mhack
google_analytics:
id: UA-6981296-7
github:
ribbon: false
copyright: '© 2013 Marcos Hack. All rights reserved.'
diff --git a/_layouts/default.html b/_layouts/default.html
index 7da1df0..3e18138 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,33 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ page.title }} {{ site.title_sufix }}</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link href="/assets/css/bootstrap-2.2.2.css" rel="stylesheet">
- <link href="/assets/css/style.css?v={{ site.time | date: "%Y%m%d%H%M%S" }}" rel="stylesheet">
+ {% stylesheet application %}
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
<div class="container">
{{ content }}
</div>
{% include footer.html %}
-
- <script src="/assets/js/jquery-1.9.0.js"></script>
- <script src="/assets/js/bootstrap-2.2.2.js"></script>
+ {% javascript application %}
</body>
</html>
\ No newline at end of file
diff --git a/_plugins/ext.rb b/_plugins/ext.rb
new file mode 100644
index 0000000..b9c6c96
--- /dev/null
+++ b/_plugins/ext.rb
@@ -0,0 +1 @@
+require "jekyll-assets"
diff --git a/contato.md b/contato.md
index 1cf618a..0aed9ee 100644
--- a/contato.md
+++ b/contato.md
@@ -1,13 +1,15 @@
---
layout: default
title: Contato
-date: 2009-12-10 18:00:29 UTC
-updated: 2009-12-10 18:00:29 UTC
+date: 2009-12-10 15:00:29 -0300
+updated: 2013-07-25 22:53:00 -0300
---
# Contato
**E-mail, GTalk:** [email protected]
**Twitter:** [@marcoshack](http://twitter.com/marcoshack)
-**Github:** [github.com/marcoshack](http://github.com/marcoshack)
\ No newline at end of file
+**Github:** [github.com/marcoshack](http://github.com/marcoshack)
+
+**LinkedIn:** [br.linkedin.com/in/marcoshack](http://br.linkedin.com/in/marcoshack/)
|
marcoshack/marcoshack.github.io
|
fecb7b527ff8a393dec1278634a6d7f2983bf4e7
|
draft do post sobre gatling
|
diff --git a/_drafts/gatling.md b/_drafts/gatling.md
new file mode 100644
index 0000000..c82280e
--- /dev/null
+++ b/_drafts/gatling.md
@@ -0,0 +1,16 @@
+---
+layout: post
+title: "JMeter, Gatling, e a mudança de cultura na área de testes"
+description: "Gatling é um ferramenta assÃncrona de testes de carga que utiliza uma DSL em Scala para criação de cenários."
+image: gatling-logo-with-no-gun.png
+categories: [ programação, performance ]
+tags: [ gatling, jmeter, performance, stress-test, load-test ]
+---
+
+Desde que o mundo é mundo quando pensamos em teste de carga pensamos em [JMeter](http://jmeter.apache.org/). Existem outras ferramentas conhecidas, como o também open-source [ab](http://httpd.apache.org/docs/2.2/programs/ab.html), além de outras tantas ferramentas comerciais. Mas via de regra o JMeter costuma ser a primeira opção. No geral o JMeter é uma ferramenta bem descente, madura, com uma GUI fácil de usar, suporte a muitos protocolos e centenas de plugins pra facilitar a vida.
+
+Mas nem tudo são flores, e duas caracterÃsticas dessa ferramenta sempre incomodaram bastante: sua natureza sÃncrona, com o conceito de uma thread por usuário virtual, e a pouco amigável representação XML dos cenários de teste.
+
+A representação em XML para a maioria nunca foi um problema tão grande, até porque em muitas empresas a criação dos cenários e execução dos testes são responsabilidades de um time de QA, que historicamente são formados por profissionais de TI especializados porém geralmente não programadores. Porém esse perfil vem mudando nos últimos anos, principalmente devido a necessidade de automação de testes. Além disso, a tão falada cultura [DevOps](http://en.wikipedia.org/wiki/DevOps) vem aproximando não só as áreas de desenvolvimento e operações, mas também a equipes de qualidade, pois descobrimos que tão ruim quanto jogar um pacote de software para o outro lado do muro para ser instalado e configurado,
+
+Com a aproximação ...
diff --git a/images/gatling-logo-machine-gun.png b/images/gatling-logo-machine-gun.png
new file mode 100644
index 0000000..fcb1714
Binary files /dev/null and b/images/gatling-logo-machine-gun.png differ
diff --git a/images/gatling-logo-with-no-gun.png b/images/gatling-logo-with-no-gun.png
new file mode 100644
index 0000000..5cc2a96
Binary files /dev/null and b/images/gatling-logo-with-no-gun.png differ
|
marcoshack/marcoshack.github.io
|
b9956089e1cdb7b136b3ba210d9b713c99e1fde9
|
versionamento dos assetes do twitter-bootstrap
|
diff --git a/_layouts/default.html b/_layouts/default.html
index bb3ced2..7da1df0 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,31 +1,33 @@
<!DOCTYPE html>
<html lang="en">
<head>
+ <title>{{ page.title }} {{ site.title_sufix }}</title>
+
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
- <title>{{ page.title }} {{ site.title_sufix }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link href="/assets/css/bootstrap.css" rel="stylesheet">
+
+ <link href="/assets/css/bootstrap-2.2.2.css" rel="stylesheet">
<link href="/assets/css/style.css?v={{ site.time | date: "%Y%m%d%H%M%S" }}" rel="stylesheet">
+
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
-
<div class="container">
{{ content }}
</div>
{% include footer.html %}
<script src="/assets/js/jquery-1.9.0.js"></script>
- <script src="/assets/js/bootstrap.js"></script>
+ <script src="/assets/js/bootstrap-2.2.2.js"></script>
</body>
</html>
\ No newline at end of file
diff --git a/assets/css/bootstrap.css b/assets/css/bootstrap-2.2.2.css
similarity index 100%
rename from assets/css/bootstrap.css
rename to assets/css/bootstrap-2.2.2.css
diff --git a/assets/css/custom.css b/assets/css/custom.css
deleted file mode 100644
index a30cafe..0000000
--- a/assets/css/custom.css
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Footer
--------------------------------------------------- */
-
-.footer {
- text-align: center;
- padding: 30px 0;
- margin-top: 70px;
- border-top: 1px solid #e5e5e5;
- background-color: #f5f5f5;
-}
-.footer p {
- margin-bottom: 0;
- color: #777;
-}
-.footer-links {
- margin: 10px 0;
-}
-.footer-links li {
- display: inline;
- padding: 0 2px;
-}
-.footer-links li:first-child {
- padding-left: 0;
-}
diff --git a/assets/js/bootstrap.js b/assets/js/bootstrap-2.2.2.js
similarity index 100%
rename from assets/js/bootstrap.js
rename to assets/js/bootstrap-2.2.2.js
|
marcoshack/marcoshack.github.io
|
6112f2a5fa2d825834a4e81516d9f88f68253e1d
|
[deploy] remover diretorio temporario antes de clonar o repositorio
|
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index a8443d0..7b0ef03 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,38 +1,39 @@
#!/usr/bin/env bash
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
TIMEZONE=America/Sao_Paulo
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
function log_step {
echo -e "\e[1;33m--> ${1}\e[00m"
}
log_step "Setting up local workspace"
+if [[ -d $TMP_GIT_CLONE ]]; then rm -Rf $TMP_GIT_CLONE; fi
git clone $GIT_REPO $TMP_GIT_CLONE
log_step "Updating dependencies"
cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
log_step "Updating site"
TZ=$TIMEZONE $JEKYLL_CMD build -s $TMP_GIT_CLONE -d $PUBLIC_WWW
log_step "Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
marcoshack/marcoshack.github.io
|
824396375c6f3b8e8504f42cb266fe921b50bab1
|
versionamento do style.css
|
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index ef59f0e..a8443d0 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,38 +1,38 @@
#!/usr/bin/env bash
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
TIMEZONE=America/Sao_Paulo
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
function log_step {
echo -e "\e[1;33m--> ${1}\e[00m"
}
log_step "Setting up local workspace"
git clone $GIT_REPO $TMP_GIT_CLONE
log_step "Updating dependencies"
cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
log_step "Updating site"
-TZ=$TIMEZONE $JEKYLL_CMD $TMP_GIT_CLONE $PUBLIC_WWW
+TZ=$TIMEZONE $JEKYLL_CMD build -s $TMP_GIT_CLONE -d $PUBLIC_WWW
log_step "Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
diff --git a/_layouts/default.html b/_layouts/default.html
index 9a56509..bb3ced2 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,31 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
<title>{{ page.title }} {{ site.title_sufix }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/assets/css/bootstrap.css" rel="stylesheet">
- <link href="/assets/css/style.css" rel="stylesheet">
+ <link href="/assets/css/style.css?v={{ site.time | date: "%Y%m%d%H%M%S" }}" rel="stylesheet">
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
<div class="container">
{{ content }}
</div>
{% include footer.html %}
<script src="/assets/js/jquery-1.9.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
</body>
</html>
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
19ea5fa66b7ca20d42627164505f3ab8d2da0fc3
|
posts relacionados e semantica nos posts
|
diff --git a/.ruby-version b/.ruby-version
new file mode 100644
index 0000000..8e17352
--- /dev/null
+++ b/.ruby-version
@@ -0,0 +1 @@
+ruby-1.9.3-p448
diff --git a/Gemfile b/Gemfile
index 52f214e..25dc308 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,12 +1,12 @@
source "https://rubygems.org"
gem 'jekyll'
gem 'rake'
gem 'nokogiri'
# gsl needs native libraries:
#
# $ brew tap homebrew/versions
# $ brew install gsl114
#
-gem 'gsl'
\ No newline at end of file
+gem 'gsl'
diff --git a/Gemfile.lock b/Gemfile.lock
index 38a9cd8..f3e46ef 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,48 +1,50 @@
GEM
remote: https://rubygems.org/
specs:
classifier (1.3.3)
fast-stemmer (>= 1.0.0)
colorator (0.1)
- commander (4.1.3)
+ commander (4.1.4)
highline (~> 1.6.11)
directory_watcher (1.4.1)
fast-stemmer (1.0.2)
gsl (1.15.3)
narray (>= 0.5.9)
highline (1.6.19)
- jekyll (1.0.3)
+ jekyll (1.1.2)
classifier (~> 1.3)
colorator (~> 0.1)
commander (~> 4.1.3)
directory_watcher (~> 1.4.1)
kramdown (~> 1.0.2)
- liquid (~> 2.3)
+ liquid (~> 2.5.1)
maruku (~> 0.5)
pygments.rb (~> 0.5.0)
+ redcarpet (~> 2.2.2)
safe_yaml (~> 0.7.0)
kramdown (1.0.2)
- liquid (2.5.0)
+ liquid (2.5.1)
maruku (0.6.1)
syntax (>= 1.0.0)
- mini_portile (0.5.0)
+ mini_portile (0.5.1)
narray (0.6.0.8)
nokogiri (1.6.0)
mini_portile (~> 0.5.0)
posix-spawn (0.3.6)
- pygments.rb (0.5.1)
+ pygments.rb (0.5.2)
posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.1.0)
rake (10.1.0)
+ redcarpet (2.2.2)
safe_yaml (0.7.1)
syntax (1.0.0)
yajl-ruby (1.1.0)
PLATFORMS
ruby
DEPENDENCIES
gsl
jekyll
nokogiri
rake
diff --git a/Rakefile b/Rakefile
index 2954ffc..cb191fe 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,29 +1,34 @@
require 'rubygems'
require 'rake'
SITE_HOSTNAME = "direct.mhack.com"
def info(message)
puts "\e[1;33m--> #{message}\e[00m"
end
def update_remote_repo
info "Updating remote repository"
sh "git push #{SITE_HOSTNAME}:~/repo/mhack.git master"
end
def update_git_hooks
info "Updating git hooks"
sh "scp _deploy/git-post-receive.sh direct.mhack.com:~/repo/mhack.git/hooks/post-receive"
end
task :server do
info "Starting local server"
- sh "jekyll server --watch --future"
+ sh "jekyll server --watch --future --drafts --lsi"
+end
+
+task :build do
+ info "Build site"
+ sh "jekyll build --future --drafts --lsi"
end
task :deploy do
info "Deploying to #{SITE_HOSTNAME}"
update_git_hooks
update_remote_repo
end
diff --git a/_config.yml b/_config.yml
index 429b8f2..2c9cda3 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,29 +1,29 @@
permalink: /:year/:month/:title.html
exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md, README_POSTS.md ]
future: false
lsi: true # Produces an index for related posts.
-paginate: 4
+paginate: 10
plugins: ./_plugins
brand: mhack
author:
name: Marcos Hack
email: [email protected]
twitter: marcoshack
github: marcoshack
linkedin: marcoshack
google_plus: 101876381204467415756
title_sufix: '- Marcos Hack'
disqus:
shortname: mhack
google_analytics:
id: UA-6981296-7
github:
ribbon: false
copyright: '© 2013 Marcos Hack. All rights reserved.'
diff --git a/_drafts/2013-06-27-vontade_politica.md b/_drafts/2013-06-27-vontade_politica.md
deleted file mode 100644
index 54a81ec..0000000
--- a/_drafts/2013-06-27-vontade_politica.md
+++ /dev/null
@@ -1,15 +0,0 @@
----
-layout: post
-title: "Vontade polÃtica"
-description: ""
-image: bandeira_brasil.jpg
-date: 2013-06-27 22:40 UTC
-categories: [ politica ]
-tags: [ brasil, politica, manifestacoes ]
----
-
-A tão falada "vontade polÃtica", ou melhor dizendo, a falta dela, ficou tão escancarada nos últimos dias que chega a dar raiva de pensar em tudo o que poderia ter sido feito pelo paÃs só nas últimas duas décadas e meia.
-
-Não fui em nenhuma das manifestação até agora, por inércia, e por cagaço também. Sei que terei outras oportunidades, mas pelo menos essa história toda me fez voltar a ter interesse em aprender, acompanhar e participar do processo polÃtico do meu paÃs, do qual a maioria das pessoas se mantem afastadas "pra não passar raiva", "por não ter jeito", e por muitas outras "razões". Mas sabemos que não passam de desculpas pra evitar o confronto direto com problemas difÃceis e o esforço pra sair do lugar.
-
-Parabéns a todos que foram pras ruas nas últimas semanas dando a cara a tapa, a balas de borracha e gás lacrimogêneo pra tentar melhorar nosso paÃs. E vamos manter esse gigante acordado, pois sabemos que qualquer vacilo ele volta pra cama na mesma velocidade que saiu.
\ No newline at end of file
diff --git a/_drafts/restful_apis.md b/_drafts/restful_apis.md
new file mode 100644
index 0000000..4cd22ec
--- /dev/null
+++ b/_drafts/restful_apis.md
@@ -0,0 +1,10 @@
+---
+layout: post
+title: "Desenvolvendo APIs RESTful: Rails"
+description: "Insights para o desenvolvimento de APIs RESTful usando Rails."
+image:
+categories: [ programação ]
+tags: [ rails, ruby, rest, restful, api, http ]
+---
+
+lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat sed diam voluptua at vero eos et accusam et justo duo dolores et ea rebum stet clita kasd gubergren no sea takimata sanctus est lorem ipsum dolor sit amet lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat sed diam voluptua at vero eos et accusam et justo duo dolores et ea rebum stet clita kasd gubergren no sea takimata sanctus est lorem ipsum dolor sit amet lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat sed diam voluptua at vero eos et accusam et justo duo dolores et ea rebum stet clita kasd gubergren no sea takimata sanctus est lorem ipsum dolor sit amet duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi lorem ipsum dolor sit amet consectetuer adipiscing
diff --git a/_includes/author_name.html b/_includes/author_name.html
index 83c6e11..e59122b 100644
--- a/_includes/author_name.html
+++ b/_includes/author_name.html
@@ -1,5 +1,7 @@
{% if site.author.google_plus != nil %}
-<a href="https://plus.google.com/{{ site.author.google_plus }}?rel=author">{{ site.author.name }}</a>
+<a href="https://plus.google.com/{{ site.author.google_plus }}?rel=author">
+ <span class="byline author vcard">{{ site.author.name }}
+</a>
{% else %}
-{{ site.author.name }}
-{% endif %}
\ No newline at end of file
+<span class="byline author vcard">{{ site.author.name }}
+{% endif %}
diff --git a/_includes/disqus_div.html b/_includes/disqus_div.html
index 9120fa7..c2b439c 100644
--- a/_includes/disqus_div.html
+++ b/_includes/disqus_div.html
@@ -1,8 +1,8 @@
{% unless page.comments == false %}
<!-- disqus placeholder-->
-<div id="disqus">
+<div id="disqus" class="comment">
<div id="disqus_thread"></div>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
{% endunless %}
\ No newline at end of file
diff --git a/_includes/facebook_div.html b/_includes/facebook_div.html
index 629b17f..4991994 100644
--- a/_includes/facebook_div.html
+++ b/_includes/facebook_div.html
@@ -1,3 +1,3 @@
<!-- facebook placeholder -->
-<div class="fb-like" data-send="true" data-width="450" data-show-faces="false">
+<div class="fb-like entry-unrelated" data-send="true" data-width="450" data-show-faces="false">
</div>
\ No newline at end of file
diff --git a/_includes/footer.html b/_includes/footer.html
index cc73d52..0a9a82a 100644
--- a/_includes/footer.html
+++ b/_includes/footer.html
@@ -1,14 +1,14 @@
<footer class="footer">
- <p>{{ site.copyright }}</p>
- <p>Powered by Open Source software:
+ <p class="source-org vcard copyright">{{ site.copyright }}</p>
+ <p class="entry-unrelated">Powered by Open Source software:
<a href="https://github.com/mojombo/jekyll">Jekyll</a>,
<a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> and much more.
</p>
- <ul class="footer-links">
+ <ul class="entry-unrelated footer-links ">
<li><a href="https://github.com/{{ site.author.github }}/">GitHub</a></li>
<li class="muted">·</li>
<li><a href="https://twitter.com/{{ site.author.twitter }}">Twitter</a></li>
<li class="muted">·</li>
<li><a href="http://linkedin.com/in/{{ site.author.linkedin }}/">LinkedIn</a></li>
</ul>
</footer>
\ No newline at end of file
diff --git a/_includes/navbar.html b/_includes/navbar.html
index ed4098a..ea22b76 100644
--- a/_includes/navbar.html
+++ b/_includes/navbar.html
@@ -1,23 +1,23 @@
-<div class="navbar navbar-inverse navbar-fixed-top">
+<div class="navbar navbar-inverse navbar-fixed-top entry-unrelated">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="/">{{ site.brand }}</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="">
<a href="/">Home</a>
</li>
<li class="">
<a href="/contato.html">Contato</a>
</li>
</ul>
</div>
{% include github_ribbon.html %}
</div>
</div>
</div>
\ No newline at end of file
diff --git a/_includes/post_date.html b/_includes/post_date.html
index 14ee9d2..1a8b2c3 100644
--- a/_includes/post_date.html
+++ b/_includes/post_date.html
@@ -1,3 +1,3 @@
-<time datetime="{{ post.date | date: "%Y-%m-%dT%H:%M%z" }}">
+<time class="published" datetime="{{ post.date | date: "%Y-%m-%dT%H:%M%z" }}">
{{ post.date | date: "%Y-%m-%d %H:%M %z" }}
</time>
\ No newline at end of file
diff --git a/_layouts/default.html b/_layouts/default.html
index 755ae90..9a56509 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,35 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
<title>{{ page.title }} {{ site.title_sufix }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/assets/css/bootstrap.css" rel="stylesheet">
<link href="/assets/css/style.css" rel="stylesheet">
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
+
<div class="container">
- <div class="row">
- <div class="span8">
- {{ content }}
- </div>
- {% include sidebar.html %}
- </div>
+ {{ content }}
</div>
{% include footer.html %}
<script src="/assets/js/jquery-1.9.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
</body>
</html>
\ No newline at end of file
diff --git a/_layouts/post.html b/_layouts/post.html
index 0b99844..6813b1d 100644
--- a/_layouts/post.html
+++ b/_layouts/post.html
@@ -1,43 +1,65 @@
---
layout: default
---
-{% assign post = page %}
-
-<!-- post header -->
-<div class="page-header">
- <h1><a href="{{ post.url }}">{{ post.title }}</a></h1>
- <ul class="post-info">
- <li>{% include post_date.html %}</li>
- <li class="muted">·</li>
- <li>By {% include author_name.html %}</li>
- </ul>
-</div>
+{% assign post = page %}
-<div class="post">
- {{ content }}
-</div>
+<div class="row">
-{% include facebook_div.html %}
-{% include facebook_script.html %}
+ <!-- post -->
+ <div class="span8">
+ <article class="hentry">
+ <div class="page-header">
+ <a href="{{ post.url }}">
+ <h1 class="entry-title">{{ post.title }}</h1>
+ </a>
+ <ul class="post-info">
+ <li>{% include post_date.html %}</li>
+ <li class="muted">·</li>
+ <li>By {% include author_name.html %}</li>
+ </ul>
+ </div>
-<br/> <!-- uhhhh -->
+ <div class="entry-content">
+ {{ content }}
+ </div>
+ </article>
-{% include disqus_div.html %}
-{% include disqus_script.html %}
+ {% include facebook_div.html %}
+ {% include facebook_script.html %}
-<hr class="bs-docs-separator">
+ <br/> <!-- uhhhh -->
-<div class="row">
- <div class="span8">
- {% if post.previous != nil %}
- <a href="{{ post.previous.url }}">
- <span class="pull-left"><i class="icon-backward"></i> {{ post.previous.title }}</span>
- </a>
- {% endif %}
- {% if post.next != nil %}
- <a href="{{ post.next.url }}">
- <span class="pull-right">{{ post.next.title }} <i class="icon-forward"></i></span>
- </a>
- {% endif %}
+ {% include disqus_div.html %}
+ {% include disqus_script.html %}
+
+ <hr class="bs-docs-separator">
+
+ <div class="row entry-unrelated">
+ <div class="span8">
+ {% if post.previous != nil %}
+ <a href="{{ post.previous.url }}">
+ <span class="pull-left"><i class="icon-backward"></i> {{ post.previous.title }}</span>
+ </a>
+ {% endif %}
+ {% if post.next != nil %}
+ <a href="{{ post.next.url }}">
+ <span class="pull-right">{{ post.next.title }} <i class="icon-forward"></i></span>
+ </a>
+ {% endif %}
+ </div>
+ </div>
+ </div>
+
+ <!-- sidebar -->
+ <div class="span4 hidden-phone entry-unrelated">
+ <p class="lead muted">leia também...</p>
+ {% for related in site.related_posts limit: 4 %}
+ <div class="row">
+ <div class="span4">
+ <h4><a class="muted" href="{{ related.url }}">{{ related.title }}</a></h4>
+ <p class="muted"><small>{{ related.content | strip_html | truncatewords: 30 }}</small></p>
+ </div>
+ </div>
+ {% endfor %}
</div>
</div>
diff --git a/_posts/2008-12-01-segunda-via-documento-carro-sao-paulo.html b/_posts/2008-12-01-segunda-via-documento-carro-sao-paulo.html
index b45121e..3b7e3d2 100644
--- a/_posts/2008-12-01-segunda-via-documento-carro-sao-paulo.html
+++ b/_posts/2008-12-01-segunda-via-documento-carro-sao-paulo.html
@@ -1,9 +1,11 @@
---
layout: post
title: Segunda via do documento do carro em São Paulo
date: 2008-12-01 14:10:51 UTC
updated: 2008-12-01 14:10:51 UTC
categories: cotidiano
---
-Saindo um pouco do assunto de tecnologia, gostaria de compartilhar a experiência, no mÃnimo cansativa, de tirar a segunda via do documento do carro em São Paulo. Se eu tivesse essas informações com certeza o trabalho teria sido bem menor.<br/><br/>Semana passada tive meu carro furtado na região da Pompéia e, dentre outras coisas, levaram o documento do veÃculo que estava no porta-luvas. Sabendo o trabalho que dá pra tirar a segunda via vou levar a sério a recomendação de sempre carrega-lo comigo.<br/><br/>Abaixo seguem os passos para tirar a segunda via, parece até um roteiro de um jogo de vÃdeo-game :)<br/><ol><br/> <li>Faça o Boletim de Ocorrência (B.O.) de preferência na delegacia mais próxima do local onde ocorreu o fato. Mesmo sendo permitido faze-lo em qualquer delegacia do Estado de São Paulo (informação de um funcionário da delegacia) é muito comum te mandarem de um lado para o outro alegando que tem que fazer no local do furto ou perto de sua residência. O B.O. pela Internet só pode ser feito se não houve arrombamento do veÃculo. Um funcionário da delegacia inclusive sugeriu que eu fizesse pela Internet dizendo que deixei a janela do carro aberta e o documento do banco, para que pudesse ser caracterizado como "furto", e você ser caracterizado como "otário";</li><br/> <li>Providencie os seguintes documentos listados no <a href="http://www.detran.sp.gov.br/detran_servicos/servicos_veiculos.asp">site do DETRAN</a>, entre em <span style="font-style:italic;">"</span><a style="font-style:italic;"><span class="txtDestaquesLaranja">2ª Via de Documentos</span></a><span style="font-style:italic;">"</span> e depois <span style="font-style:italic;">"</span><a style="font-style:italic;"><span class="txtDestaquesLaranja">2ª via de documento de licenciamento"</span></a>, além disso:- Cópia do RG e cópia do documento que comprove parentesco (certidão de casamento por exemplo) caso quem for tirar a segunda via não seja o proprietário do veÃculo, leve os também os originais- O Decalque do chassi e motor pode ser feito no estacionamento ao lado do DETRAN, o preço varia de R$ 20,00 a 60,00 dependendo da dificuldade pra tirar (tenho um Fiesta, cujo o número do motor só dá pra tirar por baixo do carro, isso me custou R$ 25,00). Você pode tentar encontrar no seu carro ou levar em um posto de vistoria de seguradoras e dar uma gorjeta pro cara tirar, pergunte ao seu corretor sobre o posto mais próximo;</li><br/> <li>Vá ao DETRAN do Ibirapuera pois tudo será feito lá. O Poupa-tempo faz apenas a "montagem do processo" (verificar documentação e preenchimento do formulário) de graça, mas de qualquer forma você terá que ir ao DETRAN fazer vistoria, apresentar o processo e pegar o documento do carro, então sugiro ir direto lá e fazer tudo, com um custo adicional de aproximadamente R$ 6,00 para comprar e preencher o formulário, evitando uma fila monstruosa do Poupa-tempo, pelo menos no da Sé no dia que fui, uma segunda-feira por volta de 14h, haviam umas 200 pessoas na fila!</li><br/> <li>Se for tirar o decalque entre no estacionamento que fica imediatamente após o prédio do DETRAN na 23 de maio (tem um toldo verde na frente). Na verdade é o único estacionamento perto dali. Tire o decalque e guarde as etiquetas, você deverá cola-las no formulário que faremos a seguir;</li><br/> <li>Ao lado da lanchonete, perto da saÃda do estacionamento, existe uma copiadora que monta o processo (a última loja), como disse me cobraram R$ 6,00 pra fazer;</li><br/> <li>Vá ao prédio menor logo atrás do prédio principal do DETRAN, chamado também de prédio CRV, ao entrar no prédio vire a esquerda, existem 3 guichês, vá ao último da direita (pessoa fÃsica) e pegue um tal "PTRE", é um documento que comprova que os dados do CRV (doc. de transferência) estão corretos, vão pedir isso na vistoria;</li><br/> <li>Pegue seu carro e faça a vistoria, é só sair do estacionamento e manter tudo a direita, logo depois da curva tem a entrada, com umas placas "Lacração";</li><br/> <li>Depois volte ao mesmo prédio do DETRAN onde você pegou o PTRE, provavelmente você terá que colocar o carro novamente no estacionamento. Dessa vez ao entrar no prédio vire a direita e procure pelo balcão de Licenciamento, é só entregar tudo e pegar o documento. No meu caso entregaram na hora, mas me disseram que poderia demorar até 3 dias úteis, deve depender do movimento.</li><br/></ol><br/>Como eu disse, esse é jeito mais fácil, eu tive que passar no DETRAN do Villa Lobos achando que poderia fazer a vistoria antes, de lá me mandaram pro Poupa-Tempo, fui até a Sé pra descobrir que poderia ir direto no DETRAN, e no DETRAN você descobre algumas coisas que não estão escritas em lugar nenhum, como o tal PTRE. E ainda têm gente que enche o peito pra dizer "sou brasileiro e não desisto nunca!", também, com uma burocracia e falta de informação dessas se desistir não tira nem o RG.<br/><br/>Boa sorte e lembre-se: NUNCA DEIXE O DOCUMENTO NO PORTA-LUVAS!!!<br/><br/>
\ No newline at end of file
+<p>Saindo um pouco do assunto de tecnologia, gostaria de compartilhar a experiência, no mÃnimo cansativa, de tirar a segunda via do documento do carro em São Paulo. Se eu tivesse essas informações com certeza o trabalho teria sido bem menor.</p>
+
+Semana passada tive meu carro furtado na região da Pompéia e, dentre outras coisas, levaram o documento do veÃculo que estava no porta-luvas. Sabendo o trabalho que dá pra tirar a segunda via vou levar a sério a recomendação de sempre carrega-lo comigo.<br/><br/>Abaixo seguem os passos para tirar a segunda via, parece até um roteiro de um jogo de vÃdeo-game :)<br/><ol><br/> <li>Faça o Boletim de Ocorrência (B.O.) de preferência na delegacia mais próxima do local onde ocorreu o fato. Mesmo sendo permitido faze-lo em qualquer delegacia do Estado de São Paulo (informação de um funcionário da delegacia) é muito comum te mandarem de um lado para o outro alegando que tem que fazer no local do furto ou perto de sua residência. O B.O. pela Internet só pode ser feito se não houve arrombamento do veÃculo. Um funcionário da delegacia inclusive sugeriu que eu fizesse pela Internet dizendo que deixei a janela do carro aberta e o documento do banco, para que pudesse ser caracterizado como "furto", e você ser caracterizado como "otário";</li><br/> <li>Providencie os seguintes documentos listados no <a href="http://www.detran.sp.gov.br/detran_servicos/servicos_veiculos.asp">site do DETRAN</a>, entre em <span style="font-style:italic;">"</span><a style="font-style:italic;"><span class="txtDestaquesLaranja">2ª Via de Documentos</span></a><span style="font-style:italic;">"</span> e depois <span style="font-style:italic;">"</span><a style="font-style:italic;"><span class="txtDestaquesLaranja">2ª via de documento de licenciamento"</span></a>, além disso:- Cópia do RG e cópia do documento que comprove parentesco (certidão de casamento por exemplo) caso quem for tirar a segunda via não seja o proprietário do veÃculo, leve os também os originais- O Decalque do chassi e motor pode ser feito no estacionamento ao lado do DETRAN, o preço varia de R$ 20,00 a 60,00 dependendo da dificuldade pra tirar (tenho um Fiesta, cujo o número do motor só dá pra tirar por baixo do carro, isso me custou R$ 25,00). Você pode tentar encontrar no seu carro ou levar em um posto de vistoria de seguradoras e dar uma gorjeta pro cara tirar, pergunte ao seu corretor sobre o posto mais próximo;</li><br/> <li>Vá ao DETRAN do Ibirapuera pois tudo será feito lá. O Poupa-tempo faz apenas a "montagem do processo" (verificar documentação e preenchimento do formulário) de graça, mas de qualquer forma você terá que ir ao DETRAN fazer vistoria, apresentar o processo e pegar o documento do carro, então sugiro ir direto lá e fazer tudo, com um custo adicional de aproximadamente R$ 6,00 para comprar e preencher o formulário, evitando uma fila monstruosa do Poupa-tempo, pelo menos no da Sé no dia que fui, uma segunda-feira por volta de 14h, haviam umas 200 pessoas na fila!</li><br/> <li>Se for tirar o decalque entre no estacionamento que fica imediatamente após o prédio do DETRAN na 23 de maio (tem um toldo verde na frente). Na verdade é o único estacionamento perto dali. Tire o decalque e guarde as etiquetas, você deverá cola-las no formulário que faremos a seguir;</li><br/> <li>Ao lado da lanchonete, perto da saÃda do estacionamento, existe uma copiadora que monta o processo (a última loja), como disse me cobraram R$ 6,00 pra fazer;</li><br/> <li>Vá ao prédio menor logo atrás do prédio principal do DETRAN, chamado também de prédio CRV, ao entrar no prédio vire a esquerda, existem 3 guichês, vá ao último da direita (pessoa fÃsica) e pegue um tal "PTRE", é um documento que comprova que os dados do CRV (doc. de transferência) estão corretos, vão pedir isso na vistoria;</li><br/> <li>Pegue seu carro e faça a vistoria, é só sair do estacionamento e manter tudo a direita, logo depois da curva tem a entrada, com umas placas "Lacração";</li><br/> <li>Depois volte ao mesmo prédio do DETRAN onde você pegou o PTRE, provavelmente você terá que colocar o carro novamente no estacionamento. Dessa vez ao entrar no prédio vire a direita e procure pelo balcão de Licenciamento, é só entregar tudo e pegar o documento. No meu caso entregaram na hora, mas me disseram que poderia demorar até 3 dias úteis, deve depender do movimento.</li><br/></ol><br/>Como eu disse, esse é jeito mais fácil, eu tive que passar no DETRAN do Villa Lobos achando que poderia fazer a vistoria antes, de lá me mandaram pro Poupa-Tempo, fui até a Sé pra descobrir que poderia ir direto no DETRAN, e no DETRAN você descobre algumas coisas que não estão escritas em lugar nenhum, como o tal PTRE. E ainda têm gente que enche o peito pra dizer "sou brasileiro e não desisto nunca!", também, com uma burocracia e falta de informação dessas se desistir não tira nem o RG.<br/><br/>Boa sorte e lembre-se: NUNCA DEIXE O DOCUMENTO NO PORTA-LUVAS!!!<br/><br/>
\ No newline at end of file
diff --git a/_posts/2009-03-26-ip-communications-2008.html b/_posts/2009-03-26-ip-communications-2008.html
index ac152d8..904a469 100644
--- a/_posts/2009-03-26-ip-communications-2008.html
+++ b/_posts/2009-03-26-ip-communications-2008.html
@@ -1,8 +1,20 @@
---
layout: post
title: IP Communications 2008
date: 2009-03-26 12:01:12 UTC
updated: 2009-03-26 12:01:12 UTC
---
-Esse post está uns 3 meses atrasado, mas como diz o ditado "antes tarde do que nunca".<br/><br/>Nos dias 4 e 5 de Dezembro de 2008 a <a href="http://www.voicetechnology.com.br/">Voice Technology</a> esteve presente na<a href="http://www.ipcomm2008.com.br/"> IPCommunications 2008</a> ministrando duas palestras sobre VoIP. Foi nossa primeira experiência como palestrantes em um evento desse porte e com certeza o ponta pé inicial para tentar criar essa cultura dentro da empresa.<br/><br/>Trabalhamos a mais de 4 anos com o desenvolvimento de produtos e serviços VoIP mas até então não havÃamos trabalhado para expor e compartilhar esse conhecimento com o mercado e principalmente com a comunidade de Software Livre e Código Aberto, visto que utilizamos vários sistemas, ferramentas e frameworks opensource em nosso dia-a-dia e sabemos que é nosso dever devolver algo para a comunidade, seja através de software ou passando esse conhecimento adiante. Essa troca é um fator fundamental para o bom funcionamento desse ecossistema e com certeza é o que nós e a Voice queremos que aconteça.<br/><br/>Nosso colega André Pantalião escreveu dois posts no blog Ensinar (outra iniciativa para compartilhar nosso conhecimento) sobre o evento: <a href="http://ensinar.wordpress.com/2008/12/04/ipcomm-2008-palestra-do-hack-e-noel/">IPComm 2008 - Palestra do Hack e Noel</a> e<span style="text-decoration:underline;"> </span><a href="http://ensinar.wordpress.com/2008/12/05/ipcomm-2008-palestra-do-antonio-e-do-sakuma/">IPComm 2008 - Palestra do Antonio e do Sakuma</a><br/><br/>E a seguir estão os slides das duas apresentações. Fiquem a vontade para entrar em contato se tiverem crÃticas, dúvidas, sugestões ou interesse em mais detalhes sobre as apresentações:<br/><br/><span style="font-weight:bold;">OpenSER em Cluster utilizando IPVS e Keepalived</span><br/>Por Marcos Hack e Noel Rocha<br/><br/>[googleapps domain="docs" dir="present/embed" query="id=ddc3gb2x_2gqzrqgsx" width="410" height="342" /]<br/><br/><span style="font-weight:bold;">Testes de performance em plataformas SIP utilizando SIPP</span><br/>Por Antônio Anderson e Daniel Sakuma<br/><br/>[googleapps domain="docs" dir="present/embed" query="id=dg69scmg_142g4rc52gf" width="410" height="342" /]
\ No newline at end of file
+<p>Nos dias 4 e 5 de Dezembro de 2008 a <a href="http://www.voicetechnology.com.br/">Voice Technology</a> esteve presente na<a href="http://www.ipcomm2008.com.br/"> IPCommunications 2008</a> ministrando duas palestras sobre VoIP.</p>
+
+<p>Foi nossa primeira experiência como palestrantes em um evento desse porte e com certeza o ponta pé inicial para tentar criar essa cultura dentro da empresa.</p>
+
+<p>Trabalhamos a mais de 4 anos com o desenvolvimento de produtos e serviços VoIP mas até então não havÃamos trabalhado para expor e compartilhar esse conhecimento com o mercado e principalmente com a comunidade de Software Livre e Código Aberto, visto que utilizamos vários sistemas, ferramentas e frameworks opensource em nosso dia-a-dia e sabemos que é nosso dever devolver algo para a comunidade, seja através de software ou passando esse conhecimento adiante. Essa troca é um fator fundamental para o bom funcionamento desse ecossistema e com certeza é o que nós e a Voice queremos que aconteça.</p>
+
+<p>Nosso colega André Pantalião escreveu dois posts no blog Ensinar (outra iniciativa para compartilhar nosso conhecimento) sobre o evento: <a href="http://ensinar.wordpress.com/2008/12/04/ipcomm-2008-palestra-do-hack-e-noel/">IPComm 2008 - Palestra do Hack e Noel</a> e<span style="text-decoration:underline;"> </span><a href="http://ensinar.wordpress.com/2008/12/05/ipcomm-2008-palestra-do-antonio-e-do-sakuma/">IPComm 2008 - Palestra do Antonio e do Sakuma</a></p>
+
+<p>A seguir estão os slides das duas apresentações. Fiquem a vontade para entrar em contato se tiverem crÃticas, dúvidas, sugestões ou interesse em mais detalhes sobre as apresentações:</p>
+
+<div>
+<span style="font-weight:bold;">OpenSER em Cluster utilizando IPVS e Keepalived</span><br/>Por Marcos Hack e Noel Rocha<br/><br/>[googleapps domain="docs" dir="present/embed" query="id=ddc3gb2x_2gqzrqgsx" width="410" height="342" /]<br/><br/><span style="font-weight:bold;">Testes de performance em plataformas SIP utilizando SIPP</span><br/>Por Antônio Anderson e Daniel Sakuma<br/><br/>[googleapps domain="docs" dir="present/embed" query="id=dg69scmg_142g4rc52gf" width="410" height="342" /]
+</div>
\ No newline at end of file
diff --git a/_posts/2009-12-17-o-ze-o-git-e-o-github.html b/_posts/2009-12-17-o-ze-o-git-e-o-github.html
index 6a17544..1522f9e 100644
--- a/_posts/2009-12-17-o-ze-o-git-e-o-github.html
+++ b/_posts/2009-12-17-o-ze-o-git-e-o-github.html
@@ -1,94 +1,96 @@
---
layout: post
title: O Zé, O git e o Github
date: 2009-12-17 14:01:14 UTC
updated: 2009-12-17 14:01:14 UTC
categories:
- dev
tags:
- git
- github
---
-<p>
-Esses dias estava eu tentando convencer um amigo meu, o Zé, de o que usar o Github como "hub" (duh!) de projetos Git é muito interessante e paga a "complexidade" extra dos pulls, pushs e merges intermediários. A conversa é relativamente longa, mas divertida e rápida de ler. Se você é teimoso como o Zé, pode servir pra entender melhor a idéia do Github e da dinâmica dos sistemas de controle de versão distribuÃdos:
-</p>
-<span style="color: #ff6600;">Zé</span>: como faço o push?<br/>
-<span style="color: #ff6600;">Zé</span>: vc liberou lá?<br/>
-<span style="color: #0000ff;">Hack</span>: na verdade vc tem que fazer pull agora<br/>
-<span style="color: #ff6600;">Zé</span>: xiiii<br/>
-<span style="color: #ff6600;">Zé</span>: pull?<br/>
-<span style="color: #0000ff;">Hack</span>: push é vc mandar do seu repositorio local pra algum lugar<br/>
-<span style="color: #0000ff;">Hack</span>: pull é de algum lugar pro se repositorio<br/>
-<span style="color: #ff6600;">Zé</span>: a gente aqui manda ver push mesmo<br/>
-<span style="color: #ff6600;">Zé</span>: afinal, a minha é a última vrs<br/>
-<span style="color: #ff6600;">Zé</span>: como é esse pull?<br/>
-<span style="color: #0000ff;">Hack</span>: pera ai<br/>
-<span style="color: #0000ff;">Hack</span>: vc quer puxar as minhas alterações ou enviar as suas?<br/>
-<span style="color: #ff6600;">Zé</span>: mandar a minha<br/>
-<span style="color: #0000ff;">Hack</span>: vc já atualizou com a minha?<br/>
-<span style="color: #ff6600;">Zé</span>: sim sr<br/>
-<span style="color: #0000ff;">Hack</span>: com o rails:freeze ?<br/>
-<span style="color: #0000ff;">Hack</span>: ok<br/>
-<span style="color: #ff6600;">Zé</span>: já escrevi o crawler e já quero mandar pro sr<br/>
-<span style="color: #ff6600;">Zé</span>: se for possÃvel<br/>
-<span style="color: #ff6600;">Zé</span>: senao te mando os arquivos por email<br/>
-<span style="color: #0000ff;">Hack</span>: para<br/>
-<span style="color: #ff6600;">Zé</span>: ou gero um patch<br/>
-<span style="color: #0000ff;">Hack</span>: ta doido<br/>
-<span style="color: #0000ff;">Hack</span>: vc criou sua conta no github?<br/>
-<span style="color: #ff6600;">Zé</span>: acho que já tenho<br/>
-<span style="color: #ff6600;">Zé</span>: perai<br/>
-<span style="color: #0000ff;">Hack</span>: depois vai no meu repositorio e clica em "fork"<br/>
-<span style="color: #0000ff;">Hack</span>: isso vai criar um fork do meu repositorio na sua conta<br/>
-<span style="color: #ff6600;">Zé</span>: xiiiiiii<br/>
-<span style="color: #0000ff;">Hack</span>: q?<br/>
-<span style="color: #ff6600;">Zé</span>: o que eu gosto mesmo no github é a simplicidade<br/>
-<span style="color: #0000ff;">Hack</span>: bom, mas ai o problema não é o github<br/>
-<span style="color: #0000ff;">Hack</span>: scm distribuido é assim p..rra<br/>
-<span style="color: #0000ff;">Hack</span>: vai por mim, vc vai ver que é legal depois<br/>
-<span style="color: #ff6600;">Zé</span>: cara, eu uso o git há mais de um ano<br/>
-<span style="color: #ff6600;">Zé</span>: o github embassa<br/>
-<span style="color: #0000ff;">Hack</span>: vc deve usar o git como usava o SVN<br/>
-<span style="color: #ff6600;">Zé</span>: cade o lance do meu ssh direto?<br/>
-<span style="color: #ff6600;">Zé</span>: hein?<br/>
-<span style="color: #ff6600;">Zé</span>: nem velho... aqui git é moeda corrente<br/>
-<span style="color: #ff6600;">Zé</span>: a gente troca versão um com o outro direto<br/>
-<span style="color: #ff6600;">Zé</span>: mas tá, blz<br/>
-<span style="color: #ff6600;">Zé</span>: vamos ao github<br/>
-<span style="color: #0000ff;">Hack</span>: pois é, vc tem IP publico?<br/>
-<span style="color: #0000ff;">Hack</span>: se tivesse daria<br/>
-<span style="color: #ff6600;">Zé</span>: né<br/>
-<span style="color: #0000ff;">Hack</span>: por isso o github é bom<br/>
-<span style="color: #0000ff;">Hack</span>: e como vcs trocam versao direto sem o pull?<br/>
-<span style="color: #ff6600;">Zé</span>: vc vai e clona, aà faz push de volta direto pro cara<br/>
-<span style="color: #0000ff;">Hack</span>: ah, e todo mundo tem direito de escrita no repositorio do cara?<br/>
-<span style="color: #ff6600;">Zé</span>: push ssh://maquinadoze/repo/projeto<br/>
-<span style="color: #ff6600;">Zé</span>: quem ele quer né<br/>
-<span style="color: #ff6600;">Zé</span>: isso rola entre os arquitetos<br/>
-<span style="color: #0000ff;">Hack</span>: bom, geralmente vc clona o repositorio do zé, que é o tal do "fork"<br/>
-<span style="color: #0000ff;">Hack</span>: ai vc diz pro zé, "zé, tem coisa aqui, veja se vc quer"<br/>
-<span style="color: #0000ff;">Hack</span>: ai o zé vai lá e dá um pull no seu repositório<br/>
-<span style="color: #0000ff;">Hack</span>: e ELE decide se o que vc fez entra ou não no repositório DELE<br/>
-<span style="color: #ff6600;">Zé</span>: pois é<br/>
-<span style="color: #ff6600;">Zé</span>: muuuito mais legal<br/>
-<span style="color: #0000ff;">Hack</span>: ta zuando?<br/>
-<span style="color: #0000ff;">Hack</span>: vai fazer o fork ou não mané?<br/>
-<span style="color: #0000ff;">Hack</span>: ah, já ta lá<br/>
-<span style="color: #0000ff;">Hack</span>: agora vc faz o clone pra sua máquina<br/>
-<span style="color: #0000ff;">Hack</span>: ou "checkout", se quiser pensar "svn"<br/>
-<span style="color: #0000ff;">Hack</span>: coloca as alterações que vc fez nesse clone<br/>
-<span style="color: #0000ff;">Hack</span>: e dá um push<br/>
-<span style="color: #0000ff;">Hack</span>: ai eu pego<br/>
-<span style="color: #0000ff;">Hack</span>: detalhe: vc clona o SEU repositorio, não o meu<br/>
-<span style="color: #ff6600;">Zé</span>: ou seja, lixo<br/>
-<span style="color: #ff6600;">Zé</span>: lixo lixo lixo lixo<br/>
-<span style="color: #0000ff;">Hack</span>: não vou discutir<br/>
-<span style="color: #0000ff;">Hack</span>: ta bom vai, vou discutir um pouquinho<br/>
-<span style="color: #0000ff;">Hack</span>: o github facilita pro caso como o nosso<br/>
-<span style="color: #0000ff;">Hack</span>: o github na verdade é um servidor com IP publico que agente usa como um "espelho" dos respositorios que estao na nossas maquinas<br/>
-<span style="color: #0000ff;">Hack</span>: mas eu nao acesso a sua maquina diretamente, assim como vc poderia ter desligado seu laptop e ido tomar um suco de laranja com acerola<br/>
-<span style="color: #0000ff;">Hack</span>: e ai, como eu pegaria as suas alteracoes pra continuar trabalhando?<br/>
-<span style="color: #0000ff;">Hack</span>: e como pessoas que nem se conhecem podem colaborar cada um no seu timezone, e etc, etc, etc<br/>
-<span style="color: #0000ff;">Hack</span>: eles usam o github<br/>
-<span style="color: #0000ff;">Hack</span>: legal né?<br/>
-<br/>
\ No newline at end of file
+<p>Esses dias estava eu tentando convencer um amigo meu, o Zé, de o que usar o Github como "hub" (duh!) de projetos Git é muito interessante e paga a "complexidade" extra dos pulls, pushs e merges intermediários. A conversa é relativamente longa, mas divertida e rápida de ler.</p>
+
+<p>Se você é teimoso como o Zé, pode servir pra entender melhor a idéia do Github e da dinâmica dos sistemas de controle de versão distribuÃdos:</p>
+
+<div>
+ <span style="color: #ff6600;">Zé</span>: como faço o push?<br/>
+ <span style="color: #ff6600;">Zé</span>: vc liberou lá?<br/>
+ <span style="color: #0000ff;">Hack</span>: na verdade vc tem que fazer pull agora<br/>
+ <span style="color: #ff6600;">Zé</span>: xiiii<br/>
+ <span style="color: #ff6600;">Zé</span>: pull?<br/>
+ <span style="color: #0000ff;">Hack</span>: push é vc mandar do seu repositorio local pra algum lugar<br/>
+ <span style="color: #0000ff;">Hack</span>: pull é de algum lugar pro se repositorio<br/>
+ <span style="color: #ff6600;">Zé</span>: a gente aqui manda ver push mesmo<br/>
+ <span style="color: #ff6600;">Zé</span>: afinal, a minha é a última vrs<br/>
+ <span style="color: #ff6600;">Zé</span>: como é esse pull?<br/>
+ <span style="color: #0000ff;">Hack</span>: pera ai<br/>
+ <span style="color: #0000ff;">Hack</span>: vc quer puxar as minhas alterações ou enviar as suas?<br/>
+ <span style="color: #ff6600;">Zé</span>: mandar a minha<br/>
+ <span style="color: #0000ff;">Hack</span>: vc já atualizou com a minha?<br/>
+ <span style="color: #ff6600;">Zé</span>: sim sr<br/>
+ <span style="color: #0000ff;">Hack</span>: com o rails:freeze ?<br/>
+ <span style="color: #0000ff;">Hack</span>: ok<br/>
+ <span style="color: #ff6600;">Zé</span>: já escrevi o crawler e já quero mandar pro sr<br/>
+ <span style="color: #ff6600;">Zé</span>: se for possÃvel<br/>
+ <span style="color: #ff6600;">Zé</span>: senao te mando os arquivos por email<br/>
+ <span style="color: #0000ff;">Hack</span>: para<br/>
+ <span style="color: #ff6600;">Zé</span>: ou gero um patch<br/>
+ <span style="color: #0000ff;">Hack</span>: ta doido<br/>
+ <span style="color: #0000ff;">Hack</span>: vc criou sua conta no github?<br/>
+ <span style="color: #ff6600;">Zé</span>: acho que já tenho<br/>
+ <span style="color: #ff6600;">Zé</span>: perai<br/>
+ <span style="color: #0000ff;">Hack</span>: depois vai no meu repositorio e clica em "fork"<br/>
+ <span style="color: #0000ff;">Hack</span>: isso vai criar um fork do meu repositorio na sua conta<br/>
+ <span style="color: #ff6600;">Zé</span>: xiiiiiii<br/>
+ <span style="color: #0000ff;">Hack</span>: q?<br/>
+ <span style="color: #ff6600;">Zé</span>: o que eu gosto mesmo no github é a simplicidade<br/>
+ <span style="color: #0000ff;">Hack</span>: bom, mas ai o problema não é o github<br/>
+ <span style="color: #0000ff;">Hack</span>: scm distribuido é assim p..rra<br/>
+ <span style="color: #0000ff;">Hack</span>: vai por mim, vc vai ver que é legal depois<br/>
+ <span style="color: #ff6600;">Zé</span>: cara, eu uso o git há mais de um ano<br/>
+ <span style="color: #ff6600;">Zé</span>: o github embassa<br/>
+ <span style="color: #0000ff;">Hack</span>: vc deve usar o git como usava o SVN<br/>
+ <span style="color: #ff6600;">Zé</span>: cade o lance do meu ssh direto?<br/>
+ <span style="color: #ff6600;">Zé</span>: hein?<br/>
+ <span style="color: #ff6600;">Zé</span>: nem velho... aqui git é moeda corrente<br/>
+ <span style="color: #ff6600;">Zé</span>: a gente troca versão um com o outro direto<br/>
+ <span style="color: #ff6600;">Zé</span>: mas tá, blz<br/>
+ <span style="color: #ff6600;">Zé</span>: vamos ao github<br/>
+ <span style="color: #0000ff;">Hack</span>: pois é, vc tem IP publico?<br/>
+ <span style="color: #0000ff;">Hack</span>: se tivesse daria<br/>
+ <span style="color: #ff6600;">Zé</span>: né<br/>
+ <span style="color: #0000ff;">Hack</span>: por isso o github é bom<br/>
+ <span style="color: #0000ff;">Hack</span>: e como vcs trocam versao direto sem o pull?<br/>
+ <span style="color: #ff6600;">Zé</span>: vc vai e clona, aà faz push de volta direto pro cara<br/>
+ <span style="color: #0000ff;">Hack</span>: ah, e todo mundo tem direito de escrita no repositorio do cara?<br/>
+ <span style="color: #ff6600;">Zé</span>: push ssh://maquinadoze/repo/projeto<br/>
+ <span style="color: #ff6600;">Zé</span>: quem ele quer né<br/>
+ <span style="color: #ff6600;">Zé</span>: isso rola entre os arquitetos<br/>
+ <span style="color: #0000ff;">Hack</span>: bom, geralmente vc clona o repositorio do zé, que é o tal do "fork"<br/>
+ <span style="color: #0000ff;">Hack</span>: ai vc diz pro zé, "zé, tem coisa aqui, veja se vc quer"<br/>
+ <span style="color: #0000ff;">Hack</span>: ai o zé vai lá e dá um pull no seu repositório<br/>
+ <span style="color: #0000ff;">Hack</span>: e ELE decide se o que vc fez entra ou não no repositório DELE<br/>
+ <span style="color: #ff6600;">Zé</span>: pois é<br/>
+ <span style="color: #ff6600;">Zé</span>: muuuito mais legal<br/>
+ <span style="color: #0000ff;">Hack</span>: ta zuando?<br/>
+ <span style="color: #0000ff;">Hack</span>: vai fazer o fork ou não mané?<br/>
+ <span style="color: #0000ff;">Hack</span>: ah, já ta lá<br/>
+ <span style="color: #0000ff;">Hack</span>: agora vc faz o clone pra sua máquina<br/>
+ <span style="color: #0000ff;">Hack</span>: ou "checkout", se quiser pensar "svn"<br/>
+ <span style="color: #0000ff;">Hack</span>: coloca as alterações que vc fez nesse clone<br/>
+ <span style="color: #0000ff;">Hack</span>: e dá um push<br/>
+ <span style="color: #0000ff;">Hack</span>: ai eu pego<br/>
+ <span style="color: #0000ff;">Hack</span>: detalhe: vc clona o SEU repositorio, não o meu<br/>
+ <span style="color: #ff6600;">Zé</span>: ou seja, lixo<br/>
+ <span style="color: #ff6600;">Zé</span>: lixo lixo lixo lixo<br/>
+ <span style="color: #0000ff;">Hack</span>: não vou discutir<br/>
+ <span style="color: #0000ff;">Hack</span>: ta bom vai, vou discutir um pouquinho<br/>
+ <span style="color: #0000ff;">Hack</span>: o github facilita pro caso como o nosso<br/>
+ <span style="color: #0000ff;">Hack</span>: o github na verdade é um servidor com IP publico que agente usa como um "espelho" dos respositorios que estao na nossas maquinas<br/>
+ <span style="color: #0000ff;">Hack</span>: mas eu nao acesso a sua maquina diretamente, assim como vc poderia ter desligado seu laptop e ido tomar um suco de laranja com acerola<br/>
+ <span style="color: #0000ff;">Hack</span>: e ai, como eu pegaria as suas alteracoes pra continuar trabalhando?<br/>
+ <span style="color: #0000ff;">Hack</span>: e como pessoas que nem se conhecem podem colaborar cada um no seu timezone, e etc, etc, etc<br/>
+ <span style="color: #0000ff;">Hack</span>: eles usam o github<br/>
+ <span style="color: #0000ff;">Hack</span>: legal né?<br/>
+</div>
diff --git a/assets/css/style.css b/assets/css/style.css
index ca8923a..2d4d421 100644
--- a/assets/css/style.css
+++ b/assets/css/style.css
@@ -1,36 +1,36 @@
-body { padding-top: 40px; }
+body { padding-top: 50px; }
@media screen and (max-width: 768px) {
body { padding-top: 0px; }
}
.footer {
text-align: center;
padding: 30px 0;
margin-top: 70px;
border-top: 1px solid #e5e5e5;
background-color: #f5f5f5;
}
.footer p {
margin-bottom: 0;
color: #777;
}
.footer-links {
margin: 10px 0;
}
.footer-links li {
display: inline;
padding: 0 2px;
}
.footer-links li:first-child {
padding-left: 0;
}
.post-info {
margin: 10px 0;
}
.post-info li {
font-size: 85%;
color: #999999;
display: inline;
padding: 0 2px;
}
\ No newline at end of file
diff --git a/index.html b/index.html
index 9d51ead..6a7dd0f 100644
--- a/index.html
+++ b/index.html
@@ -1,27 +1,32 @@
---
layout: default
title: Home
change_frequency: always
---
-<br />
-
-{% for post in paginator.posts %}
<div class="row">
- <div class="span2 hidden-phone">
- {% if post.image != nil %}
- <img src="/images/{{ post.image }}" />
- {% endif %}
- </div>
- <div class="span6">
- <h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
- <div class="post_excerpt">
- <blockquote>
- <p>{{ post.content | strip_html | truncatewords: 30 }}</p>
- <small class="muted">{% include post_date.html %}</small>
- </blockquote>
+ <div class="span8">
+ {% for post in paginator.posts %}
+ <div class="row">
+ <div class="span2 hidden-phone">
+ {% if post.image != nil %}
+ <img src="/images/{{ post.image }}" />
+ {% endif %}
+ </div>
+ <div class="span6">
+ <h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
+ <div class="post_excerpt">
+ <blockquote>
+ <p>{{ post.content | strip_html | truncatewords: 30 }}</p>
+ <!-- <p>{{ post.excerpt }}</p> -->
+ <small class="muted">{% include post_date.html %}</small>
+ </blockquote>
+ </div>
+ </div>
</div>
+ {% endfor %}
+ {% include pagination.html %}
+ </div>
+ <div class="span4 hidden-phone">
+ {% include twitter_widget.html %}
</div>
</div>
-{% endfor %}
-
-{% include pagination.html %}
|
marcoshack/marcoshack.github.io
|
231aa2c962971743e1ae37d854321e78302de5d4
|
correcao do layout default (padding-top)
|
diff --git a/_layouts/default.html b/_layouts/default.html
index 839fcc2..755ae90 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,38 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
<title>{{ page.title }} {{ site.title_sufix }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/assets/css/bootstrap.css" rel="stylesheet">
<link href="/assets/css/style.css" rel="stylesheet">
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
- <br/>
- <br/>
-
<div class="container">
<div class="row">
<div class="span8">
{{ content }}
</div>
{% include sidebar.html %}
</div>
</div>
{% include footer.html %}
<script src="/assets/js/jquery-1.9.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
</body>
</html>
\ No newline at end of file
diff --git a/assets/css/style.css b/assets/css/style.css
index a87af02..ca8923a 100644
--- a/assets/css/style.css
+++ b/assets/css/style.css
@@ -1,34 +1,36 @@
-/* Footer
--------------------------------------------------- */
+body { padding-top: 40px; }
+@media screen and (max-width: 768px) {
+ body { padding-top: 0px; }
+}
.footer {
text-align: center;
padding: 30px 0;
margin-top: 70px;
border-top: 1px solid #e5e5e5;
background-color: #f5f5f5;
}
.footer p {
margin-bottom: 0;
color: #777;
}
.footer-links {
margin: 10px 0;
}
.footer-links li {
display: inline;
padding: 0 2px;
}
.footer-links li:first-child {
padding-left: 0;
}
.post-info {
margin: 10px 0;
}
.post-info li {
font-size: 85%;
color: #999999;
display: inline;
padding: 0 2px;
}
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
55604e24d968ac29e8484f70e9648998194e4cac
|
correcoes na task deploy
|
diff --git a/Rakefile b/Rakefile
index cddbac5..2954ffc 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,27 +1,29 @@
require 'rubygems'
require 'rake'
SITE_HOSTNAME = "direct.mhack.com"
def info(message)
puts "\e[1;33m--> #{message}\e[00m"
end
-task :server do
- info "Starting local server"
- sh "jekyll server --watch --future"
+def update_remote_repo
+ info "Updating remote repository"
+ sh "git push #{SITE_HOSTNAME}:~/repo/mhack.git master"
end
-task :deploy => [ :update_remote_repo, :update_git_hooks ] do
- info "Deploying to #{SITE_HOSTNAME}"
+def update_git_hooks
+ info "Updating git hooks"
+ sh "scp _deploy/git-post-receive.sh direct.mhack.com:~/repo/mhack.git/hooks/post-receive"
end
-task :update_remote_repo do
- info "Updating remote repository"
- sh "git push #{SITE_HOSTNAME}:~/repo/mhack.git master"
+task :server do
+ info "Starting local server"
+ sh "jekyll server --watch --future"
end
-task :update_git_hooks do
- info "Updating git hooks"
- sh "scp _deploy/git-post-receive.sh direct.mhack.com:~/repo/mhack.git/hooks/post-receive"
+task :deploy do
+ info "Deploying to #{SITE_HOSTNAME}"
+ update_git_hooks
+ update_remote_repo
end
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index 5b6ba0f..ef59f0e 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,38 +1,38 @@
#!/usr/bin/env bash
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
TIMEZONE=America/Sao_Paulo
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
function log_step {
echo -e "\e[1;33m--> ${1}\e[00m"
}
log_step "Setting up local workspace"
git clone $GIT_REPO $TMP_GIT_CLONE
log_step "Updating dependencies"
cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
log_step "Updating site"
-TZ=$TIMEZONE $JEKYLL_CMD build $TMP_GIT_CLONE $PUBLIC_WWW
+TZ=$TIMEZONE $JEKYLL_CMD $TMP_GIT_CLONE $PUBLIC_WWW
log_step "Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
marcoshack/marcoshack.github.io
|
6ab6b6c9a6fda647380bbefdf9bae4300c268192
|
[draft] Vontade Politica
|
diff --git a/_drafts/2013-06-27-vontade_politica.md b/_drafts/2013-06-27-vontade_politica.md
new file mode 100644
index 0000000..54a81ec
--- /dev/null
+++ b/_drafts/2013-06-27-vontade_politica.md
@@ -0,0 +1,15 @@
+---
+layout: post
+title: "Vontade polÃtica"
+description: ""
+image: bandeira_brasil.jpg
+date: 2013-06-27 22:40 UTC
+categories: [ politica ]
+tags: [ brasil, politica, manifestacoes ]
+---
+
+A tão falada "vontade polÃtica", ou melhor dizendo, a falta dela, ficou tão escancarada nos últimos dias que chega a dar raiva de pensar em tudo o que poderia ter sido feito pelo paÃs só nas últimas duas décadas e meia.
+
+Não fui em nenhuma das manifestação até agora, por inércia, e por cagaço também. Sei que terei outras oportunidades, mas pelo menos essa história toda me fez voltar a ter interesse em aprender, acompanhar e participar do processo polÃtico do meu paÃs, do qual a maioria das pessoas se mantem afastadas "pra não passar raiva", "por não ter jeito", e por muitas outras "razões". Mas sabemos que não passam de desculpas pra evitar o confronto direto com problemas difÃceis e o esforço pra sair do lugar.
+
+Parabéns a todos que foram pras ruas nas últimas semanas dando a cara a tapa, a balas de borracha e gás lacrimogêneo pra tentar melhorar nosso paÃs. E vamos manter esse gigante acordado, pois sabemos que qualquer vacilo ele volta pra cama na mesma velocidade que saiu.
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
6ac66ca303636c8a9e60ccb5cf33a4515fc7a5c4
|
deploy rake task fixed to use direct.mhack.com
|
diff --git a/Rakefile b/Rakefile
index 4eb43a8..960ace2 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,21 +1,27 @@
require 'rubygems'
require 'rake'
+SITE_HOSTNAME = "direct.mhack.com"
+
def info(message)
puts "\e[1;33m--> #{message}\e[00m"
end
task :server do
info "Starting local server"
sh "jekyll --server --auto --future"
end
-task :deploy => [ :update_git_hooks ] do
- info "Deploying to AWS"
- sh "git push aws master"
+task :deploy => [ :update_remote_repo, :update_git_hooks ] do
+ info "Deploying to #{SITE_HOSTNAME}"
+end
+
+task :update_remote_repo do
+ info "Updating remote repository"
+ sh "git push #{SITE_HOSTNAME}:~/repo/mhack.git master"
end
task :update_git_hooks do
info "Updating git hooks"
- sh "scp _deploy/git-post-receive.sh mhack.com:~/repo/mhack.git/hooks/post-receive"
+ sh "scp _deploy/git-post-receive.sh direct.mhack.com:~/repo/mhack.git/hooks/post-receive"
end
|
marcoshack/marcoshack.github.io
|
c39ae42c16e1d8c6391f507b1d19c7c20c78e02d
|
gem versions updated
|
diff --git a/Gemfile b/Gemfile
index 0a89dbc..52f214e 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,12 +1,12 @@
-source :rubygems
+source "https://rubygems.org"
gem 'jekyll'
gem 'rake'
gem 'nokogiri'
# gsl needs native libraries:
#
# $ brew tap homebrew/versions
# $ brew install gsl114
#
gem 'gsl'
\ No newline at end of file
diff --git a/Gemfile.lock b/Gemfile.lock
index 69132ed..38a9cd8 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,38 +1,48 @@
GEM
- remote: http://rubygems.org/
+ remote: https://rubygems.org/
specs:
classifier (1.3.3)
fast-stemmer (>= 1.0.0)
+ colorator (0.1)
+ commander (4.1.3)
+ highline (~> 1.6.11)
directory_watcher (1.4.1)
- fast-stemmer (1.0.1)
- gsl (1.14.7)
+ fast-stemmer (1.0.2)
+ gsl (1.15.3)
narray (>= 0.5.9)
- jekyll (0.12.0)
+ highline (1.6.19)
+ jekyll (1.0.3)
classifier (~> 1.3)
- directory_watcher (~> 1.1)
- kramdown (~> 0.13.4)
+ colorator (~> 0.1)
+ commander (~> 4.1.3)
+ directory_watcher (~> 1.4.1)
+ kramdown (~> 1.0.2)
liquid (~> 2.3)
maruku (~> 0.5)
- pygments.rb (~> 0.3.2)
- kramdown (0.13.8)
- liquid (2.4.1)
+ pygments.rb (~> 0.5.0)
+ safe_yaml (~> 0.7.0)
+ kramdown (1.0.2)
+ liquid (2.5.0)
maruku (0.6.1)
syntax (>= 1.0.0)
- narray (0.6.0.4)
- nokogiri (1.5.6)
+ mini_portile (0.5.0)
+ narray (0.6.0.8)
+ nokogiri (1.6.0)
+ mini_portile (~> 0.5.0)
posix-spawn (0.3.6)
- pygments.rb (0.3.7)
+ pygments.rb (0.5.1)
posix-spawn (~> 0.3.6)
yajl-ruby (~> 1.1.0)
- rake (10.0.3)
+ rake (10.1.0)
+ safe_yaml (0.7.1)
syntax (1.0.0)
yajl-ruby (1.1.0)
PLATFORMS
ruby
DEPENDENCIES
gsl
jekyll
nokogiri
rake
|
marcoshack/marcoshack.github.io
|
b55097c6f78158492f1a0ecd4439ae1e78d61744
|
replaced broken sitemap generator plugin
|
diff --git a/_plugins/generate_sitemap.rb b/_plugins/generate_sitemap.rb
new file mode 100644
index 0000000..bb683b8
--- /dev/null
+++ b/_plugins/generate_sitemap.rb
@@ -0,0 +1,154 @@
+# Jekyll sitemap page generator.
+# http://recursive-design.com/projects/jekyll-plugins/
+#
+# Version: 0.2.4 (201210160037)
+#
+# Copyright (c) 2010 Dave Perrett, http://recursive-design.com/
+# Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
+#
+# A generator that creates a sitemap.xml page for jekyll sites, suitable for submission to
+# google etc.
+#
+# To use it, simply drop this script into the _plugins directory of your Jekyll site.
+#
+# When you compile your jekyll site, this plugin will loop through the list of pages in your
+# site, and generate an entry in sitemap.xml for each one.
+
+require 'pathname'
+
+module Jekyll
+
+
+ # Monkey-patch an accessor for a page's containing folder, since
+ # we need it to generate the sitemap.
+ class Page
+ def subfolder
+ @dir
+ end
+ end
+
+
+ # Sub-class Jekyll::StaticFile to allow recovery from unimportant exception
+ # when writing the sitemap file.
+ class StaticSitemapFile < StaticFile
+ def write(dest)
+ super(dest) rescue ArgumentError
+ true
+ end
+ end
+
+
+ # Generates a sitemap.xml file containing URLs of all pages and posts.
+ class SitemapGenerator < Generator
+ safe true
+ priority :low
+
+ # Generates the sitemap.xml file.
+ #
+ # +site+ is the global Site object.
+ def generate(site)
+ # Create the destination folder if necessary.
+ site_folder = site.config['destination']
+ unless File.directory?(site_folder)
+ p = Pathname.new(site_folder)
+ p.mkdir
+ end
+
+ # Write the contents of sitemap.xml.
+ File.open(File.join(site_folder, 'sitemap.xml'), 'w') do |f|
+ f.write(generate_header())
+ f.write(generate_content(site))
+ f.write(generate_footer())
+ f.close
+ end
+
+ # Add a static file entry for the zip file, otherwise Site::cleanup will remove it.
+ site.static_files << Jekyll::StaticSitemapFile.new(site, site.dest, '/', 'sitemap.xml')
+ end
+
+ private
+
+ # Returns the XML header.
+ def generate_header
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"
+ end
+
+ # Returns a string containing the the XML entries.
+ #
+ # +site+ is the global Site object.
+ def generate_content(site)
+ result = ''
+
+ # First, try to find any stand-alone pages.
+ site.pages.each { |page|
+ path = page.subfolder + '/' + page.name
+
+ # Skip files that don't exist yet (e.g. paginator pages)
+ next unless FileTest.exist?(path)
+
+ mod_date = File.mtime(site.source + path)
+
+ # Use the user-specified permalink if one is given.
+ if page.permalink
+ path = page.permalink
+ else
+ # Be smart about the output filename.
+ path.gsub!(/.md$/, '.html')
+ end
+
+ # Ignore SASS, SCSS, and CSS files
+ next if path =~ /.(sass|scss|css)$/
+
+ # Remove the trailing 'index.html' if there is one, and just output the folder name.
+ path = path[0..-11] if path =~ /\/index.html$/
+
+ result += entry(path, mod_date, get_attrs(page), site) unless path =~ /error/
+ }
+
+ # Next, find all the posts.
+ posts = site.site_payload['site']['posts']
+ for post in posts do
+ url = post.url
+ url = '/' + url unless url =~ /^\//
+ url = url[0..-11] if url=~/\/index.html$/
+ result += entry(url, post.date, get_attrs(post), site)
+ end
+
+ result
+ end
+
+ def get_attrs( page )
+ attrs = Hash.new
+ attrs[:changefreq] = page.data['changefreq'] if page.data.has_key?('changefreq')
+ attrs[:priority] = page.data['priority'] if page.data.has_key?('priority')
+ attrs
+ end
+
+ # Returns the XML footer.
+ def generate_footer
+ "\n</urlset>"
+ end
+
+ # Creates an XML entry from the given path and date.
+ #
+ # +path+ is the URL path to the page.
+ # +date+ is the date the file was modified (in the case of regular pages), or published (for blog posts).
+ # +changefreq+ is the frequency with which the page is expected to change (this information is used by
+ # e.g. the Googlebot). This may be specified in the page's YAML front matter. If it is not set, nothing
+ # is output for this property.
+ def entry(path, date, attrs, site)
+ # Remove the trailing slash from the baseurl if it is present, for consistency.
+ baseurl = site.config['baseurl']
+ baseurl = baseurl[0..-2] if baseurl=~/\/$/
+
+ "
+ <url>
+ <loc>#{baseurl}#{path}</loc>
+ <lastmod>#{date.strftime("%Y-%m-%d")}</lastmod>
+" + attrs.map { |k,v| " <#{k}>#{v}</#{k}>" }.join("\n") + "
+ </url>"
+ end
+
+ end
+
+end
diff --git a/_plugins/sitemap_generator.rb b/_plugins/sitemap_generator.rb
deleted file mode 100644
index 419ea30..0000000
--- a/_plugins/sitemap_generator.rb
+++ /dev/null
@@ -1,308 +0,0 @@
-# Sitemap.xml Generator is a Jekyll plugin that generates a sitemap.xml file by
-# traversing all of the available posts and pages.
-#
-# How To Use:
-# 1.) Copy source file into your _plugins folder within your Jekyll project.
-# 2.) Change MY_URL to reflect your domain name.
-# 3.) Change SITEMAP_FILE_NAME if you want your sitemap to be called something
-# other than sitemap.xml.
-# 4.) Change the PAGES_INCLUDE_POSTS list to include any pages that are looping
-# through your posts (e.g. "index.html", "archive.html", etc.). This will
-# ensure that right after you make a new post, the last modified date will
-# be updated to reflect the new post.
-# 5.) Run Jekyll: jekyll --server to re-generate your site.
-# 6.) A sitemap.xml should be included in your _site folder.
-#
-# Customizations:
-# 1.) If there are any files you don't want included in the sitemap, add them
-# to the EXCLUDED_FILES list. The name should match the name of the source
-# file.
-# 2.) If you want to include the optional changefreq and priority attributes,
-# simply include custom variables in the YAML Front Matter of that file.
-# The names of these custom variables are defined below in the
-# CHANGE_FREQUENCY_CUSTOM_VARIABLE_NAME and PRIORITY_CUSTOM_VARIABLE_NAME
-# constants.
-#
-# Notes:
-# 1.) The last modified date is determined by the latest from the following:
-# system modified date of the page or post, system modified date of
-# included layout, system modified date of included layout within that
-# layout, ...
-#
-# Author: Michael Levin
-# Site: http://www.kinnetica.com
-# Distributed Under A Creative Commons License
-# - http://creativecommons.org/licenses/by/3.0/
-
-require 'rexml/document'
-
-module Jekyll
-
- # Change MY_URL to reflect the site you are using
- MY_URL = "http://mhack.com"
-
- # Change SITEMAP_FILE_NAME if you would like your sitemap file
- # to be called something else
- SITEMAP_FILE_NAME = "sitemap.xml"
-
- # Any files to exclude from being included in the sitemap.xml
- EXCLUDED_FILES = ["atom.xml"]
-
- # Any files that include posts, so that when a new post is added, the last
- # modified date of these pages should take that into account
- PAGES_INCLUDE_POSTS = ["index.html"]
-
- # Custom variable names for changefreq and priority elements
- # These names are used within the YAML Front Matter of pages or posts
- # for which you want to include these properties
- CHANGE_FREQUENCY_CUSTOM_VARIABLE_NAME = "change_frequency"
- PRIORITY_CUSTOM_VARIABLE_NAME = "priority"
-
- class Post
- attr_accessor :name
-
- def full_path_to_source
- File.join(@base, @name)
- end
-
- def location_on_server
- "#{MY_URL}#{url}"
- end
- end
-
- class Page
- attr_accessor :name
-
- def full_path_to_source
- File.join(@base, @dir, @name)
- end
-
- def location_on_server
- location = "#{MY_URL}#{@dir}#{url}"
- location.gsub(/index.html$/, "")
- end
- end
-
- class Layout
- def full_path_to_source
- File.join(@base, @name)
- end
- end
-
- # Recover from strange exception when starting server without --auto
- class SitemapFile < StaticFile
- def write(dest)
- begin
- super(dest)
- rescue
- end
-
- true
- end
- end
-
- class SitemapGenerator < Generator
-
- # Valid values allowed by sitemap.xml spec for change frequencies
- VALID_CHANGE_FREQUENCY_VALUES = ["always", "hourly", "daily", "weekly",
- "monthly", "yearly", "never"]
-
- # Goes through pages and posts and generates sitemap.xml file
- #
- # Returns nothing
- def generate(site)
- sitemap = REXML::Document.new << REXML::XMLDecl.new("1.0", "UTF-8")
-
- urlset = REXML::Element.new "urlset"
- urlset.add_attribute("xmlns",
- "http://www.sitemaps.org/schemas/sitemap/0.9")
-
- @last_modified_post_date = fill_posts(site, urlset)
- fill_pages(site, urlset)
-
- sitemap.add_element(urlset)
-
- # File I/O: create sitemap.xml file and write out pretty-printed XML
- file = File.new(File.join(site.dest, SITEMAP_FILE_NAME), "w")
- formatter = REXML::Formatters::Pretty.new(4)
- formatter.compact = true
- formatter.write(sitemap, file)
- file.close
-
- # Keep the sitemap.xml file from being cleaned by Jekyll
- site.static_files << Jekyll::SitemapFile.new(site, site.dest, "/", SITEMAP_FILE_NAME)
- end
-
- # Create url elements for all the posts and find the date of the latest one
- #
- # Returns last_modified_date of latest post
- def fill_posts(site, urlset)
- last_modified_date = nil
- site.posts.each do |post|
- if !excluded?(post.name)
- url = fill_url(site, post)
- urlset.add_element(url)
- end
-
- path = post.full_path_to_source
- date = File.mtime(path)
- last_modified_date = date if last_modified_date == nil or date > last_modified_date
- end
-
- last_modified_date
- end
-
- # Create url elements for all the normal pages and find the date of the
- # index to use with the pagination pages
- #
- # Returns last_modified_date of index page
- def fill_pages(site, urlset)
- site.pages.each do |page|
- if !excluded?(page.name)
- path = page.full_path_to_source
- if File.exists?(path)
- url = fill_url(site, page)
- urlset.add_element(url)
- end
- end
- end
- end
-
- # Fill data of each URL element: location, last modified,
- # change frequency (optional), and priority.
- #
- # Returns url REXML::Element
- def fill_url(site, page_or_post)
- url = REXML::Element.new "url"
-
- loc = fill_location(page_or_post)
- url.add_element(loc)
-
- lastmod = fill_last_modified(site, page_or_post)
- url.add_element(lastmod) if lastmod
-
- if (page_or_post.data[CHANGE_FREQUENCY_CUSTOM_VARIABLE_NAME])
- change_frequency =
- page_or_post.data[CHANGE_FREQUENCY_CUSTOM_VARIABLE_NAME].downcase
-
- if (valid_change_frequency?(change_frequency))
- changefreq = REXML::Element.new "changefreq"
- changefreq.text = change_frequency
- url.add_element(changefreq)
- else
- puts "ERROR: Invalid Change Frequency In #{page_or_post.name}"
- end
- end
-
- if (page_or_post.data[PRIORITY_CUSTOM_VARIABLE_NAME])
- priority_value = page_or_post.data[PRIORITY_CUSTOM_VARIABLE_NAME]
- if valid_priority?(priority_value)
- priority = REXML::Element.new "priority"
- priority.text = page_or_post.data[PRIORITY_CUSTOM_VARIABLE_NAME]
- url.add_element(priority)
- else
- puts "ERROR: Invalid Priority In #{page_or_post.name}"
- end
- end
-
- url
- end
-
- # Get URL location of page or post
- #
- # Returns the location of the page or post
- def fill_location(page_or_post)
- loc = REXML::Element.new "loc"
- loc.text = page_or_post.location_on_server
-
- loc
- end
-
- # Fill lastmod XML element with the last modified date for the page or post.
- #
- # Returns lastmod REXML::Element or nil
- def fill_last_modified(site, page_or_post)
- path = page_or_post.full_path_to_source
-
- lastmod = REXML::Element.new "lastmod"
- date = File.mtime(path)
- latest_date = find_latest_date(date, site, page_or_post)
-
- if @last_modified_post_date == nil
- # This is a post
- lastmod.text = latest_date.iso8601
- else
- # This is a page
- if posts_included?(page_or_post.name)
- # We want to take into account the last post date
- final_date = greater_date(latest_date, @last_modified_post_date)
- lastmod.text = final_date.iso8601
- else
- lastmod.text = latest_date.iso8601
- end
- end
- lastmod
- end
-
- # Go through the page/post and any implemented layouts and get the latest
- # modified date
- #
- # Returns formatted output of latest date of page/post and any used layouts
- def find_latest_date(latest_date, site, page_or_post)
- layouts = site.layouts
- layout = layouts[page_or_post.data["layout"]]
- while layout
- path = layout.full_path_to_source
- date = File.mtime(path)
-
- latest_date = date if (date > latest_date)
-
- layout = layouts[layout.data["layout"]]
- end
-
- latest_date
- end
-
- # Which of the two dates is later
- #
- # Returns latest of two dates
- def greater_date(date1, date2)
- if (date1 >= date2)
- date1
- else
- date2
- end
- end
-
- # Is the page or post listed as something we want to exclude?
- #
- # Returns boolean
- def excluded?(name)
- EXCLUDED_FILES.include? name
- end
-
- def posts_included?(name)
- PAGES_INCLUDE_POSTS.include? name
- end
-
- # Is the change frequency value provided valid according to the spec
- #
- # Returns boolean
- def valid_change_frequency?(change_frequency)
- VALID_CHANGE_FREQUENCY_VALUES.include? change_frequency
- end
-
- # Is the priority value provided valid according to the spec
- #
- # Returns boolean
- def valid_priority?(priority)
- begin
- priority_val = Float(priority)
- return true if priority_val >= 0.0 and priority_val <= 1.0
- rescue ArgumentError
- end
-
- false
- end
- end
-end
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
78ae4b84126e276b2f227fe0bab0e4f8ba01d764
|
avoid /favicon.ico requests
|
diff --git a/_layouts/default.html b/_layouts/default.html
index 214aed6..839fcc2 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,37 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
<title>{{ page.title }} {{ site.title_sufix }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/assets/css/bootstrap.css" rel="stylesheet">
<link href="/assets/css/style.css" rel="stylesheet">
+ <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
<br/>
<br/>
<div class="container">
<div class="row">
<div class="span8">
{{ content }}
</div>
{% include sidebar.html %}
</div>
</div>
{% include footer.html %}
<script src="/assets/js/jquery-1.9.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
</body>
</html>
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
433d643e20533cdc2d332a9b81084ef6a1c4fc67
|
disable index for empty directories
|
diff --git a/.htaccess b/.htaccess
index 8ab4a3e..736fac2 100644
--- a/.htaccess
+++ b/.htaccess
@@ -1,23 +1,25 @@
<If "%{HTTP_HOST} != 'mhack.com'">
RedirectMatch permanent /(.*) http://mhack.com/$1
</If>
+Options -Indexes
+
RedirectPermanent /2012/10/java-jdk-15-no-os-x-lion-e-mountain-lion.html /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion.html
RedirectPermanent /2012/08/mongo-on-rails-no-mongodb-sao-paulo.html /2012/09/mongo-on-rails-mongodb-sao-paulo.html
RedirectPermanent /2010/08/monitoracao-da-jvm-via-jmx-e-snmp.html /2012/05/monitoracao-jvm-com-jmx-e-snmp.html
RedirectPermanent /2009/10/japan-linux-symposium-e-lancamento-do.html /2009/10/japan-linux-symposium-lancamento-windows7.html
RedirectPermanent /2009/06/definicao-de-cloud-computing-pelo-nist.html /2009/06/definicao-de-cloud-computing-nist.html
RedirectPermanent /2009/05/amazon-web-services-leva-educacao-as.html /2009/05/amazon-web-services-leva-a-educacao-as-nuvens.html
RedirectPermanent /2008/12/segunda-via-do-documento-do-carro-em.html /2008/12/segunda-via-documento-carro-sao-paulo.html
RedirectPermanent /2012/12/jmeter-reports/ /2012/12/jmeter-reports.html
RedirectPermanent /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion/ /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion.html
RedirectPermanent /2012/09/mongo-on-rails-mongodb-sao-paulo/ /2012/09/mongo-on-rails-mongodb-sao-paulo.html
RedirectPermanent /2012/05/monitoracao-jvm-com-jmx-e-snmp/ /2012/05/monitoracao-jvm-com-jmx-e-snmp.html
RedirectPermanent /2010/01/campus-party-2010-dia-1/ /2010/01/campus-party-2010-dia-1.html
RedirectPermanent /2009/10/japan-linux-symposium-lancamento-windows7/ /2009/10/japan-linux-symposium-lancamento-windows7.html
RedirectPermanent /2009/06/definicao-de-cloud-computing-nist/ /2009/06/definicao-de-cloud-computing-nist.html
RedirectPermanent /2009/05/amazon-web-services-leva-a-educacao-as-nuvens/ /2009/05/amazon-web-services-leva-a-educacao-as-nuvens.html
RedirectPermanent /2009/03/ip-communications-2008/ /2009/03/ip-communications-2008.html
RedirectPermanent /2008/12/segunda-via-documento-carro-sao-paulo/ /2008/12/segunda-via-documento-carro-sao-paulo.html
RedirectPermanent /contato /contato.html
-RedirectPermanent /2009/12/o-ze-o-git-e-o-github/ /2009/12/o-ze-o-git-e-o-github.html
\ No newline at end of file
+RedirectPermanent /2009/12/o-ze-o-git-e-o-github/ /2009/12/o-ze-o-git-e-o-github.html
|
marcoshack/marcoshack.github.io
|
4ba7144f8baed3774d7dfbba272f244c821841a4
|
mijor change to traceroute post
|
diff --git a/_posts/2013-02-09-traceroute-216-81-59-173.md b/_posts/2013-02-09-traceroute-216-81-59-173.md
index 2bd8b96..c2e161e 100644
--- a/_posts/2013-02-09-traceroute-216-81-59-173.md
+++ b/_posts/2013-02-09-traceroute-216-81-59-173.md
@@ -1,93 +1,93 @@
---
layout: post
title: "traceroute 216.81.59.173"
description: "traceroute 216.81.59.173, may the Force be with you"
image: network1guy.png
date: 2013-02-10 0:58:00 UTC
categories: [ networking ]
-tags: [ traceroute, tcp-ip, start-wars ]
+tags: [ traceroute, 216.81.59.173, tcp-ip, start-wars ]
---
-Hoje começou a aparecer nas redes sociais um tal `traceroute 216.81.59.173`, principalmente na timeline dos nerds de plantão. A brincadeira me fez lembra do meu velho exemplar do [TCP/IP Illustrated, Volume 1](http://books.google.com.br/books/about/Tcp_Ip_Illustrated.html?id=-btNds68w84C&redir_esc=y), companheiro inseparável de muitas noites de estudo no inÃcio da minha carreira.
+Recentemente começou a aparecer nas redes sociais um tal `traceroute 216.81.59.173`, principalmente na timeline dos nerds de plantão. A brincadeira me fez lembra do meu velho exemplar do [TCP/IP Illustrated, Volume 1](http://books.google.com.br/books/about/Tcp_Ip_Illustrated.html?id=-btNds68w84C&redir_esc=y), companheiro inseparável de muitas noites de estudo no inÃcio da minha carreira.
Se você abrir um terminal e executar esse comando vai acompanhar uma breve narrativa do episódio IV do *Star Wars*, subtÃtulo *A New Hope*. Se não tiver acesso a um terminal agora, ou não fazer ideia do que seja um, segue a transcrição do output, a diversão começa na linha, ou melhor, no hop 12 (explicação continua abaixo):
traceroute to 216.81.59.173 (216.81.59.173), 60 hops max, 60 byte packets
1 * * *
2 core-cce-b.uspnet.usp.br (143.107.255.225) 0.286 ms 0.498 ms 0.481 ms
3 border1.uspnet.usp.br (143.107.251.29) 0.455 ms 0.438 ms 0.419 ms
4 border1.uspnet.usp.br (143.107.151.161) 0.388 ms 0.369 ms 0.348 ms
5 ansp.ptta.ansp.br (200.136.37.1) 21.547 ms 22.028 ms 22.501 ms
6 198.32.252.141 (198.32.252.141) 112.654 ms 112.596 ms 112.558 ms
7 198.32.252.121 (198.32.252.121) 112.772 ms 112.758 ms 112.740 ms
8 nota.he.net (198.32.124.176) 116.449 ms 116.433 ms 116.660 ms
9 10gigabitethernet1-1.core1.atl1.he.net (72.52.92.53) 129.879 ms 136.125 ms 131.046 ms
10 216.66.0.26 (216.66.0.26) 128.375 ms 130.013 ms 128.436 ms
11 * * *
12 Episode.IV (206.214.251.1) 168.720 ms 167.804 ms 167.252 ms
13 A.NEW.HOPE (206.214.251.6) 165.508 ms 167.729 ms 170.453 ms
14 It.is.a.period.of.civil.war (206.214.251.9) 169.027 ms 167.939 ms 170.261 ms
15 Rebel.spaceships (206.214.251.14) 172.063 ms 165.807 ms 170.324 ms
16 striking.from.a.hidden.base (206.214.251.17) 167.850 ms 168.486 ms 168.580 ms
17 have.won.their.first.victory (206.214.251.22) 166.301 ms 166.834 ms 167.842 ms
18 against.the.evil.Galactic.Empire (206.214.251.25) 164.308 ms 166.784 ms 164.027 ms
19 During.the.battle (206.214.251.30) 165.552 ms 163.835 ms 165.087 ms
20 Rebel.spies.managed (206.214.251.33) 165.282 ms 166.572 ms 170.600 ms
21 to.steal.secret.plans (206.214.251.38) 167.065 ms 166.779 ms 166.830 ms
22 to.the.Empires.ultimate.weapon (206.214.251.41) 170.259 ms 165.588 ms 167.586 ms
23 the.DEATH.STAR (206.214.251.46) 172.321 ms 170.072 ms 169.074 ms
24 an.armored.space.station (206.214.251.49) 168.072 ms 168.330 ms 168.039 ms
25 with.enough.power.to (206.214.251.54) 167.302 ms 167.294 ms 170.548 ms
26 destroy.an.entire.planet (206.214.251.57) 172.318 ms 172.059 ms 175.301 ms
27 Pursued.by.the.Empires (206.214.251.62) 165.316 ms 166.312 ms 165.352 ms
28 sinister.agents (206.214.251.65) 170.036 ms 168.047 ms 173.518 ms
29 Princess.Leia.races.home (206.214.251.70) 172.530 ms 172.837 ms 169.583 ms
30 aboard.her.starship (206.214.251.73) 172.313 ms 169.312 ms 170.563 ms
31 custodian.of.the.stolen.plans (206.214.251.78) 167.833 ms 170.021 ms 167.572 ms
32 that.can.save.her (206.214.251.81) 164.322 ms 167.323 ms 167.041 ms
33 people.and.restore (206.214.251.86) 167.090 ms 168.578 ms 171.545 ms
34 freedom.to.the.galaxy (206.214.251.89) 169.540 ms 170.818 ms 168.773 ms
35 0-------------------0 (206.214.251.94) 168.555 ms 167.545 ms 168.317 ms
36 0------------------0 (206.214.251.97) 174.582 ms 173.029 ms 173.281 ms
37 0-----------------0 (206.214.251.102) 167.553 ms 170.065 ms 173.312 ms
38 0----------------0 (206.214.251.105) 168.792 ms 169.281 ms 171.263 ms
39 0---------------0 (206.214.251.110) 169.041 ms 169.077 ms 168.319 ms
40 0--------------0 (206.214.251.113) 167.067 ms 164.551 ms 169.831 ms
41 0-------------0 (206.214.251.118) 164.025 ms 168.297 ms 171.813 ms
42 0------------0 (206.214.251.121) 171.812 ms 169.807 ms 167.839 ms
43 0-----------0 (206.214.251.126) 168.283 ms 170.559 ms 169.083 ms
44 0----------0 (206.214.251.129) 167.549 ms 166.817 ms 165.801 ms
45 0---------0 (206.214.251.134) 170.795 ms 171.555 ms 178.795 ms
46 0--------0 (206.214.251.137) 173.055 ms 173.551 ms 172.317 ms
47 0-------0 (206.214.251.142) 171.094 ms 174.834 ms 175.022 ms
48 0------0 (206.214.251.145) 167.540 ms 174.764 ms 171.814 ms
49 0-----0 (206.214.251.150) 176.053 ms * *
50 0----0 (206.214.251.153) 171.321 ms 172.058 ms 169.066 ms
51 0---0 (206.214.251.158) 171.304 ms 171.034 ms 172.535 ms
52 0--0 (206.214.251.161) 171.538 ms 169.066 ms 172.297 ms
53 0-0 (206.214.251.166) 172.799 ms 174.304 ms 172.073 ms
54 00 (206.214.251.169) 173.508 ms 167.787 ms 174.312 ms
55 I (206.214.251.174) 173.798 ms 173.553 ms 172.784 ms
56 By.Ryan.Werber (206.214.251.177) 171.306 ms 171.571 ms 172.280 ms
57 When.CCIEs.Get.Bored (206.214.251.182) 175.548 ms 175.313 ms 171.303 ms
58 read.more.at.beaglenetworks.net (206.214.251.185) 171.546 ms * 170.319 ms
59 FIN (206.214.251.190) 170.330 ms * *
Pra quem não sabe o que o `traceroute` faz, muito menos o que significa esses pequenos trechos de texto com pontos no lugar de espaços, seguido de um monte de números em cada linha, não tem graça nenhuma, realmente. Mas é exatamente aà que mora toda a beleza da coisa.
O traceroute é uma ferramenta de testes para redes TCP/IP e, como o nome sugere, exibe o *caminho* a partir do computador onde está sendo executado, até o endereço de destino, no caso o 216.81.59.173. O mecanismo utilizado pra mapear esse caminho não é tão relevante aqui, basta saber que o traceroute envia pacotes especialmente preparados para cada equipamento no caminho para descobrir seu endereço e tempo de reposta. Se quiser saber mais detalhes comece pelo [artigo na wikipedia](http://en.wikipedia.org/wiki/Traceroute).
Cada linha mostrada acima representa um roteador no caminho entre seu computador e o computador de destino. [Roteador](http://en.wikipedia.org/wiki/Router_%28computing%29) é um equipamento que conecta duas ou mais redes, por exemplo esse popularmente conhecido *roteador Wi-Fi* que você tem aà na sua casa, ele conecta a rede da operadora com a sua rede interna, no caso uma rede sem fio. Depois, dentro da operadora existem algumas dezenas ou centenas de roteadores que se conectam a redes de outras operadoras, e assim vai, formando uma rede mundial também conhecida como Internet :)
Cada linha do traceroute é formada pelo *hostname*, o endereço IP associado a esse nome, e os tempos de reposta dos pacotes enviados pelo traceroute. Como você pode deduzir, a história é contada através do *hostname* de cada roteador, que nada mais é que um nome amigável dado a cada equipamento de forma a facilitar sua identificação pelos humanos.
Esse hostname é descoberto através de uma consulta a um serviço de nomes, chamado DNS (*Domain Name System*), o mesmo que transforma um endereço como *www.google.com* em um endereço IP que os computadores utilizam para se comunicar. Mas no caso do traceroute a operação é inversa, pois ele descobre o endereço IP de cada roteador e o traduz para um nome. Essa operação é chamada de *DNS reverso*, e é realizada através de registros no domÃnio especial *.in-addr.arpa*.
Ou seja, o autor da brincadeira, [Mr. Ryan Werber](http://www.linkedin.com/in/rwerber), registrou o *nome reverso* de cada endereço IP que faz parte do caminho até o host 216.81.59.173. Por exemplo, ele registro ou nome *Episode.IV* para o IP 206.214.251.1, o nome "A.NEW.HOPE" para o endereço 206.214.251.6 e assim por diante.
Claro que esse ambiente foi especialmente preparado para contar a história, pois dificilmente são necessários tantos *hops* (roteadores no caminho) para se alcançar um destino. Repare que todos os endereços do caminho começam com 206.214.251.x, que faz parte de uma rede controlada pela [Epik Networks, Inc.](http://www.epiknetworks.com/).
Esse trabalho todo pra contar essa história tão querida é o que torna a brincadeira especial.
May the Force be with you!
|
marcoshack/marcoshack.github.io
|
4fa4699b5f5ee9565e8efa8c266f772cc2878071
|
sitemap generator
|
diff --git a/_plugins/sitemap_generator.rb b/_plugins/sitemap_generator.rb
new file mode 100644
index 0000000..419ea30
--- /dev/null
+++ b/_plugins/sitemap_generator.rb
@@ -0,0 +1,308 @@
+# Sitemap.xml Generator is a Jekyll plugin that generates a sitemap.xml file by
+# traversing all of the available posts and pages.
+#
+# How To Use:
+# 1.) Copy source file into your _plugins folder within your Jekyll project.
+# 2.) Change MY_URL to reflect your domain name.
+# 3.) Change SITEMAP_FILE_NAME if you want your sitemap to be called something
+# other than sitemap.xml.
+# 4.) Change the PAGES_INCLUDE_POSTS list to include any pages that are looping
+# through your posts (e.g. "index.html", "archive.html", etc.). This will
+# ensure that right after you make a new post, the last modified date will
+# be updated to reflect the new post.
+# 5.) Run Jekyll: jekyll --server to re-generate your site.
+# 6.) A sitemap.xml should be included in your _site folder.
+#
+# Customizations:
+# 1.) If there are any files you don't want included in the sitemap, add them
+# to the EXCLUDED_FILES list. The name should match the name of the source
+# file.
+# 2.) If you want to include the optional changefreq and priority attributes,
+# simply include custom variables in the YAML Front Matter of that file.
+# The names of these custom variables are defined below in the
+# CHANGE_FREQUENCY_CUSTOM_VARIABLE_NAME and PRIORITY_CUSTOM_VARIABLE_NAME
+# constants.
+#
+# Notes:
+# 1.) The last modified date is determined by the latest from the following:
+# system modified date of the page or post, system modified date of
+# included layout, system modified date of included layout within that
+# layout, ...
+#
+# Author: Michael Levin
+# Site: http://www.kinnetica.com
+# Distributed Under A Creative Commons License
+# - http://creativecommons.org/licenses/by/3.0/
+
+require 'rexml/document'
+
+module Jekyll
+
+ # Change MY_URL to reflect the site you are using
+ MY_URL = "http://mhack.com"
+
+ # Change SITEMAP_FILE_NAME if you would like your sitemap file
+ # to be called something else
+ SITEMAP_FILE_NAME = "sitemap.xml"
+
+ # Any files to exclude from being included in the sitemap.xml
+ EXCLUDED_FILES = ["atom.xml"]
+
+ # Any files that include posts, so that when a new post is added, the last
+ # modified date of these pages should take that into account
+ PAGES_INCLUDE_POSTS = ["index.html"]
+
+ # Custom variable names for changefreq and priority elements
+ # These names are used within the YAML Front Matter of pages or posts
+ # for which you want to include these properties
+ CHANGE_FREQUENCY_CUSTOM_VARIABLE_NAME = "change_frequency"
+ PRIORITY_CUSTOM_VARIABLE_NAME = "priority"
+
+ class Post
+ attr_accessor :name
+
+ def full_path_to_source
+ File.join(@base, @name)
+ end
+
+ def location_on_server
+ "#{MY_URL}#{url}"
+ end
+ end
+
+ class Page
+ attr_accessor :name
+
+ def full_path_to_source
+ File.join(@base, @dir, @name)
+ end
+
+ def location_on_server
+ location = "#{MY_URL}#{@dir}#{url}"
+ location.gsub(/index.html$/, "")
+ end
+ end
+
+ class Layout
+ def full_path_to_source
+ File.join(@base, @name)
+ end
+ end
+
+ # Recover from strange exception when starting server without --auto
+ class SitemapFile < StaticFile
+ def write(dest)
+ begin
+ super(dest)
+ rescue
+ end
+
+ true
+ end
+ end
+
+ class SitemapGenerator < Generator
+
+ # Valid values allowed by sitemap.xml spec for change frequencies
+ VALID_CHANGE_FREQUENCY_VALUES = ["always", "hourly", "daily", "weekly",
+ "monthly", "yearly", "never"]
+
+ # Goes through pages and posts and generates sitemap.xml file
+ #
+ # Returns nothing
+ def generate(site)
+ sitemap = REXML::Document.new << REXML::XMLDecl.new("1.0", "UTF-8")
+
+ urlset = REXML::Element.new "urlset"
+ urlset.add_attribute("xmlns",
+ "http://www.sitemaps.org/schemas/sitemap/0.9")
+
+ @last_modified_post_date = fill_posts(site, urlset)
+ fill_pages(site, urlset)
+
+ sitemap.add_element(urlset)
+
+ # File I/O: create sitemap.xml file and write out pretty-printed XML
+ file = File.new(File.join(site.dest, SITEMAP_FILE_NAME), "w")
+ formatter = REXML::Formatters::Pretty.new(4)
+ formatter.compact = true
+ formatter.write(sitemap, file)
+ file.close
+
+ # Keep the sitemap.xml file from being cleaned by Jekyll
+ site.static_files << Jekyll::SitemapFile.new(site, site.dest, "/", SITEMAP_FILE_NAME)
+ end
+
+ # Create url elements for all the posts and find the date of the latest one
+ #
+ # Returns last_modified_date of latest post
+ def fill_posts(site, urlset)
+ last_modified_date = nil
+ site.posts.each do |post|
+ if !excluded?(post.name)
+ url = fill_url(site, post)
+ urlset.add_element(url)
+ end
+
+ path = post.full_path_to_source
+ date = File.mtime(path)
+ last_modified_date = date if last_modified_date == nil or date > last_modified_date
+ end
+
+ last_modified_date
+ end
+
+ # Create url elements for all the normal pages and find the date of the
+ # index to use with the pagination pages
+ #
+ # Returns last_modified_date of index page
+ def fill_pages(site, urlset)
+ site.pages.each do |page|
+ if !excluded?(page.name)
+ path = page.full_path_to_source
+ if File.exists?(path)
+ url = fill_url(site, page)
+ urlset.add_element(url)
+ end
+ end
+ end
+ end
+
+ # Fill data of each URL element: location, last modified,
+ # change frequency (optional), and priority.
+ #
+ # Returns url REXML::Element
+ def fill_url(site, page_or_post)
+ url = REXML::Element.new "url"
+
+ loc = fill_location(page_or_post)
+ url.add_element(loc)
+
+ lastmod = fill_last_modified(site, page_or_post)
+ url.add_element(lastmod) if lastmod
+
+ if (page_or_post.data[CHANGE_FREQUENCY_CUSTOM_VARIABLE_NAME])
+ change_frequency =
+ page_or_post.data[CHANGE_FREQUENCY_CUSTOM_VARIABLE_NAME].downcase
+
+ if (valid_change_frequency?(change_frequency))
+ changefreq = REXML::Element.new "changefreq"
+ changefreq.text = change_frequency
+ url.add_element(changefreq)
+ else
+ puts "ERROR: Invalid Change Frequency In #{page_or_post.name}"
+ end
+ end
+
+ if (page_or_post.data[PRIORITY_CUSTOM_VARIABLE_NAME])
+ priority_value = page_or_post.data[PRIORITY_CUSTOM_VARIABLE_NAME]
+ if valid_priority?(priority_value)
+ priority = REXML::Element.new "priority"
+ priority.text = page_or_post.data[PRIORITY_CUSTOM_VARIABLE_NAME]
+ url.add_element(priority)
+ else
+ puts "ERROR: Invalid Priority In #{page_or_post.name}"
+ end
+ end
+
+ url
+ end
+
+ # Get URL location of page or post
+ #
+ # Returns the location of the page or post
+ def fill_location(page_or_post)
+ loc = REXML::Element.new "loc"
+ loc.text = page_or_post.location_on_server
+
+ loc
+ end
+
+ # Fill lastmod XML element with the last modified date for the page or post.
+ #
+ # Returns lastmod REXML::Element or nil
+ def fill_last_modified(site, page_or_post)
+ path = page_or_post.full_path_to_source
+
+ lastmod = REXML::Element.new "lastmod"
+ date = File.mtime(path)
+ latest_date = find_latest_date(date, site, page_or_post)
+
+ if @last_modified_post_date == nil
+ # This is a post
+ lastmod.text = latest_date.iso8601
+ else
+ # This is a page
+ if posts_included?(page_or_post.name)
+ # We want to take into account the last post date
+ final_date = greater_date(latest_date, @last_modified_post_date)
+ lastmod.text = final_date.iso8601
+ else
+ lastmod.text = latest_date.iso8601
+ end
+ end
+ lastmod
+ end
+
+ # Go through the page/post and any implemented layouts and get the latest
+ # modified date
+ #
+ # Returns formatted output of latest date of page/post and any used layouts
+ def find_latest_date(latest_date, site, page_or_post)
+ layouts = site.layouts
+ layout = layouts[page_or_post.data["layout"]]
+ while layout
+ path = layout.full_path_to_source
+ date = File.mtime(path)
+
+ latest_date = date if (date > latest_date)
+
+ layout = layouts[layout.data["layout"]]
+ end
+
+ latest_date
+ end
+
+ # Which of the two dates is later
+ #
+ # Returns latest of two dates
+ def greater_date(date1, date2)
+ if (date1 >= date2)
+ date1
+ else
+ date2
+ end
+ end
+
+ # Is the page or post listed as something we want to exclude?
+ #
+ # Returns boolean
+ def excluded?(name)
+ EXCLUDED_FILES.include? name
+ end
+
+ def posts_included?(name)
+ PAGES_INCLUDE_POSTS.include? name
+ end
+
+ # Is the change frequency value provided valid according to the spec
+ #
+ # Returns boolean
+ def valid_change_frequency?(change_frequency)
+ VALID_CHANGE_FREQUENCY_VALUES.include? change_frequency
+ end
+
+ # Is the priority value provided valid according to the spec
+ #
+ # Returns boolean
+ def valid_priority?(priority)
+ begin
+ priority_val = Float(priority)
+ return true if priority_val >= 0.0 and priority_val <= 1.0
+ rescue ArgumentError
+ end
+
+ false
+ end
+ end
+end
\ No newline at end of file
diff --git a/index.html b/index.html
index ea67d6d..9d51ead 100644
--- a/index.html
+++ b/index.html
@@ -1,26 +1,27 @@
---
layout: default
title: Home
+change_frequency: always
---
<br />
{% for post in paginator.posts %}
<div class="row">
<div class="span2 hidden-phone">
{% if post.image != nil %}
<img src="/images/{{ post.image }}" />
{% endif %}
</div>
<div class="span6">
<h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
<div class="post_excerpt">
<blockquote>
<p>{{ post.content | strip_html | truncatewords: 30 }}</p>
<small class="muted">{% include post_date.html %}</small>
</blockquote>
</div>
</div>
</div>
{% endfor %}
{% include pagination.html %}
|
marcoshack/marcoshack.github.io
|
06c7281b67d04887f5225ac432d1dd00b52dbe1a
|
traceroute 216.81.59.173
|
diff --git a/_posts/2013-02-09-traceroute-216-81-59-173.md b/_posts/2013-02-09-traceroute-216-81-59-173.md
new file mode 100644
index 0000000..2bd8b96
--- /dev/null
+++ b/_posts/2013-02-09-traceroute-216-81-59-173.md
@@ -0,0 +1,93 @@
+---
+layout: post
+title: "traceroute 216.81.59.173"
+description: "traceroute 216.81.59.173, may the Force be with you"
+image: network1guy.png
+date: 2013-02-10 0:58:00 UTC
+categories: [ networking ]
+tags: [ traceroute, tcp-ip, start-wars ]
+---
+
+Hoje começou a aparecer nas redes sociais um tal `traceroute 216.81.59.173`, principalmente na timeline dos nerds de plantão. A brincadeira me fez lembra do meu velho exemplar do [TCP/IP Illustrated, Volume 1](http://books.google.com.br/books/about/Tcp_Ip_Illustrated.html?id=-btNds68w84C&redir_esc=y), companheiro inseparável de muitas noites de estudo no inÃcio da minha carreira.
+
+Se você abrir um terminal e executar esse comando vai acompanhar uma breve narrativa do episódio IV do *Star Wars*, subtÃtulo *A New Hope*. Se não tiver acesso a um terminal agora, ou não fazer ideia do que seja um, segue a transcrição do output, a diversão começa na linha, ou melhor, no hop 12 (explicação continua abaixo):
+
+ traceroute to 216.81.59.173 (216.81.59.173), 60 hops max, 60 byte packets
+ 1 * * *
+ 2 core-cce-b.uspnet.usp.br (143.107.255.225) 0.286 ms 0.498 ms 0.481 ms
+ 3 border1.uspnet.usp.br (143.107.251.29) 0.455 ms 0.438 ms 0.419 ms
+ 4 border1.uspnet.usp.br (143.107.151.161) 0.388 ms 0.369 ms 0.348 ms
+ 5 ansp.ptta.ansp.br (200.136.37.1) 21.547 ms 22.028 ms 22.501 ms
+ 6 198.32.252.141 (198.32.252.141) 112.654 ms 112.596 ms 112.558 ms
+ 7 198.32.252.121 (198.32.252.121) 112.772 ms 112.758 ms 112.740 ms
+ 8 nota.he.net (198.32.124.176) 116.449 ms 116.433 ms 116.660 ms
+ 9 10gigabitethernet1-1.core1.atl1.he.net (72.52.92.53) 129.879 ms 136.125 ms 131.046 ms
+ 10 216.66.0.26 (216.66.0.26) 128.375 ms 130.013 ms 128.436 ms
+ 11 * * *
+ 12 Episode.IV (206.214.251.1) 168.720 ms 167.804 ms 167.252 ms
+ 13 A.NEW.HOPE (206.214.251.6) 165.508 ms 167.729 ms 170.453 ms
+ 14 It.is.a.period.of.civil.war (206.214.251.9) 169.027 ms 167.939 ms 170.261 ms
+ 15 Rebel.spaceships (206.214.251.14) 172.063 ms 165.807 ms 170.324 ms
+ 16 striking.from.a.hidden.base (206.214.251.17) 167.850 ms 168.486 ms 168.580 ms
+ 17 have.won.their.first.victory (206.214.251.22) 166.301 ms 166.834 ms 167.842 ms
+ 18 against.the.evil.Galactic.Empire (206.214.251.25) 164.308 ms 166.784 ms 164.027 ms
+ 19 During.the.battle (206.214.251.30) 165.552 ms 163.835 ms 165.087 ms
+ 20 Rebel.spies.managed (206.214.251.33) 165.282 ms 166.572 ms 170.600 ms
+ 21 to.steal.secret.plans (206.214.251.38) 167.065 ms 166.779 ms 166.830 ms
+ 22 to.the.Empires.ultimate.weapon (206.214.251.41) 170.259 ms 165.588 ms 167.586 ms
+ 23 the.DEATH.STAR (206.214.251.46) 172.321 ms 170.072 ms 169.074 ms
+ 24 an.armored.space.station (206.214.251.49) 168.072 ms 168.330 ms 168.039 ms
+ 25 with.enough.power.to (206.214.251.54) 167.302 ms 167.294 ms 170.548 ms
+ 26 destroy.an.entire.planet (206.214.251.57) 172.318 ms 172.059 ms 175.301 ms
+ 27 Pursued.by.the.Empires (206.214.251.62) 165.316 ms 166.312 ms 165.352 ms
+ 28 sinister.agents (206.214.251.65) 170.036 ms 168.047 ms 173.518 ms
+ 29 Princess.Leia.races.home (206.214.251.70) 172.530 ms 172.837 ms 169.583 ms
+ 30 aboard.her.starship (206.214.251.73) 172.313 ms 169.312 ms 170.563 ms
+ 31 custodian.of.the.stolen.plans (206.214.251.78) 167.833 ms 170.021 ms 167.572 ms
+ 32 that.can.save.her (206.214.251.81) 164.322 ms 167.323 ms 167.041 ms
+ 33 people.and.restore (206.214.251.86) 167.090 ms 168.578 ms 171.545 ms
+ 34 freedom.to.the.galaxy (206.214.251.89) 169.540 ms 170.818 ms 168.773 ms
+ 35 0-------------------0 (206.214.251.94) 168.555 ms 167.545 ms 168.317 ms
+ 36 0------------------0 (206.214.251.97) 174.582 ms 173.029 ms 173.281 ms
+ 37 0-----------------0 (206.214.251.102) 167.553 ms 170.065 ms 173.312 ms
+ 38 0----------------0 (206.214.251.105) 168.792 ms 169.281 ms 171.263 ms
+ 39 0---------------0 (206.214.251.110) 169.041 ms 169.077 ms 168.319 ms
+ 40 0--------------0 (206.214.251.113) 167.067 ms 164.551 ms 169.831 ms
+ 41 0-------------0 (206.214.251.118) 164.025 ms 168.297 ms 171.813 ms
+ 42 0------------0 (206.214.251.121) 171.812 ms 169.807 ms 167.839 ms
+ 43 0-----------0 (206.214.251.126) 168.283 ms 170.559 ms 169.083 ms
+ 44 0----------0 (206.214.251.129) 167.549 ms 166.817 ms 165.801 ms
+ 45 0---------0 (206.214.251.134) 170.795 ms 171.555 ms 178.795 ms
+ 46 0--------0 (206.214.251.137) 173.055 ms 173.551 ms 172.317 ms
+ 47 0-------0 (206.214.251.142) 171.094 ms 174.834 ms 175.022 ms
+ 48 0------0 (206.214.251.145) 167.540 ms 174.764 ms 171.814 ms
+ 49 0-----0 (206.214.251.150) 176.053 ms * *
+ 50 0----0 (206.214.251.153) 171.321 ms 172.058 ms 169.066 ms
+ 51 0---0 (206.214.251.158) 171.304 ms 171.034 ms 172.535 ms
+ 52 0--0 (206.214.251.161) 171.538 ms 169.066 ms 172.297 ms
+ 53 0-0 (206.214.251.166) 172.799 ms 174.304 ms 172.073 ms
+ 54 00 (206.214.251.169) 173.508 ms 167.787 ms 174.312 ms
+ 55 I (206.214.251.174) 173.798 ms 173.553 ms 172.784 ms
+ 56 By.Ryan.Werber (206.214.251.177) 171.306 ms 171.571 ms 172.280 ms
+ 57 When.CCIEs.Get.Bored (206.214.251.182) 175.548 ms 175.313 ms 171.303 ms
+ 58 read.more.at.beaglenetworks.net (206.214.251.185) 171.546 ms * 170.319 ms
+ 59 FIN (206.214.251.190) 170.330 ms * *
+
+
+Pra quem não sabe o que o `traceroute` faz, muito menos o que significa esses pequenos trechos de texto com pontos no lugar de espaços, seguido de um monte de números em cada linha, não tem graça nenhuma, realmente. Mas é exatamente aà que mora toda a beleza da coisa.
+
+O traceroute é uma ferramenta de testes para redes TCP/IP e, como o nome sugere, exibe o *caminho* a partir do computador onde está sendo executado, até o endereço de destino, no caso o 216.81.59.173. O mecanismo utilizado pra mapear esse caminho não é tão relevante aqui, basta saber que o traceroute envia pacotes especialmente preparados para cada equipamento no caminho para descobrir seu endereço e tempo de reposta. Se quiser saber mais detalhes comece pelo [artigo na wikipedia](http://en.wikipedia.org/wiki/Traceroute).
+
+Cada linha mostrada acima representa um roteador no caminho entre seu computador e o computador de destino. [Roteador](http://en.wikipedia.org/wiki/Router_%28computing%29) é um equipamento que conecta duas ou mais redes, por exemplo esse popularmente conhecido *roteador Wi-Fi* que você tem aà na sua casa, ele conecta a rede da operadora com a sua rede interna, no caso uma rede sem fio. Depois, dentro da operadora existem algumas dezenas ou centenas de roteadores que se conectam a redes de outras operadoras, e assim vai, formando uma rede mundial também conhecida como Internet :)
+
+Cada linha do traceroute é formada pelo *hostname*, o endereço IP associado a esse nome, e os tempos de reposta dos pacotes enviados pelo traceroute. Como você pode deduzir, a história é contada através do *hostname* de cada roteador, que nada mais é que um nome amigável dado a cada equipamento de forma a facilitar sua identificação pelos humanos.
+
+Esse hostname é descoberto através de uma consulta a um serviço de nomes, chamado DNS (*Domain Name System*), o mesmo que transforma um endereço como *www.google.com* em um endereço IP que os computadores utilizam para se comunicar. Mas no caso do traceroute a operação é inversa, pois ele descobre o endereço IP de cada roteador e o traduz para um nome. Essa operação é chamada de *DNS reverso*, e é realizada através de registros no domÃnio especial *.in-addr.arpa*.
+
+Ou seja, o autor da brincadeira, [Mr. Ryan Werber](http://www.linkedin.com/in/rwerber), registrou o *nome reverso* de cada endereço IP que faz parte do caminho até o host 216.81.59.173. Por exemplo, ele registro ou nome *Episode.IV* para o IP 206.214.251.1, o nome "A.NEW.HOPE" para o endereço 206.214.251.6 e assim por diante.
+
+Claro que esse ambiente foi especialmente preparado para contar a história, pois dificilmente são necessários tantos *hops* (roteadores no caminho) para se alcançar um destino. Repare que todos os endereços do caminho começam com 206.214.251.x, que faz parte de uma rede controlada pela [Epik Networks, Inc.](http://www.epiknetworks.com/).
+
+Esse trabalho todo pra contar essa história tão querida é o que torna a brincadeira especial.
+
+May the Force be with you!
diff --git a/images/network1guy.png b/images/network1guy.png
new file mode 100644
index 0000000..0a1f130
Binary files /dev/null and b/images/network1guy.png differ
|
marcoshack/marcoshack.github.io
|
bfbb7f2247dcbb8d595860c1b5dd78110cf96889
|
post info (date and author) refactored as a list
|
diff --git a/_layouts/post.html b/_layouts/post.html
index 2307f48..0b99844 100644
--- a/_layouts/post.html
+++ b/_layouts/post.html
@@ -1,35 +1,43 @@
---
layout: default
---
{% assign post = page %}
<!-- post header -->
<div class="page-header">
<h1><a href="{{ post.url }}">{{ post.title }}</a></h1>
- <small class="muted">{% include post_date.html %} | {% include author_name.html %}</small>
+ <ul class="post-info">
+ <li>{% include post_date.html %}</li>
+ <li class="muted">·</li>
+ <li>By {% include author_name.html %}</li>
+ </ul>
</div>
<div class="post">
{{ content }}
</div>
{% include facebook_div.html %}
{% include facebook_script.html %}
<br/> <!-- uhhhh -->
{% include disqus_div.html %}
{% include disqus_script.html %}
<hr class="bs-docs-separator">
<div class="row">
<div class="span8">
+ {% if post.previous != nil %}
<a href="{{ post.previous.url }}">
<span class="pull-left"><i class="icon-backward"></i> {{ post.previous.title }}</span>
</a>
+ {% endif %}
+ {% if post.next != nil %}
<a href="{{ post.next.url }}">
<span class="pull-right">{{ post.next.title }} <i class="icon-forward"></i></span>
</a>
+ {% endif %}
</div>
</div>
diff --git a/assets/css/style.css b/assets/css/style.css
index a30cafe..a87af02 100644
--- a/assets/css/style.css
+++ b/assets/css/style.css
@@ -1,24 +1,34 @@
/* Footer
-------------------------------------------------- */
.footer {
text-align: center;
padding: 30px 0;
margin-top: 70px;
border-top: 1px solid #e5e5e5;
background-color: #f5f5f5;
}
.footer p {
margin-bottom: 0;
color: #777;
}
.footer-links {
margin: 10px 0;
}
.footer-links li {
display: inline;
padding: 0 2px;
}
.footer-links li:first-child {
padding-left: 0;
}
+
+.post-info {
+ margin: 10px 0;
+}
+.post-info li {
+ font-size: 85%;
+ color: #999999;
+ display: inline;
+ padding: 0 2px;
+}
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
5cabbaecf67002d3751055ce75a19b019e6093e4
|
minor home layout fixes
|
diff --git a/_includes/footer.html b/_includes/footer.html
index 01bd639..cc73d52 100644
--- a/_includes/footer.html
+++ b/_includes/footer.html
@@ -1,16 +1,14 @@
<footer class="footer">
- <div class="container">
- <p>{{ site.copyright }}</p>
- <p>Powered by Open Source software:
- <a href="https://github.com/mojombo/jekyll">Jekyll</a>,
- <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> and much more.
- </p>
- <ul class="footer-links">
- <li><a href="https://github.com/{{ site.author.github }}/">GitHub</a></li>
- <li class="muted">·</li>
- <li><a href="https://twitter.com/{{ site.author.twitter }}">Twitter</a></li>
- <li class="muted">·</li>
- <li><a href="http://linkedin.com/in/{{ site.author.linkedin }}/">LinkedIn</a></li>
- </ul>
- </div>
+ <p>{{ site.copyright }}</p>
+ <p>Powered by Open Source software:
+ <a href="https://github.com/mojombo/jekyll">Jekyll</a>,
+ <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> and much more.
+ </p>
+ <ul class="footer-links">
+ <li><a href="https://github.com/{{ site.author.github }}/">GitHub</a></li>
+ <li class="muted">·</li>
+ <li><a href="https://twitter.com/{{ site.author.twitter }}">Twitter</a></li>
+ <li class="muted">·</li>
+ <li><a href="http://linkedin.com/in/{{ site.author.linkedin }}/">LinkedIn</a></li>
+ </ul>
</footer>
\ No newline at end of file
diff --git a/_includes/sidebar.html b/_includes/sidebar.html
index c4e8c82..bc9bf9d 100644
--- a/_includes/sidebar.html
+++ b/_includes/sidebar.html
@@ -1,4 +1,5 @@
+<br />
<!-- side bar -->
<div class="span2 hidden-phone">
{% include twitter_widget.html %}
</div>
\ No newline at end of file
diff --git a/index.html b/index.html
index 3c6cf83..ea67d6d 100644
--- a/index.html
+++ b/index.html
@@ -1,25 +1,26 @@
---
layout: default
title: Home
---
+<br />
{% for post in paginator.posts %}
<div class="row">
<div class="span2 hidden-phone">
{% if post.image != nil %}
<img src="/images/{{ post.image }}" />
{% endif %}
</div>
<div class="span6">
<h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
<div class="post_excerpt">
<blockquote>
<p>{{ post.content | strip_html | truncatewords: 30 }}</p>
<small class="muted">{% include post_date.html %}</small>
</blockquote>
</div>
</div>
</div>
{% endfor %}
{% include pagination.html %}
|
marcoshack/marcoshack.github.io
|
c7ce4cefc6e16be74574eb39d0d6fcb90ec76aaf
|
previous and next post links in the post layout
|
diff --git a/_layouts/post.html b/_layouts/post.html
index 7013831..2307f48 100644
--- a/_layouts/post.html
+++ b/_layouts/post.html
@@ -1,22 +1,35 @@
---
layout: default
---
-{% assign post = page %}
+{% assign post = page %}
<!-- post header -->
<div class="page-header">
<h1><a href="{{ post.url }}">{{ post.title }}</a></h1>
<small class="muted">{% include post_date.html %} | {% include author_name.html %}</small>
</div>
<div class="post">
{{ content }}
</div>
{% include facebook_div.html %}
{% include facebook_script.html %}
<br/> <!-- uhhhh -->
{% include disqus_div.html %}
{% include disqus_script.html %}
+
+<hr class="bs-docs-separator">
+
+<div class="row">
+ <div class="span8">
+ <a href="{{ post.previous.url }}">
+ <span class="pull-left"><i class="icon-backward"></i> {{ post.previous.title }}</span>
+ </a>
+ <a href="{{ post.next.url }}">
+ <span class="pull-right">{{ post.next.title }} <i class="icon-forward"></i></span>
+ </a>
+ </div>
+</div>
|
marcoshack/marcoshack.github.io
|
6d5535cf9425a063b5e8ecd9b728af11194eb52e
|
removed alien <br/> in ga.html
|
diff --git a/_includes/ga.html b/_includes/ga.html
index d3f9e0b..d03e19f 100644
--- a/_includes/ga.html
+++ b/_includes/ga.html
@@ -1,12 +1,11 @@
-<br/>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '{{ site.google_analytics.id }}']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
49128f8cce616166df92db443a77dc5e23528418
|
set TZ variable on jekyll cmd to set the correct timezone
|
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index 4916c46..ac8ab23 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,37 +1,38 @@
#!/usr/bin/env bash
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
+TIMEZONE=America/Sao_Paulo
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
function log_step {
echo -e "\e[1;33m--> ${1}\e[00m"
}
log_step "Setting up local workspace"
git clone $GIT_REPO $TMP_GIT_CLONE
log_step "Updating dependencies"
cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
log_step "Updating site"
-$JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW
+TZ=$TIMEZONE $JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW
log_step "Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
marcoshack/marcoshack.github.io
|
ca2b69b05b6488a1856078ed63578dd9794b3fd5
|
color in rake tasks output
|
diff --git a/Rakefile b/Rakefile
index 91cd9c1..4eb43a8 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,14 +1,21 @@
require 'rubygems'
require 'rake'
+def info(message)
+ puts "\e[1;33m--> #{message}\e[00m"
+end
+
task :server do
+ info "Starting local server"
sh "jekyll --server --auto --future"
end
task :deploy => [ :update_git_hooks ] do
+ info "Deploying to AWS"
sh "git push aws master"
end
task :update_git_hooks do
+ info "Updating git hooks"
sh "scp _deploy/git-post-receive.sh mhack.com:~/repo/mhack.git/hooks/post-receive"
end
|
marcoshack/marcoshack.github.io
|
44bc9357df362f9f1e73e98495b2893d76b5f15a
|
post <time datetime=...> format fixed
|
diff --git a/_includes/post_date.html b/_includes/post_date.html
new file mode 100644
index 0000000..14ee9d2
--- /dev/null
+++ b/_includes/post_date.html
@@ -0,0 +1,3 @@
+<time datetime="{{ post.date | date: "%Y-%m-%dT%H:%M%z" }}">
+ {{ post.date | date: "%Y-%m-%d %H:%M %z" }}
+</time>
\ No newline at end of file
diff --git a/_layouts/post.html b/_layouts/post.html
index 9e4900a..7013831 100644
--- a/_layouts/post.html
+++ b/_layouts/post.html
@@ -1,25 +1,22 @@
---
layout: default
---
+{% assign post = page %}
+
<!-- post header -->
<div class="page-header">
- <h1><a href="{{ page.url }}">{{ page.title }}</a></h1>
- <small class="muted">
- <time datetime="{{ page.date | date: "%Y-%m-%d %H:%M:%S %z" }}">
- {{ page.date | date: "%Y-%m-%d %H:%M %Z" }}
- </time> |
- {% include author_name.html %}
- </small>
+ <h1><a href="{{ post.url }}">{{ post.title }}</a></h1>
+ <small class="muted">{% include post_date.html %} | {% include author_name.html %}</small>
</div>
<div class="post">
{{ content }}
</div>
{% include facebook_div.html %}
{% include facebook_script.html %}
<br/> <!-- uhhhh -->
{% include disqus_div.html %}
{% include disqus_script.html %}
diff --git a/index.html b/index.html
index 51c5a16..3c6cf83 100644
--- a/index.html
+++ b/index.html
@@ -1,25 +1,25 @@
---
layout: default
title: Home
---
{% for post in paginator.posts %}
<div class="row">
<div class="span2 hidden-phone">
{% if post.image != nil %}
<img src="/images/{{ post.image }}" />
{% endif %}
</div>
<div class="span6">
<h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
- <div class="post_content">
+ <div class="post_excerpt">
<blockquote>
<p>{{ post.content | strip_html | truncatewords: 30 }}</p>
- <small>{{ post.date | date: "%Y-%m-%d" }}</small>
+ <small class="muted">{% include post_date.html %}</small>
</blockquote>
</div>
</div>
</div>
{% endfor %}
{% include pagination.html %}
|
marcoshack/marcoshack.github.io
|
11746635a237265e8179b118fe41d284dc7f3ab0
|
post date using <time> tag
|
diff --git a/_layouts/post.html b/_layouts/post.html
index 4d39497..9e4900a 100644
--- a/_layouts/post.html
+++ b/_layouts/post.html
@@ -1,22 +1,25 @@
---
layout: default
---
<!-- post header -->
<div class="page-header">
<h1><a href="{{ page.url }}">{{ page.title }}</a></h1>
<small class="muted">
- {{ page.date | date: "%Y-%m-%d %H:%M" }} | {% include author_name.html %}
+ <time datetime="{{ page.date | date: "%Y-%m-%d %H:%M:%S %z" }}">
+ {{ page.date | date: "%Y-%m-%d %H:%M %Z" }}
+ </time> |
+ {% include author_name.html %}
</small>
</div>
<div class="post">
{{ content }}
</div>
{% include facebook_div.html %}
{% include facebook_script.html %}
<br/> <!-- uhhhh -->
{% include disqus_div.html %}
{% include disqus_script.html %}
|
marcoshack/marcoshack.github.io
|
4ad16a07310758ddc1f3deec9785113e22d10ac7
|
brand style fixed and github ribbon disabled
|
diff --git a/_config.yml b/_config.yml
index ecbda4e..429b8f2 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,28 +1,29 @@
permalink: /:year/:month/:title.html
-
exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md, README_POSTS.md ]
-
future: false
lsi: true # Produces an index for related posts.
paginate: 4
+plugins: ./_plugins
+
+brand: mhack
author:
name: Marcos Hack
- display_name: Marcos Hack
email: [email protected]
twitter: marcoshack
github: marcoshack
linkedin: marcoshack
google_plus: 101876381204467415756
-plugins: ./_plugins
+title_sufix: '- Marcos Hack'
disqus:
shortname: mhack
google_analytics:
id: UA-6981296-7
-title_sufix: '- Marcos Hack'
+github:
+ ribbon: false
copyright: '© 2013 Marcos Hack. All rights reserved.'
diff --git a/_includes/github_ribbon.html b/_includes/github_ribbon.html
index ab74225..205ffe5 100644
--- a/_includes/github_ribbon.html
+++ b/_includes/github_ribbon.html
@@ -1,3 +1,5 @@
+{% if site.github.ribbon == true %}
<spam class="hidden-phone">
<a href="https://github.com/{{ site.author.github }}"><img style="position: absolute; top: 0; right: 0; border: 0;" src="/images/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
-</spam>
\ No newline at end of file
+</spam>
+{% endif %}
\ No newline at end of file
diff --git a/_includes/navbar.html b/_includes/navbar.html
index c91ff17..ed4098a 100644
--- a/_includes/navbar.html
+++ b/_includes/navbar.html
@@ -1,23 +1,23 @@
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
- <a class="brand" href="/">mhack</a>
+ <a class="brand" href="/">{{ site.brand }}</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="">
- <a href="/">home</a>
+ <a href="/">Home</a>
</li>
<li class="">
- <a href="/contato.html">contato</a>
+ <a href="/contato.html">Contato</a>
</li>
</ul>
</div>
{% include github_ribbon.html %}
</div>
</div>
</div>
\ No newline at end of file
diff --git a/_layouts/default.html b/_layouts/default.html
index f5eaea3..214aed6 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,38 +1,37 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
<title>{{ page.title }} {{ site.title_sufix }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/assets/css/bootstrap.css" rel="stylesheet">
- <link href="/assets/css/docs.css" rel="stylesheet">
- <link href="/assets/css/custom.css" rel="stylesheet">
+ <link href="/assets/css/style.css" rel="stylesheet">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
<br/>
<br/>
<div class="container">
<div class="row">
<div class="span8">
{{ content }}
</div>
{% include sidebar.html %}
</div>
</div>
{% include footer.html %}
<script src="/assets/js/jquery-1.9.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
</body>
</html>
\ No newline at end of file
diff --git a/assets/css/custom.css b/assets/css/custom.css
index acdaedb..a30cafe 100644
--- a/assets/css/custom.css
+++ b/assets/css/custom.css
@@ -1,3 +1,24 @@
-a.no_decoration {
- text-decoration: none;
-}
\ No newline at end of file
+/* Footer
+-------------------------------------------------- */
+
+.footer {
+ text-align: center;
+ padding: 30px 0;
+ margin-top: 70px;
+ border-top: 1px solid #e5e5e5;
+ background-color: #f5f5f5;
+}
+.footer p {
+ margin-bottom: 0;
+ color: #777;
+}
+.footer-links {
+ margin: 10px 0;
+}
+.footer-links li {
+ display: inline;
+ padding: 0 2px;
+}
+.footer-links li:first-child {
+ padding-left: 0;
+}
diff --git a/assets/css/style.css b/assets/css/style.css
new file mode 100644
index 0000000..a30cafe
--- /dev/null
+++ b/assets/css/style.css
@@ -0,0 +1,24 @@
+/* Footer
+-------------------------------------------------- */
+
+.footer {
+ text-align: center;
+ padding: 30px 0;
+ margin-top: 70px;
+ border-top: 1px solid #e5e5e5;
+ background-color: #f5f5f5;
+}
+.footer p {
+ margin-bottom: 0;
+ color: #777;
+}
+.footer-links {
+ margin: 10px 0;
+}
+.footer-links li {
+ display: inline;
+ padding: 0 2px;
+}
+.footer-links li:first-child {
+ padding-left: 0;
+}
|
marcoshack/marcoshack.github.io
|
9c960df2caa7c1d6f3d9295279d94f57180f963c
|
ignorar README_POSTS.md
|
diff --git a/_config.yml b/_config.yml
index 03ee837..ecbda4e 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,28 +1,28 @@
permalink: /:year/:month/:title.html
-exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md ]
+exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md, README_POSTS.md ]
future: false
lsi: true # Produces an index for related posts.
paginate: 4
author:
name: Marcos Hack
display_name: Marcos Hack
email: [email protected]
twitter: marcoshack
github: marcoshack
linkedin: marcoshack
google_plus: 101876381204467415756
plugins: ./_plugins
disqus:
shortname: mhack
google_analytics:
id: UA-6981296-7
title_sufix: '- Marcos Hack'
copyright: '© 2013 Marcos Hack. All rights reserved.'
|
marcoshack/marcoshack.github.io
|
0238089d36c4890d31f114e3ebe974c3d55de576
|
ids de redes sociais e servicos no _config.yml
|
diff --git a/_config.yml b/_config.yml
index d619cfc..03ee837 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,17 +1,28 @@
permalink: /:year/:month/:title.html
exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md ]
future: false
lsi: true # Produces an index for related posts.
paginate: 4
-authors:
- mhack:
- name: Marcos Hack
- display_name: Marcos Hack
- email: [email protected]
- twitter: marcoshack
- github: marcoshack
-
-plugins: ./_plugins
\ No newline at end of file
+author:
+ name: Marcos Hack
+ display_name: Marcos Hack
+ email: [email protected]
+ twitter: marcoshack
+ github: marcoshack
+ linkedin: marcoshack
+ google_plus: 101876381204467415756
+
+plugins: ./_plugins
+
+disqus:
+ shortname: mhack
+
+google_analytics:
+ id: UA-6981296-7
+
+title_sufix: '- Marcos Hack'
+
+copyright: '© 2013 Marcos Hack. All rights reserved.'
diff --git a/_includes/author_name.html b/_includes/author_name.html
new file mode 100644
index 0000000..83c6e11
--- /dev/null
+++ b/_includes/author_name.html
@@ -0,0 +1,5 @@
+{% if site.author.google_plus != nil %}
+<a href="https://plus.google.com/{{ site.author.google_plus }}?rel=author">{{ site.author.name }}</a>
+{% else %}
+{{ site.author.name }}
+{% endif %}
\ No newline at end of file
diff --git a/_includes/disqus_script.html b/_includes/disqus_script.html
index 34833da..eaae432 100644
--- a/_includes/disqus_script.html
+++ b/_includes/disqus_script.html
@@ -1,11 +1,11 @@
{% unless page.comments == false %}
<!-- disqus script -->
<script type="text/javascript">
- var disqus_shortname = 'mhack';
+ var disqus_shortname = '{{ site.disqus.shortname }}';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
{% endunless %}
diff --git a/_includes/footer.html b/_includes/footer.html
new file mode 100644
index 0000000..01bd639
--- /dev/null
+++ b/_includes/footer.html
@@ -0,0 +1,16 @@
+<footer class="footer">
+ <div class="container">
+ <p>{{ site.copyright }}</p>
+ <p>Powered by Open Source software:
+ <a href="https://github.com/mojombo/jekyll">Jekyll</a>,
+ <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> and much more.
+ </p>
+ <ul class="footer-links">
+ <li><a href="https://github.com/{{ site.author.github }}/">GitHub</a></li>
+ <li class="muted">·</li>
+ <li><a href="https://twitter.com/{{ site.author.twitter }}">Twitter</a></li>
+ <li class="muted">·</li>
+ <li><a href="http://linkedin.com/in/{{ site.author.linkedin }}/">LinkedIn</a></li>
+ </ul>
+ </div>
+</footer>
\ No newline at end of file
diff --git a/_includes/ga.html b/_includes/ga.html
index c6c1c7b..d3f9e0b 100644
--- a/_includes/ga.html
+++ b/_includes/ga.html
@@ -1,12 +1,12 @@
<br/>
<script type="text/javascript">
var _gaq = _gaq || [];
- _gaq.push(['_setAccount', 'UA-6981296-7']);
+ _gaq.push(['_setAccount', '{{ site.google_analytics.id }}']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
\ No newline at end of file
diff --git a/_includes/github_ribbon.html b/_includes/github_ribbon.html
index ebf63a6..ab74225 100644
--- a/_includes/github_ribbon.html
+++ b/_includes/github_ribbon.html
@@ -1,3 +1,3 @@
<spam class="hidden-phone">
- <a href="https://github.com/marcoshack"><img style="position: absolute; top: 0; right: 0; border: 0;" src="/images/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
+ <a href="https://github.com/{{ site.author.github }}"><img style="position: absolute; top: 0; right: 0; border: 0;" src="/images/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
</spam>
\ No newline at end of file
diff --git a/_includes/twitter_widget.html b/_includes/twitter_widget.html
index 1ab7a1a..a48352a 100644
--- a/_includes/twitter_widget.html
+++ b/_includes/twitter_widget.html
@@ -1,3 +1,3 @@
-<a class="twitter-timeline" href="https://twitter.com/marcoshack" data-widget-id="293893619042107392">Tweets by @marcoshack</a>
+<a class="twitter-timeline" href="https://twitter.com/{{ site.author.twitter }}" data-widget-id="293893619042107392">Tweets by @{{ site.author.twitter }}</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
</script>
\ No newline at end of file
diff --git a/_layouts/default.html b/_layouts/default.html
index 02979b2..f5eaea3 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,51 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
- <title>{{ page.title }} - Marcos Hack</title>
+ <title>{{ page.title }} {{ site.title_sufix }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/assets/css/bootstrap.css" rel="stylesheet">
<link href="/assets/css/docs.css" rel="stylesheet">
<link href="/assets/css/custom.css" rel="stylesheet">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
<br/>
<br/>
<div class="container">
<div class="row">
- <!-- main content -->
<div class="span8">
{{ content }}
</div>
{% include sidebar.html %}
</div>
</div>
- <footer class="footer">
- <div class="container">
- <p>© 2013 Marcos Hack. All rights reserved.</p>
- <p>Powered by Open Source software: <a href="https://github.com/mojombo/jekyll">Jekyll</a>, <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> and much more.</p>
- <ul class="footer-links">
- <li><a href="https://github.com/marcoshack/">GitHub</a></li>
- <li class="muted">·</li>
- <li><a href="https://twitter.com/marcoshack">Twitter</a></li>
- <li class="muted">·</li>
- <li><a href="http://br.linkedin.com/in/marcoshack/">LinkedIn</a></li>
- </ul>
- </div>
- </footer>
+ {% include footer.html %}
<script src="/assets/js/jquery-1.9.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
</body>
</html>
\ No newline at end of file
diff --git a/_layouts/post.html b/_layouts/post.html
index c0e5f34..4d39497 100644
--- a/_layouts/post.html
+++ b/_layouts/post.html
@@ -1,23 +1,22 @@
---
layout: default
---
<!-- post header -->
<div class="page-header">
<h1><a href="{{ page.url }}">{{ page.title }}</a></h1>
<small class="muted">
- {{ page.date | date: "%Y-%m-%d %H:%M" }} |
- <a href="https://plus.google.com/101876381204467415756?rel=author">Marcos Hack</a>
+ {{ page.date | date: "%Y-%m-%d %H:%M" }} | {% include author_name.html %}
</small>
</div>
<div class="post">
{{ content }}
</div>
{% include facebook_div.html %}
{% include facebook_script.html %}
<br/> <!-- uhhhh -->
{% include disqus_div.html %}
{% include disqus_script.html %}
|
marcoshack/marcoshack.github.io
|
0b5339ed63066124f1acdcd87e75c01c60c79e8f
|
footer
|
diff --git a/_layouts/default.html b/_layouts/default.html
index ba78153..02979b2 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,36 +1,51 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
<title>{{ page.title }} - Marcos Hack</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/assets/css/bootstrap.css" rel="stylesheet">
+ <link href="/assets/css/docs.css" rel="stylesheet">
<link href="/assets/css/custom.css" rel="stylesheet">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
<br/>
<br/>
<div class="container">
<div class="row">
<!-- main content -->
<div class="span8">
{{ content }}
</div>
{% include sidebar.html %}
</div>
</div>
+ <footer class="footer">
+ <div class="container">
+ <p>© 2013 Marcos Hack. All rights reserved.</p>
+ <p>Powered by Open Source software: <a href="https://github.com/mojombo/jekyll">Jekyll</a>, <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> and much more.</p>
+ <ul class="footer-links">
+ <li><a href="https://github.com/marcoshack/">GitHub</a></li>
+ <li class="muted">·</li>
+ <li><a href="https://twitter.com/marcoshack">Twitter</a></li>
+ <li class="muted">·</li>
+ <li><a href="http://br.linkedin.com/in/marcoshack/">LinkedIn</a></li>
+ </ul>
+ </div>
+ </footer>
+
<script src="/assets/js/jquery-1.9.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
</body>
</html>
\ No newline at end of file
diff --git a/assets/css/docs.css b/assets/css/docs.css
new file mode 100644
index 0000000..c7bddd4
--- /dev/null
+++ b/assets/css/docs.css
@@ -0,0 +1,1064 @@
+/* Add additional stylesheets below
+-------------------------------------------------- */
+/*
+ Bootstrap's documentation styles
+ Special styles for presenting Bootstrap's documentation and examples
+*/
+
+
+
+/* Body and structure
+-------------------------------------------------- */
+
+body {
+ position: relative;
+ padding-top: 40px;
+}
+
+/* Code in headings */
+h3 code {
+ font-size: 14px;
+ font-weight: normal;
+}
+
+
+
+/* Tweak navbar brand link to be super sleek
+-------------------------------------------------- */
+
+body > .navbar {
+ font-size: 13px;
+}
+
+/* Change the docs' brand */
+body > .navbar .brand {
+ padding-right: 0;
+ padding-left: 0;
+ margin-left: 20px;
+ float: right;
+ font-weight: bold;
+ color: #000;
+ text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.125);
+ -webkit-transition: all .2s linear;
+ -moz-transition: all .2s linear;
+ transition: all .2s linear;
+}
+body > .navbar .brand:hover {
+ text-decoration: none;
+ text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.4);
+}
+
+
+/* Sections
+-------------------------------------------------- */
+
+/* padding for in-page bookmarks and fixed navbar */
+section {
+ padding-top: 30px;
+}
+section > .page-header,
+section > .lead {
+ color: #5a5a5a;
+}
+section > ul li {
+ margin-bottom: 5px;
+}
+
+/* Separators (hr) */
+.bs-docs-separator {
+ margin: 40px 0 39px;
+}
+
+/* Faded out hr */
+hr.soften {
+ height: 1px;
+ margin: 70px 0;
+ background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
+ background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
+ background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
+ background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
+ border: 0;
+}
+
+
+
+/* Jumbotrons
+-------------------------------------------------- */
+
+/* Base class
+------------------------- */
+.jumbotron {
+ position: relative;
+ padding: 40px 0;
+ color: #fff;
+ text-align: center;
+ text-shadow: 0 1px 3px rgba(0,0,0,.4), 0 0 30px rgba(0,0,0,.075);
+ background: #020031; /* Old browsers */
+ background: -moz-linear-gradient(45deg, #020031 0%, #6d3353 100%); /* FF3.6+ */
+ background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#020031), color-stop(100%,#6d3353)); /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* Chrome10+,Safari5.1+ */
+ background: -o-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* Opera 11.10+ */
+ background: -ms-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* IE10+ */
+ background: linear-gradient(45deg, #020031 0%,#6d3353 100%); /* W3C */
+ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#020031', endColorstr='#6d3353',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
+ -webkit-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
+ -moz-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
+ box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
+}
+.jumbotron h1 {
+ font-size: 80px;
+ font-weight: bold;
+ letter-spacing: -1px;
+ line-height: 1;
+}
+.jumbotron p {
+ font-size: 24px;
+ font-weight: 300;
+ line-height: 1.25;
+ margin-bottom: 30px;
+}
+
+/* Link styles (used on .masthead-links as well) */
+.jumbotron a {
+ color: #fff;
+ color: rgba(255,255,255,.5);
+ -webkit-transition: all .2s ease-in-out;
+ -moz-transition: all .2s ease-in-out;
+ transition: all .2s ease-in-out;
+}
+.jumbotron a:hover {
+ color: #fff;
+ text-shadow: 0 0 10px rgba(255,255,255,.25);
+}
+
+/* Download button */
+.masthead .btn {
+ padding: 19px 24px;
+ font-size: 24px;
+ font-weight: 200;
+ color: #fff; /* redeclare to override the `.jumbotron a` */
+ border: 0;
+ -webkit-border-radius: 6px;
+ -moz-border-radius: 6px;
+ border-radius: 6px;
+ -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
+ -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
+ box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
+ -webkit-transition: none;
+ -moz-transition: none;
+ transition: none;
+}
+.masthead .btn:hover {
+ -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
+ -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
+ box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
+}
+.masthead .btn:active {
+ -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
+ -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
+ box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
+}
+
+
+/* Pattern overlay
+------------------------- */
+.jumbotron .container {
+ position: relative;
+ z-index: 2;
+}
+.jumbotron:after {
+ content: '';
+ display: block;
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ background: url(../img/bs-docs-masthead-pattern.png) repeat center center;
+ opacity: .4;
+}
+@media
+only screen and (-webkit-min-device-pixel-ratio: 2),
+only screen and ( min--moz-device-pixel-ratio: 2),
+only screen and ( -o-min-device-pixel-ratio: 2/1) {
+
+ .jumbotron:after {
+ background-size: 150px 150px;
+ }
+
+}
+
+/* Masthead (docs home)
+------------------------- */
+.masthead {
+ padding: 70px 0 80px;
+ margin-bottom: 0;
+ color: #fff;
+}
+.masthead h1 {
+ font-size: 120px;
+ line-height: 1;
+ letter-spacing: -2px;
+}
+.masthead p {
+ font-size: 40px;
+ font-weight: 200;
+ line-height: 1.25;
+}
+
+/* Textual links in masthead */
+.masthead-links {
+ margin: 0;
+ list-style: none;
+}
+.masthead-links li {
+ display: inline;
+ padding: 0 10px;
+ color: rgba(255,255,255,.25);
+}
+
+/* Social proof buttons from GitHub & Twitter */
+.bs-docs-social {
+ padding: 15px 0;
+ text-align: center;
+ background-color: #f5f5f5;
+ border-top: 1px solid #fff;
+ border-bottom: 1px solid #ddd;
+}
+
+/* Quick links on Home */
+.bs-docs-social-buttons {
+ margin-left: 0;
+ margin-bottom: 0;
+ padding-left: 0;
+ list-style: none;
+}
+.bs-docs-social-buttons li {
+ display: inline-block;
+ padding: 5px 8px;
+ line-height: 1;
+ *display: inline;
+ *zoom: 1;
+}
+
+/* Subhead (other pages)
+------------------------- */
+.subhead {
+ text-align: left;
+ border-bottom: 1px solid #ddd;
+}
+.subhead h1 {
+ font-size: 60px;
+}
+.subhead p {
+ margin-bottom: 20px;
+}
+.subhead .navbar {
+ display: none;
+}
+
+
+
+/* Marketing section of Overview
+-------------------------------------------------- */
+
+.marketing {
+ text-align: center;
+ color: #5a5a5a;
+}
+.marketing h1 {
+ margin: 60px 0 10px;
+ font-size: 60px;
+ font-weight: 200;
+ line-height: 1;
+ letter-spacing: -1px;
+}
+.marketing h2 {
+ font-weight: 200;
+ margin-bottom: 5px;
+}
+.marketing p {
+ font-size: 16px;
+ line-height: 1.5;
+}
+.marketing .marketing-byline {
+ margin-bottom: 40px;
+ font-size: 20px;
+ font-weight: 300;
+ line-height: 1.25;
+ color: #999;
+}
+.marketing-img {
+ display: block;
+ margin: 0 auto 30px;
+ max-height: 145px;
+}
+
+
+
+/* Footer
+-------------------------------------------------- */
+
+.footer {
+ text-align: center;
+ padding: 30px 0;
+ margin-top: 70px;
+ border-top: 1px solid #e5e5e5;
+ background-color: #f5f5f5;
+}
+.footer p {
+ margin-bottom: 0;
+ color: #777;
+}
+.footer-links {
+ margin: 10px 0;
+}
+.footer-links li {
+ display: inline;
+ padding: 0 2px;
+}
+.footer-links li:first-child {
+ padding-left: 0;
+}
+
+
+
+/* Special grid styles
+-------------------------------------------------- */
+
+.show-grid {
+ margin-top: 10px;
+ margin-bottom: 20px;
+}
+.show-grid [class*="span"] {
+ background-color: #eee;
+ text-align: center;
+ -webkit-border-radius: 3px;
+ -moz-border-radius: 3px;
+ border-radius: 3px;
+ min-height: 40px;
+ line-height: 40px;
+}
+.show-grid:hover [class*="span"] {
+ background: #ddd;
+}
+.show-grid .show-grid {
+ margin-top: 0;
+ margin-bottom: 0;
+}
+.show-grid .show-grid [class*="span"] {
+ margin-top: 5px;
+}
+.show-grid [class*="span"] [class*="span"] {
+ background-color: #ccc;
+}
+.show-grid [class*="span"] [class*="span"] [class*="span"] {
+ background-color: #999;
+}
+
+
+
+/* Mini layout previews
+-------------------------------------------------- */
+.mini-layout {
+ border: 1px solid #ddd;
+ -webkit-border-radius: 6px;
+ -moz-border-radius: 6px;
+ border-radius: 6px;
+ -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.075);
+ -moz-box-shadow: 0 1px 2px rgba(0,0,0,.075);
+ box-shadow: 0 1px 2px rgba(0,0,0,.075);
+}
+.mini-layout,
+.mini-layout .mini-layout-body,
+.mini-layout.fluid .mini-layout-sidebar {
+ height: 300px;
+}
+.mini-layout {
+ margin-bottom: 20px;
+ padding: 9px;
+}
+.mini-layout div {
+ -webkit-border-radius: 3px;
+ -moz-border-radius: 3px;
+ border-radius: 3px;
+}
+.mini-layout .mini-layout-body {
+ background-color: #dceaf4;
+ margin: 0 auto;
+ width: 70%;
+}
+.mini-layout.fluid .mini-layout-sidebar,
+.mini-layout.fluid .mini-layout-header,
+.mini-layout.fluid .mini-layout-body {
+ float: left;
+}
+.mini-layout.fluid .mini-layout-sidebar {
+ background-color: #bbd8e9;
+ width: 20%;
+}
+.mini-layout.fluid .mini-layout-body {
+ width: 77.5%;
+ margin-left: 2.5%;
+}
+
+
+
+/* Download page
+-------------------------------------------------- */
+
+.download .page-header {
+ margin-top: 36px;
+}
+.page-header .toggle-all {
+ margin-top: 5px;
+}
+
+/* Space out h3s when following a section */
+.download h3 {
+ margin-bottom: 5px;
+}
+.download-builder input + h3,
+.download-builder .checkbox + h3 {
+ margin-top: 9px;
+}
+
+/* Fields for variables */
+.download-builder input[type=text] {
+ margin-bottom: 9px;
+ font-family: Menlo, Monaco, "Courier New", monospace;
+ font-size: 12px;
+ color: #d14;
+}
+.download-builder input[type=text]:focus {
+ background-color: #fff;
+}
+
+/* Custom, larger checkbox labels */
+.download .checkbox {
+ padding: 6px 10px 6px 25px;
+ font-size: 13px;
+ line-height: 18px;
+ color: #555;
+ background-color: #f9f9f9;
+ -webkit-border-radius: 3px;
+ -moz-border-radius: 3px;
+ border-radius: 3px;
+ cursor: pointer;
+}
+.download .checkbox:hover {
+ color: #333;
+ background-color: #f5f5f5;
+}
+.download .checkbox small {
+ font-size: 12px;
+ color: #777;
+}
+
+/* Variables section */
+#variables label {
+ margin-bottom: 0;
+}
+
+/* Giant download button */
+.download-btn {
+ margin: 36px 0 108px;
+}
+#download p,
+#download h4 {
+ max-width: 50%;
+ margin: 0 auto;
+ color: #999;
+ text-align: center;
+}
+#download h4 {
+ margin-bottom: 0;
+}
+#download p {
+ margin-bottom: 18px;
+}
+.download-btn .btn {
+ display: block;
+ width: auto;
+ padding: 19px 24px;
+ margin-bottom: 27px;
+ font-size: 30px;
+ line-height: 1;
+ text-align: center;
+ -webkit-border-radius: 6px;
+ -moz-border-radius: 6px;
+ border-radius: 6px;
+}
+
+
+
+/* Misc
+-------------------------------------------------- */
+
+/* Make tables spaced out a bit more */
+h2 + table,
+h3 + table,
+h4 + table,
+h2 + .row {
+ margin-top: 5px;
+}
+
+/* Example sites showcase */
+.example-sites {
+ xmargin-left: 20px;
+}
+.example-sites img {
+ max-width: 100%;
+ margin: 0 auto;
+}
+
+.scrollspy-example {
+ height: 200px;
+ overflow: auto;
+ position: relative;
+}
+
+
+/* Fake the :focus state to demo it */
+.focused {
+ border-color: rgba(82,168,236,.8);
+ -webkit-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
+ -moz-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
+ box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
+ outline: 0;
+}
+
+/* For input sizes, make them display block */
+.docs-input-sizes select,
+.docs-input-sizes input[type=text] {
+ display: block;
+ margin-bottom: 9px;
+}
+
+/* Icons
+------------------------- */
+.the-icons {
+ margin-left: 0;
+ list-style: none;
+}
+.the-icons li {
+ float: left;
+ width: 25%;
+ line-height: 25px;
+}
+.the-icons i:hover {
+ background-color: rgba(255,0,0,.25);
+}
+
+/* Example page
+------------------------- */
+.bootstrap-examples p {
+ font-size: 13px;
+ line-height: 18px;
+}
+.bootstrap-examples .thumbnail {
+ margin-bottom: 9px;
+ background-color: #fff;
+}
+
+
+
+/* Bootstrap code examples
+-------------------------------------------------- */
+
+/* Base class */
+.bs-docs-example {
+ position: relative;
+ margin: 15px 0;
+ padding: 39px 19px 14px;
+ *padding-top: 19px;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ -webkit-border-radius: 4px;
+ -moz-border-radius: 4px;
+ border-radius: 4px;
+}
+
+/* Echo out a label for the example */
+.bs-docs-example:after {
+ content: "Example";
+ position: absolute;
+ top: -1px;
+ left: -1px;
+ padding: 3px 7px;
+ font-size: 12px;
+ font-weight: bold;
+ background-color: #f5f5f5;
+ border: 1px solid #ddd;
+ color: #9da0a4;
+ -webkit-border-radius: 4px 0 4px 0;
+ -moz-border-radius: 4px 0 4px 0;
+ border-radius: 4px 0 4px 0;
+}
+
+/* Remove spacing between an example and it's code */
+.bs-docs-example + .prettyprint {
+ margin-top: -20px;
+ padding-top: 15px;
+}
+
+/* Tweak examples
+------------------------- */
+.bs-docs-example > p:last-child {
+ margin-bottom: 0;
+}
+.bs-docs-example .table,
+.bs-docs-example .progress,
+.bs-docs-example .well,
+.bs-docs-example .alert,
+.bs-docs-example .hero-unit,
+.bs-docs-example .pagination,
+.bs-docs-example .navbar,
+.bs-docs-example > .nav,
+.bs-docs-example blockquote {
+ margin-bottom: 5px;
+}
+.bs-docs-example .pagination {
+ margin-top: 0;
+}
+.bs-navbar-top-example,
+.bs-navbar-bottom-example {
+ z-index: 1;
+ padding: 0;
+ height: 90px;
+ overflow: hidden; /* cut the drop shadows off */
+}
+.bs-navbar-top-example .navbar-fixed-top,
+.bs-navbar-bottom-example .navbar-fixed-bottom {
+ margin-left: 0;
+ margin-right: 0;
+}
+.bs-navbar-top-example {
+ -webkit-border-radius: 0 0 4px 4px;
+ -moz-border-radius: 0 0 4px 4px;
+ border-radius: 0 0 4px 4px;
+}
+.bs-navbar-top-example:after {
+ top: auto;
+ bottom: -1px;
+ -webkit-border-radius: 0 4px 0 4px;
+ -moz-border-radius: 0 4px 0 4px;
+ border-radius: 0 4px 0 4px;
+}
+.bs-navbar-bottom-example {
+ -webkit-border-radius: 4px 4px 0 0;
+ -moz-border-radius: 4px 4px 0 0;
+ border-radius: 4px 4px 0 0;
+}
+.bs-navbar-bottom-example .navbar {
+ margin-bottom: 0;
+}
+form.bs-docs-example {
+ padding-bottom: 19px;
+}
+
+/* Images */
+.bs-docs-example-images img {
+ margin: 10px;
+ display: inline-block;
+}
+
+/* Tooltips */
+.bs-docs-tooltip-examples {
+ text-align: center;
+ margin: 0 0 10px;
+ list-style: none;
+}
+.bs-docs-tooltip-examples li {
+ display: inline;
+ padding: 0 10px;
+}
+
+/* Popovers */
+.bs-docs-example-popover {
+ padding-bottom: 24px;
+ background-color: #f9f9f9;
+}
+.bs-docs-example-popover .popover {
+ position: relative;
+ display: block;
+ float: left;
+ width: 260px;
+ margin: 20px;
+}
+
+/* Dropdowns */
+.bs-docs-example-submenus {
+ min-height: 180px;
+}
+.bs-docs-example-submenus > .pull-left + .pull-left {
+ margin-left: 20px;
+}
+.bs-docs-example-submenus .dropup > .dropdown-menu,
+.bs-docs-example-submenus .dropdown > .dropdown-menu {
+ display: block;
+ position: static;
+ margin-bottom: 5px;
+ *width: 180px;
+}
+
+
+
+/* Responsive docs
+-------------------------------------------------- */
+
+/* Utility classes table
+------------------------- */
+.responsive-utilities th small {
+ display: block;
+ font-weight: normal;
+ color: #999;
+}
+.responsive-utilities tbody th {
+ font-weight: normal;
+}
+.responsive-utilities td {
+ text-align: center;
+}
+.responsive-utilities td.is-visible {
+ color: #468847;
+ background-color: #dff0d8 !important;
+}
+.responsive-utilities td.is-hidden {
+ color: #ccc;
+ background-color: #f9f9f9 !important;
+}
+
+/* Responsive tests
+------------------------- */
+.responsive-utilities-test {
+ margin-top: 5px;
+ margin-left: 0;
+ list-style: none;
+ overflow: hidden; /* clear floats */
+}
+.responsive-utilities-test li {
+ position: relative;
+ float: left;
+ width: 25%;
+ height: 43px;
+ font-size: 14px;
+ font-weight: bold;
+ line-height: 43px;
+ color: #999;
+ text-align: center;
+ border: 1px solid #ddd;
+ -webkit-border-radius: 4px;
+ -moz-border-radius: 4px;
+ border-radius: 4px;
+}
+.responsive-utilities-test li + li {
+ margin-left: 10px;
+}
+.responsive-utilities-test span {
+ position: absolute;
+ top: -1px;
+ left: -1px;
+ right: -1px;
+ bottom: -1px;
+ -webkit-border-radius: 4px;
+ -moz-border-radius: 4px;
+ border-radius: 4px;
+}
+.responsive-utilities-test span {
+ color: #468847;
+ background-color: #dff0d8;
+ border: 1px solid #d6e9c6;
+}
+
+
+
+/* Sidenav for Docs
+-------------------------------------------------- */
+
+.bs-docs-sidenav {
+ width: 228px;
+ margin: 30px 0 0;
+ padding: 0;
+ background-color: #fff;
+ -webkit-border-radius: 6px;
+ -moz-border-radius: 6px;
+ border-radius: 6px;
+ -webkit-box-shadow: 0 1px 4px rgba(0,0,0,.065);
+ -moz-box-shadow: 0 1px 4px rgba(0,0,0,.065);
+ box-shadow: 0 1px 4px rgba(0,0,0,.065);
+}
+.bs-docs-sidenav > li > a {
+ display: block;
+ width: 190px \9;
+ margin: 0 0 -1px;
+ padding: 8px 14px;
+ border: 1px solid #e5e5e5;
+}
+.bs-docs-sidenav > li:first-child > a {
+ -webkit-border-radius: 6px 6px 0 0;
+ -moz-border-radius: 6px 6px 0 0;
+ border-radius: 6px 6px 0 0;
+}
+.bs-docs-sidenav > li:last-child > a {
+ -webkit-border-radius: 0 0 6px 6px;
+ -moz-border-radius: 0 0 6px 6px;
+ border-radius: 0 0 6px 6px;
+}
+.bs-docs-sidenav > .active > a {
+ position: relative;
+ z-index: 2;
+ padding: 9px 15px;
+ border: 0;
+ text-shadow: 0 1px 0 rgba(0,0,0,.15);
+ -webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
+ -moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
+ box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
+}
+/* Chevrons */
+.bs-docs-sidenav .icon-chevron-right {
+ float: right;
+ margin-top: 2px;
+ margin-right: -6px;
+ opacity: .25;
+}
+.bs-docs-sidenav > li > a:hover {
+ background-color: #f5f5f5;
+}
+.bs-docs-sidenav a:hover .icon-chevron-right {
+ opacity: .5;
+}
+.bs-docs-sidenav .active .icon-chevron-right,
+.bs-docs-sidenav .active a:hover .icon-chevron-right {
+ background-image: url(../img/glyphicons-halflings-white.png);
+ opacity: 1;
+}
+.bs-docs-sidenav.affix {
+ top: 40px;
+}
+.bs-docs-sidenav.affix-bottom {
+ position: absolute;
+ top: auto;
+ bottom: 270px;
+}
+
+
+
+
+/* Responsive
+-------------------------------------------------- */
+
+/* Desktop large
+------------------------- */
+@media (min-width: 1200px) {
+ .bs-docs-container {
+ max-width: 970px;
+ }
+ .bs-docs-sidenav {
+ width: 258px;
+ }
+ .bs-docs-sidenav > li > a {
+ width: 230px \9; /* Override the previous IE8-9 hack */
+ }
+}
+
+/* Desktop
+------------------------- */
+@media (max-width: 980px) {
+ /* Unfloat brand */
+ body > .navbar-fixed-top .brand {
+ float: left;
+ margin-left: 0;
+ padding-left: 10px;
+ padding-right: 10px;
+ }
+
+ /* Inline-block quick links for more spacing */
+ .quick-links li {
+ display: inline-block;
+ margin: 5px;
+ }
+
+ /* When affixed, space properly */
+ .bs-docs-sidenav {
+ top: 0;
+ width: 218px;
+ margin-top: 30px;
+ margin-right: 0;
+ }
+}
+
+/* Tablet to desktop
+------------------------- */
+@media (min-width: 768px) and (max-width: 979px) {
+ /* Remove any padding from the body */
+ body {
+ padding-top: 0;
+ }
+ /* Widen masthead and social buttons to fill body padding */
+ .jumbotron {
+ margin-top: -20px; /* Offset bottom margin on .navbar */
+ }
+ /* Adjust sidenav width */
+ .bs-docs-sidenav {
+ width: 166px;
+ margin-top: 20px;
+ }
+ .bs-docs-sidenav.affix {
+ top: 0;
+ }
+}
+
+/* Tablet
+------------------------- */
+@media (max-width: 767px) {
+ /* Remove any padding from the body */
+ body {
+ padding-top: 0;
+ }
+
+ /* Widen masthead and social buttons to fill body padding */
+ .jumbotron {
+ padding: 40px 20px;
+ margin-top: -20px; /* Offset bottom margin on .navbar */
+ margin-right: -20px;
+ margin-left: -20px;
+ }
+ .masthead h1 {
+ font-size: 90px;
+ }
+ .masthead p,
+ .masthead .btn {
+ font-size: 24px;
+ }
+ .marketing .span4 {
+ margin-bottom: 40px;
+ }
+ .bs-docs-social {
+ margin: 0 -20px;
+ }
+
+ /* Space out the show-grid examples */
+ .show-grid [class*="span"] {
+ margin-bottom: 5px;
+ }
+
+ /* Sidenav */
+ .bs-docs-sidenav {
+ width: auto;
+ margin-bottom: 20px;
+ }
+ .bs-docs-sidenav.affix {
+ position: static;
+ width: auto;
+ top: 0;
+ }
+
+ /* Unfloat the back to top link in footer */
+ .footer {
+ margin-left: -20px;
+ margin-right: -20px;
+ padding-left: 20px;
+ padding-right: 20px;
+ }
+ .footer p {
+ margin-bottom: 9px;
+ }
+}
+
+/* Landscape phones
+------------------------- */
+@media (max-width: 480px) {
+ /* Remove padding above jumbotron */
+ body {
+ padding-top: 0;
+ }
+
+ /* Change up some type stuff */
+ h2 small {
+ display: block;
+ }
+
+ /* Downsize the jumbotrons */
+ .jumbotron h1 {
+ font-size: 45px;
+ }
+ .jumbotron p,
+ .jumbotron .btn {
+ font-size: 18px;
+ }
+ .jumbotron .btn {
+ display: block;
+ margin: 0 auto;
+ }
+
+ /* center align subhead text like the masthead */
+ .subhead h1,
+ .subhead p {
+ text-align: center;
+ }
+
+ /* Marketing on home */
+ .marketing h1 {
+ font-size: 30px;
+ }
+ .marketing-byline {
+ font-size: 18px;
+ }
+
+ /* center example sites */
+ .example-sites {
+ margin-left: 0;
+ }
+ .example-sites > li {
+ float: none;
+ display: block;
+ max-width: 280px;
+ margin: 0 auto 18px;
+ text-align: center;
+ }
+ .example-sites .thumbnail > img {
+ max-width: 270px;
+ }
+
+ /* Do our best to make tables work in narrow viewports */
+ table code {
+ white-space: normal;
+ word-wrap: break-word;
+ word-break: break-all;
+ }
+
+ /* Examples: dropdowns */
+ .bs-docs-example-submenus > .pull-left {
+ float: none;
+ clear: both;
+ }
+ .bs-docs-example-submenus > .pull-left,
+ .bs-docs-example-submenus > .pull-left + .pull-left {
+ margin-left: 0;
+ }
+ .bs-docs-example-submenus p {
+ margin-bottom: 0;
+ }
+ .bs-docs-example-submenus .dropup > .dropdown-menu,
+ .bs-docs-example-submenus .dropdown > .dropdown-menu {
+ margin-bottom: 10px;
+ float: none;
+ max-width: 180px;
+ }
+
+ /* Examples: modal */
+ .modal-example .modal {
+ position: relative;
+ top: auto;
+ right: auto;
+ bottom: auto;
+ left: auto;
+ }
+
+ /* Tighten up footer */
+ .footer {
+ padding-top: 20px;
+ padding-bottom: 20px;
+ }
+}
|
marcoshack/marcoshack.github.io
|
bada113812bb487d14c47a84d44489605ea33f93
|
alteracao do titulo da ome
|
diff --git a/index.html b/index.html
index d0e717e..51c5a16 100644
--- a/index.html
+++ b/index.html
@@ -1,25 +1,25 @@
---
layout: default
-title: home
+title: Home
---
{% for post in paginator.posts %}
<div class="row">
<div class="span2 hidden-phone">
{% if post.image != nil %}
<img src="/images/{{ post.image }}" />
{% endif %}
</div>
<div class="span6">
<h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
<div class="post_content">
<blockquote>
<p>{{ post.content | strip_html | truncatewords: 30 }}</p>
<small>{{ post.date | date: "%Y-%m-%d" }}</small>
</blockquote>
</div>
</div>
</div>
{% endfor %}
{% include pagination.html %}
|
marcoshack/marcoshack.github.io
|
02b07b72fe34da57268d5e45a4e4a465f426e881
|
troca do prefixo 'mhack' pelo sufixo 'Marcos Hack' no titulo das paginas
|
diff --git a/_layouts/default.html b/_layouts/default.html
index de859e9..ba78153 100644
--- a/_layouts/default.html
+++ b/_layouts/default.html
@@ -1,36 +1,36 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{% if page.tags != nil %}
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
{% endif %}
{% if page.description != nil %}
<meta name="description" content="{{ page.description }}">
{% endif %}
- <title>mhack - {{ page.title }}</title>
+ <title>{{ page.title }} - Marcos Hack</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/assets/css/bootstrap.css" rel="stylesheet">
<link href="/assets/css/custom.css" rel="stylesheet">
{% include ga.html %}
</head>
<body>
{% include navbar.html %}
<br/>
<br/>
<div class="container">
<div class="row">
<!-- main content -->
<div class="span8">
{{ content }}
</div>
{% include sidebar.html %}
</div>
</div>
<script src="/assets/js/jquery-1.9.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
</body>
</html>
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
ab668915a4f2b9abcde6ee3556309d2918ed120f
|
link de autor para o google+ nos posts
|
diff --git a/_layouts/post.html b/_layouts/post.html
index bb1f51e..c0e5f34 100644
--- a/_layouts/post.html
+++ b/_layouts/post.html
@@ -1,20 +1,23 @@
---
layout: default
---
<!-- post header -->
<div class="page-header">
<h1><a href="{{ page.url }}">{{ page.title }}</a></h1>
- <p class="small"><i class="icon-time"></i> {{ page.date | date: "%Y-%m-%d %H:%M" }}</p>
+ <small class="muted">
+ {{ page.date | date: "%Y-%m-%d %H:%M" }} |
+ <a href="https://plus.google.com/101876381204467415756?rel=author">Marcos Hack</a>
+ </small>
</div>
<div class="post">
{{ content }}
</div>
{% include facebook_div.html %}
{% include facebook_script.html %}
<br/> <!-- uhhhh -->
{% include disqus_div.html %}
{% include disqus_script.html %}
|
marcoshack/marcoshack.github.io
|
55e85b05a661ba80a2b0e782c668cc8ae27a5540
|
um pouco mais de estilo na home
|
diff --git a/assets/css/custom.css b/assets/css/custom.css
index e69de29..acdaedb 100644
--- a/assets/css/custom.css
+++ b/assets/css/custom.css
@@ -0,0 +1,3 @@
+a.no_decoration {
+ text-decoration: none;
+}
\ No newline at end of file
diff --git a/index.html b/index.html
index a8943b2..d0e717e 100644
--- a/index.html
+++ b/index.html
@@ -1,24 +1,25 @@
---
layout: default
title: home
---
{% for post in paginator.posts %}
<div class="row">
<div class="span2 hidden-phone">
{% if post.image != nil %}
<img src="/images/{{ post.image }}" />
{% endif %}
</div>
<div class="span6">
<h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
- <p class="small"><i class="icon-time"></i> {{ post.date | date: "%Y-%m-%d %H:%M" }}</p>
<div class="post_content">
- {{ post.content | strip_html | truncatewords: 30 }}
- <a href="{{ post.url }}"><span class="text-info">continuar lendo</span></a>
+ <blockquote>
+ <p>{{ post.content | strip_html | truncatewords: 30 }}</p>
+ <small>{{ post.date | date: "%Y-%m-%d" }}</small>
+ </blockquote>
</div>
</div>
</div>
{% endfor %}
{% include pagination.html %}
|
marcoshack/marcoshack.github.io
|
8c9a6a4cd89803f09d46ce568c52401e84cdc429
|
redirecionamento do post 'o ze e o git'
|
diff --git a/.htaccess b/.htaccess
index ed388cf..8ab4a3e 100644
--- a/.htaccess
+++ b/.htaccess
@@ -1,23 +1,23 @@
<If "%{HTTP_HOST} != 'mhack.com'">
RedirectMatch permanent /(.*) http://mhack.com/$1
</If>
RedirectPermanent /2012/10/java-jdk-15-no-os-x-lion-e-mountain-lion.html /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion.html
RedirectPermanent /2012/08/mongo-on-rails-no-mongodb-sao-paulo.html /2012/09/mongo-on-rails-mongodb-sao-paulo.html
RedirectPermanent /2010/08/monitoracao-da-jvm-via-jmx-e-snmp.html /2012/05/monitoracao-jvm-com-jmx-e-snmp.html
RedirectPermanent /2009/10/japan-linux-symposium-e-lancamento-do.html /2009/10/japan-linux-symposium-lancamento-windows7.html
RedirectPermanent /2009/06/definicao-de-cloud-computing-pelo-nist.html /2009/06/definicao-de-cloud-computing-nist.html
RedirectPermanent /2009/05/amazon-web-services-leva-educacao-as.html /2009/05/amazon-web-services-leva-a-educacao-as-nuvens.html
RedirectPermanent /2008/12/segunda-via-do-documento-do-carro-em.html /2008/12/segunda-via-documento-carro-sao-paulo.html
RedirectPermanent /2012/12/jmeter-reports/ /2012/12/jmeter-reports.html
RedirectPermanent /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion/ /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion.html
RedirectPermanent /2012/09/mongo-on-rails-mongodb-sao-paulo/ /2012/09/mongo-on-rails-mongodb-sao-paulo.html
RedirectPermanent /2012/05/monitoracao-jvm-com-jmx-e-snmp/ /2012/05/monitoracao-jvm-com-jmx-e-snmp.html
RedirectPermanent /2010/01/campus-party-2010-dia-1/ /2010/01/campus-party-2010-dia-1.html
RedirectPermanent /2009/10/japan-linux-symposium-lancamento-windows7/ /2009/10/japan-linux-symposium-lancamento-windows7.html
RedirectPermanent /2009/06/definicao-de-cloud-computing-nist/ /2009/06/definicao-de-cloud-computing-nist.html
RedirectPermanent /2009/05/amazon-web-services-leva-a-educacao-as-nuvens/ /2009/05/amazon-web-services-leva-a-educacao-as-nuvens.html
RedirectPermanent /2009/03/ip-communications-2008/ /2009/03/ip-communications-2008.html
RedirectPermanent /2008/12/segunda-via-documento-carro-sao-paulo/ /2008/12/segunda-via-documento-carro-sao-paulo.html
RedirectPermanent /contato /contato.html
-RedirectPermanent /2009/12/o-ze-o-git-e-o-github /2009/12/o-ze-o-git-e-o-github.html
\ No newline at end of file
+RedirectPermanent /2009/12/o-ze-o-git-e-o-github/ /2009/12/o-ze-o-git-e-o-github.html
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
1cae757afeacd7569cde2d8edeb6c3a116a16551
|
redirecionamento do post 'o ze e o git'
|
diff --git a/.htaccess b/.htaccess
index 2b2d77e..ed388cf 100644
--- a/.htaccess
+++ b/.htaccess
@@ -1,22 +1,23 @@
<If "%{HTTP_HOST} != 'mhack.com'">
RedirectMatch permanent /(.*) http://mhack.com/$1
</If>
RedirectPermanent /2012/10/java-jdk-15-no-os-x-lion-e-mountain-lion.html /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion.html
RedirectPermanent /2012/08/mongo-on-rails-no-mongodb-sao-paulo.html /2012/09/mongo-on-rails-mongodb-sao-paulo.html
RedirectPermanent /2010/08/monitoracao-da-jvm-via-jmx-e-snmp.html /2012/05/monitoracao-jvm-com-jmx-e-snmp.html
RedirectPermanent /2009/10/japan-linux-symposium-e-lancamento-do.html /2009/10/japan-linux-symposium-lancamento-windows7.html
RedirectPermanent /2009/06/definicao-de-cloud-computing-pelo-nist.html /2009/06/definicao-de-cloud-computing-nist.html
RedirectPermanent /2009/05/amazon-web-services-leva-educacao-as.html /2009/05/amazon-web-services-leva-a-educacao-as-nuvens.html
RedirectPermanent /2008/12/segunda-via-do-documento-do-carro-em.html /2008/12/segunda-via-documento-carro-sao-paulo.html
RedirectPermanent /2012/12/jmeter-reports/ /2012/12/jmeter-reports.html
RedirectPermanent /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion/ /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion.html
RedirectPermanent /2012/09/mongo-on-rails-mongodb-sao-paulo/ /2012/09/mongo-on-rails-mongodb-sao-paulo.html
RedirectPermanent /2012/05/monitoracao-jvm-com-jmx-e-snmp/ /2012/05/monitoracao-jvm-com-jmx-e-snmp.html
RedirectPermanent /2010/01/campus-party-2010-dia-1/ /2010/01/campus-party-2010-dia-1.html
RedirectPermanent /2009/10/japan-linux-symposium-lancamento-windows7/ /2009/10/japan-linux-symposium-lancamento-windows7.html
RedirectPermanent /2009/06/definicao-de-cloud-computing-nist/ /2009/06/definicao-de-cloud-computing-nist.html
RedirectPermanent /2009/05/amazon-web-services-leva-a-educacao-as-nuvens/ /2009/05/amazon-web-services-leva-a-educacao-as-nuvens.html
RedirectPermanent /2009/03/ip-communications-2008/ /2009/03/ip-communications-2008.html
RedirectPermanent /2008/12/segunda-via-documento-carro-sao-paulo/ /2008/12/segunda-via-documento-carro-sao-paulo.html
-RedirectPermanent /contato /contato.html
\ No newline at end of file
+RedirectPermanent /contato /contato.html
+RedirectPermanent /2009/12/o-ze-o-git-e-o-github /2009/12/o-ze-o-git-e-o-github.html
\ No newline at end of file
|
marcoshack/marcoshack.github.io
|
0eea4a2b17eed5d2df04fcf391543302d2d96f7b
|
remocao da sincronizacao de repositorios remotos do post-receive
|
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index 8341701..4916c46 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,44 +1,37 @@
#!/usr/bin/env bash
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
[email protected]:marcoshack/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
function log_step {
echo -e "\e[1;33m--> ${1}\e[00m"
}
log_step "Setting up local workspace"
git clone $GIT_REPO $TMP_GIT_CLONE
log_step "Updating dependencies"
cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
log_step "Updating site"
$JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW
-log_step "Syincing remote repositories"
-for REPO in $REMOTE_REPOS; do
- cd $TMP_GIT_CLONE
- git push --mirror $REPO
-done
-
log_step "Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
marcoshack/marcoshack.github.io
|
4373e0ee0dca8b7fdb23d38c1859d3590815ab4c
|
correcao na declaracao do interpretador do post-receive (#!)
|
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index dfb770a..8341701 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,44 +1,44 @@
-#!/usr/bin/bash
+#!/usr/bin/env bash
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
[email protected]:marcoshack/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
function log_step {
echo -e "\e[1;33m--> ${1}\e[00m"
}
log_step "Setting up local workspace"
git clone $GIT_REPO $TMP_GIT_CLONE
log_step "Updating dependencies"
cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
log_step "Updating site"
$JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW
log_step "Syincing remote repositories"
for REPO in $REMOTE_REPOS; do
cd $TMP_GIT_CLONE
git push --mirror $REPO
done
log_step "Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
marcoshack/marcoshack.github.io
|
32a176d80b00663a96d4e1bbf64c4205a20a556a
|
cores no hook post-receive
|
diff --git a/Rakefile b/Rakefile
index 4c1841f..91cd9c1 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,18 +1,14 @@
require 'rubygems'
require 'rake'
task :server do
sh "jekyll --server --auto --future"
end
-namespace :site do
- task :deploy do
- sh "git push aws master"
- end
+task :deploy => [ :update_git_hooks ] do
+ sh "git push aws master"
end
-namespace :git do
- task :update_hooks do
- sh "scp _deploy/git-post-receive.sh mhack.com:~/repo/mhack.git/hooks/post-receive"
- end
+task :update_git_hooks do
+ sh "scp _deploy/git-post-receive.sh mhack.com:~/repo/mhack.git/hooks/post-receive"
end
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index c72db07..dfb770a 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,39 +1,44 @@
+#!/usr/bin/bash
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
[email protected]:marcoshack/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
-echo "--> Setting up local workspace"
+function log_step {
+ echo -e "\e[1;33m--> ${1}\e[00m"
+}
+
+log_step "Setting up local workspace"
git clone $GIT_REPO $TMP_GIT_CLONE
-echo "--> Updating dependencies"
+log_step "Updating dependencies"
cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
-echo "--> Updating site"
+log_step "Updating site"
$JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW
-echo "--> Syincing remote repositories"
+log_step "Syincing remote repositories"
for REPO in $REMOTE_REPOS; do
cd $TMP_GIT_CLONE
git push --mirror $REPO
done
-echo "--> Cleaning up local workspace"
+log_step "Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
marcoshack/marcoshack.github.io
|
d8cfd19dfb3be57f570f9e00179d1711e610853b
|
bundle install --quiet
|
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index ac7053d..c72db07 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,37 +1,39 @@
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
[email protected]:marcoshack/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
echo "--> Setting up local workspace"
git clone $GIT_REPO $TMP_GIT_CLONE
-cd $TMP_GIT_CLONE && $BUNDLE_CMD install
+echo "--> Updating dependencies"
+cd $TMP_GIT_CLONE && $BUNDLE_CMD install --quiet
echo "--> Updating site"
$JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW
echo "--> Syincing remote repositories"
for REPO in $REMOTE_REPOS; do
- cd $TMP_GIT_CLONE && git push --mirror $REPO
+ cd $TMP_GIT_CLONE
+ git push --mirror $REPO
done
echo "--> Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
marcoshack/marcoshack.github.io
|
beca807c28c536e2923c7304bcc362cef81e5e41
|
remocao de testes nos comandos do post-receive.sh, nao estao funcionando
|
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh
index 0d40a5d..ac7053d 100644
--- a/_deploy/git-post-receive.sh
+++ b/_deploy/git-post-receive.sh
@@ -1,44 +1,37 @@
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
# <oldrev> <newrev> <refname>
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
JEKYLL_CMD=$HOME/bin/jekyll
BUNDLE_CMD=$HOME/bin/bundle
GIT_REPO=$HOME/repo/mhack.git
[email protected]:marcoshack/mhack.git
TMP_GIT_CLONE=$HOME/tmp/mhack
PUBLIC_WWW=$HOME/www/mhack
-function check_command {
- if [[ $? != 0 ]]; then exit 1; fi
-}
-
echo "--> Setting up local workspace"
git clone $GIT_REPO $TMP_GIT_CLONE
-check_command
cd $TMP_GIT_CLONE && $BUNDLE_CMD install
-check_command
echo "--> Updating site"
$JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW
-check_command
echo "--> Syincing remote repositories"
for REPO in $REMOTE_REPOS; do
cd $TMP_GIT_CLONE && git push --mirror $REPO
done
echo "--> Cleaning up local workspace"
rm -Rf $TMP_GIT_CLONE
exit 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.